Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.868
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.868 ! raeburn 4: # $Id: lonnet.pm,v 1.867 2007/04/10 20:29:53 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.15 www 34: use HTTP::Headers;
1.486 www 35: use HTTP::Date;
36: # use Date::Parse;
1.11 www 37: use vars
1.847 albertel 38: qw(%perlvar %badServerCache %spareid
1.845 albertel 39: %pr %prp $memcache %packagetab
1.662 raeburn 40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
1.741 raeburn 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685 raeburn 42: $tmpdir $_64bit %env);
1.403 www 43:
1.1 albertel 44: use IO::Socket;
1.31 www 45: use GDBM_File;
1.208 albertel 46: use HTML::LCParser;
1.637 raeburn 47: use HTML::Parser;
1.88 www 48: use Fcntl qw(:flock);
1.557 albertel 49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539 albertel 50: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 51: use Cache::Memcached;
1.676 albertel 52: use Digest::MD5;
1.790 albertel 53: use Math::Random;
1.807 albertel 54: use LONCAPA qw(:DEFAULT :match);
1.740 www 55: use LONCAPA::Configuration;
1.676 albertel 56:
1.195 www 57: my $readit;
1.550 foxr 58: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 59:
1.619 albertel 60: require Exporter;
61:
62: our @ISA = qw (Exporter);
63: our @EXPORT = qw(%env);
64:
1.449 matthew 65: =pod
66:
67: =head1 Package Variables
68:
69: These are largely undocumented, so if you decipher one please note it here.
70:
71: =over 4
72:
73: =item $processmarker
74:
75: Contains the time this process was started and this servers host id.
76:
77: =item $dumpcount
78:
79: Counts the number of times a message log flush has been attempted (regardless
80: of success) by this process. Used as part of the filename when messages are
81: delayed.
82:
83: =back
84:
85: =cut
86:
87:
1.1 albertel 88: # --------------------------------------------------------------------- Logging
1.729 www 89: {
90: my $logid;
91: sub instructor_log {
92: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
93: $logid++;
94: my $id=time().'00000'.$$.'00000'.$logid;
95: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 96: { $id => {
97: 'exe_uname' => $env{'user.name'},
98: 'exe_udom' => $env{'user.domain'},
99: 'exe_time' => time(),
100: 'exe_ip' => $ENV{'REMOTE_ADDR'},
101: 'delflag' => $delflag,
102: 'logentry' => $storehash,
103: 'uname' => $uname,
104: 'udom' => $udom,
105: }
106: },
1.729 www 107: $env{'course.'.$env{'request.course.id'}.'.domain'},
108: $env{'course.'.$env{'request.course.id'}.'.num'}
109: );
110: }
111: }
1.1 albertel 112:
1.163 harris41 113: sub logtouch {
114: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 115: unless (-e "$execdir/logs/lonnet.log") {
116: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 117: close $fh;
118: }
119: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
120: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
121: }
122:
1.1 albertel 123: sub logthis {
124: my $message=shift;
125: my $execdir=$perlvar{'lonDaemons'};
126: my $now=time;
127: my $local=localtime($now);
1.448 albertel 128: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
129: print $fh "$local ($$): $message\n";
130: close($fh);
131: }
1.1 albertel 132: return 1;
133: }
134:
135: sub logperm {
136: my $message=shift;
137: my $execdir=$perlvar{'lonDaemons'};
138: my $now=time;
139: my $local=localtime($now);
1.448 albertel 140: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
141: print $fh "$now:$message:$local\n";
142: close($fh);
143: }
1.1 albertel 144: return 1;
145: }
146:
1.850 albertel 147: sub create_connection {
1.853 albertel 148: my ($hostname,$lonid) = @_;
1.851 albertel 149: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 150: Type => SOCK_STREAM,
151: Timeout => 10);
152: return 0 if (!$client);
1.854 albertel 153: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850 albertel 154: my $result = <$client>;
155: chomp($result);
156: return 1 if ($result eq 'done');
157: return 0;
158: }
159:
160:
1.1 albertel 161: # -------------------------------------------------- Non-critical communication
162: sub subreply {
163: my ($cmd,$server)=@_;
1.838 albertel 164: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 165: #
166: # With loncnew process trimming, there's a timing hole between lonc server
167: # process exit and the master server picking up the listen on the AF_UNIX
168: # socket. In that time interval, a lock file will exist:
169:
170: my $lockfile=$peerfile.".lock";
171: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
172: sleep(1);
173: }
174: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 175: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 176: #
1.550 foxr 177: # We'll give the connection a few tries before abandoning it. If
178: # connection is not possible, we'll con_lost back to the client.
179: #
180: my $client;
181: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
182: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
183: Type => SOCK_STREAM,
184: Timeout => 10);
185: if($client) {
186: last; # Connected!
1.850 albertel 187: } else {
1.853 albertel 188: &create_connection(&hostname($server),$server);
1.550 foxr 189: }
1.850 albertel 190: sleep(1); # Try again later if failed connection.
1.550 foxr 191: }
192: my $answer;
193: if ($client) {
1.704 albertel 194: print $client "sethost:$server:$cmd\n";
1.550 foxr 195: $answer=<$client>;
196: if (!$answer) { $answer="con_lost"; }
197: chomp($answer);
198: } else {
199: $answer = 'con_lost'; # Failed connection.
200: }
1.1 albertel 201: return $answer;
202: }
203:
204: sub reply {
205: my ($cmd,$server)=@_;
1.838 albertel 206: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 207: my $answer=subreply($cmd,$server);
1.65 www 208: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 209: &logthis("<font color=\"blue\">WARNING:".
1.12 www 210: " $cmd to $server returned $answer</font>");
211: }
1.1 albertel 212: return $answer;
213: }
214:
215: # ----------------------------------------------------------- Send USR1 to lonc
216:
217: sub reconlonc {
1.836 www 218: &logthis("Trying to reconnect lonc");
1.1 albertel 219: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 220: if (open(my $fh,"<$loncfile")) {
1.1 albertel 221: my $loncpid=<$fh>;
222: chomp($loncpid);
223: if (kill 0 => $loncpid) {
224: &logthis("lonc at pid $loncpid responding, sending USR1");
225: kill USR1 => $loncpid;
226: sleep 1;
1.836 www 227: } else {
1.12 www 228: &logthis(
1.672 albertel 229: "<font color=\"blue\">WARNING:".
1.12 www 230: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 231: }
232: } else {
1.836 www 233: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 234: }
235: }
236:
237: # ------------------------------------------------------ Critical communication
1.12 www 238:
1.1 albertel 239: sub critical {
240: my ($cmd,$server)=@_;
1.838 albertel 241: unless (&hostname($server)) {
1.672 albertel 242: &logthis("<font color=\"blue\">WARNING:".
1.89 www 243: " Critical message to unknown server ($server)</font>");
244: return 'no_such_host';
245: }
1.1 albertel 246: my $answer=reply($cmd,$server);
247: if ($answer eq 'con_lost') {
248: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 249: my $answer=reply($cmd,$server);
1.1 albertel 250: if ($answer eq 'con_lost') {
251: my $now=time;
252: my $middlename=$cmd;
1.5 www 253: $middlename=substr($middlename,0,16);
1.1 albertel 254: $middlename=~s/\W//g;
255: my $dfilename=
1.305 www 256: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
257: $dumpcount++;
1.1 albertel 258: {
1.448 albertel 259: my $dfh;
260: if (open($dfh,">$dfilename")) {
261: print $dfh "$cmd\n";
262: close($dfh);
263: }
1.1 albertel 264: }
265: sleep 2;
266: my $wcmd='';
267: {
1.448 albertel 268: my $dfh;
269: if (open($dfh,"<$dfilename")) {
270: $wcmd=<$dfh>;
271: close($dfh);
272: }
1.1 albertel 273: }
274: chomp($wcmd);
1.7 www 275: if ($wcmd eq $cmd) {
1.672 albertel 276: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 277: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 278: &logperm("D:$server:$cmd");
279: return 'con_delayed';
280: } else {
1.672 albertel 281: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 282: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 283: &logperm("F:$server:$cmd");
284: return 'con_failed';
285: }
286: }
287: }
288: return $answer;
1.405 albertel 289: }
290:
1.755 albertel 291: # ------------------------------------------- check if return value is an error
292:
293: sub error {
294: my ($result) = @_;
1.756 albertel 295: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 296: if ($2 == 2) { return undef; }
297: return $1;
298: }
299: return undef;
300: }
301:
1.783 albertel 302: sub convert_and_load_session_env {
303: my ($lonidsdir,$handle)=@_;
304: my @profile;
305: {
306: open(my $idf,"$lonidsdir/$handle.id");
307: flock($idf,LOCK_SH);
308: @profile=<$idf>;
309: close($idf);
310: }
311: my %temp_env;
312: foreach my $line (@profile) {
1.786 albertel 313: if ($line !~ m/=/) {
314: return 0;
315: }
1.783 albertel 316: chomp($line);
317: my ($envname,$envvalue)=split(/=/,$line,2);
318: $temp_env{&unescape($envname)} = &unescape($envvalue);
319: }
320: unlink("$lonidsdir/$handle.id");
321: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
322: 0640)) {
323: %disk_env = %temp_env;
324: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
325: untie(%disk_env);
326: }
1.786 albertel 327: return 1;
1.783 albertel 328: }
329:
1.374 www 330: # ------------------------------------------- Transfer profile into environment
1.780 albertel 331: my $env_loaded;
332: sub transfer_profile_to_env {
1.788 albertel 333: my ($lonidsdir,$handle,$force_transfer) = @_;
334: if (!$force_transfer && $env_loaded) { return; }
1.374 www 335:
1.720 albertel 336: if (!defined($lonidsdir)) {
337: $lonidsdir = $perlvar{'lonIDsDir'};
338: }
339: if (!defined($handle)) {
340: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
341: }
342:
1.786 albertel 343: my $convert;
344: {
345: open(my $idf,"$lonidsdir/$handle.id");
346: flock($idf,LOCK_SH);
347: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
348: &GDBM_READER(),0640)) {
349: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
350: untie(%disk_env);
351: } else {
352: $convert = 1;
353: }
354: }
355: if ($convert) {
356: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
357: &logthis("Failed to load session, or convert session.");
358: }
1.374 www 359: }
1.783 albertel 360:
1.786 albertel 361: my %remove;
1.783 albertel 362: while ( my $envname = each(%env) ) {
1.433 matthew 363: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
364: if ($time < time-300) {
1.783 albertel 365: $remove{$key}++;
1.433 matthew 366: }
367: }
368: }
1.783 albertel 369:
1.619 albertel 370: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 371: $env_loaded=1;
1.783 albertel 372: foreach my $expired_key (keys(%remove)) {
1.433 matthew 373: &delenv($expired_key);
1.374 www 374: }
1.1 albertel 375: }
376:
1.830 albertel 377: sub timed_flock {
378: my ($file,$lock_type) = @_;
379: my $failed=0;
380: eval {
381: local $SIG{__DIE__}='DEFAULT';
382: local $SIG{ALRM}=sub {
383: $failed=1;
384: die("failed lock");
385: };
386: alarm(13);
387: flock($file,$lock_type);
388: alarm(0);
389: };
390: if ($failed) {
391: return undef;
392: } else {
393: return 1;
394: }
395: }
396:
1.5 www 397: # ---------------------------------------------------------- Append Environment
398:
399: sub appenv {
1.6 www 400: my %newenv=@_;
1.692 albertel 401: foreach my $key (keys(%newenv)) {
402: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 403: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 404: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 405: .'</font>');
1.692 albertel 406: delete($newenv{$key});
1.35 www 407: } else {
1.692 albertel 408: $env{$key}=$newenv{$key};
1.35 www 409: }
1.191 harris41 410: }
1.830 albertel 411: open(my $env_file,$env{'user.environment'});
412: if (&timed_flock($env_file,LOCK_EX)
413: &&
414: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
415: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 416: while (my ($key,$value) = each(%newenv)) {
417: $disk_env{$key} = $value;
1.448 albertel 418: }
1.783 albertel 419: untie(%disk_env);
1.56 www 420: }
421: return 'ok';
422: }
423: # ----------------------------------------------------- Delete from Environment
424:
425: sub delenv {
426: my $delthis=shift;
427: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 428: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 429: "Attempt to delete from environment ".$delthis);
430: return 'error';
431: }
1.830 albertel 432: open(my $env_file,$env{'user.environment'});
433: if (&timed_flock($env_file,LOCK_EX)
434: &&
435: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
436: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 437: foreach my $key (keys(%disk_env)) {
438: if ($key=~/^$delthis/) {
1.619 albertel 439: delete($env{$key});
1.783 albertel 440: delete($disk_env{$key});
1.473 matthew 441: }
1.448 albertel 442: }
1.783 albertel 443: untie(%disk_env);
1.5 www 444: }
445: return 'ok';
1.369 albertel 446: }
447:
1.790 albertel 448: sub get_env_multiple {
449: my ($name) = @_;
450: my @values;
451: if (defined($env{$name})) {
452: # exists is it an array
453: if (ref($env{$name})) {
454: @values=@{ $env{$name} };
455: } else {
456: $values[0]=$env{$name};
457: }
458: }
459: return(@values);
460: }
461:
1.369 albertel 462: # ------------------------------------------ Find out current server userload
463: # there is a copy in lond
464: sub userload {
465: my $numusers=0;
466: {
467: opendir(LONIDS,$perlvar{'lonIDsDir'});
468: my $filename;
469: my $curtime=time;
470: while ($filename=readdir(LONIDS)) {
471: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 472: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 473: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 474: }
475: closedir(LONIDS);
476: }
477: my $userloadpercent=0;
478: my $maxuserload=$perlvar{'lonUserLoadLim'};
479: if ($maxuserload) {
1.371 albertel 480: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 481: }
1.372 albertel 482: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 483: return $userloadpercent;
1.283 www 484: }
485:
486: # ------------------------------------------ Fight off request when overloaded
487:
488: sub overloaderror {
489: my ($r,$checkserver)=@_;
490: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
491: my $loadavg;
492: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 493: open(my $loadfile,'/proc/loadavg');
1.283 www 494: $loadavg=<$loadfile>;
495: $loadavg =~ s/\s.*//g;
1.285 matthew 496: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 497: close($loadfile);
1.283 www 498: } else {
499: $loadavg=&reply('load',$checkserver);
500: }
1.285 matthew 501: my $overload=$loadavg-100;
1.283 www 502: if ($overload>0) {
1.285 matthew 503: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 504: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 505: return 413;
1.283 www 506: }
507: return '';
1.5 www 508: }
1.1 albertel 509:
510: # ------------------------------ Find server with least workload from spare.tab
1.11 www 511:
1.1 albertel 512: sub spareserver {
1.670 albertel 513: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 514: my $spare_server;
1.370 albertel 515: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 516: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
517: : $userloadpercent;
518:
519: foreach my $try_server (@{ $spareid{'primary'} }) {
520: ($spare_server, $lowest_load) =
521: &compare_server_load($try_server, $spare_server, $lowest_load);
522: }
523:
524: my $found_server = ($spare_server ne '' && $lowest_load < 100);
525:
526: if (!$found_server) {
527: foreach my $try_server (@{ $spareid{'default'} }) {
528: ($spare_server, $lowest_load) =
529: &compare_server_load($try_server, $spare_server, $lowest_load);
530: }
531: }
532:
533: if (!$want_server_name) {
1.838 albertel 534: $spare_server="http://".&hostname($spare_server);
1.784 albertel 535: }
536: return $spare_server;
537: }
538:
539: sub compare_server_load {
540: my ($try_server, $spare_server, $lowest_load) = @_;
541:
542: my $loadans = &reply('load', $try_server);
543: my $userloadans = &reply('userload',$try_server);
544:
545: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
546: next; #didn't get a number from the server
547: }
548:
549: my $load;
550: if ($loadans =~ /\d/) {
551: if ($userloadans =~ /\d/) {
552: #both are numbers, pick the bigger one
553: $load = ($loadans > $userloadans) ? $loadans
554: : $userloadans;
1.411 albertel 555: } else {
1.784 albertel 556: $load = $loadans;
1.411 albertel 557: }
1.784 albertel 558: } else {
559: $load = $userloadans;
560: }
561:
562: if (($load =~ /\d/) && ($load < $lowest_load)) {
563: $spare_server = $try_server;
564: $lowest_load = $load;
1.370 albertel 565: }
1.784 albertel 566: return ($spare_server,$lowest_load);
1.202 matthew 567: }
568: # --------------------------------------------- Try to change a user's password
569:
570: sub changepass {
1.799 raeburn 571: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 572: $currentpass = &escape($currentpass);
573: $newpass = &escape($newpass);
1.799 raeburn 574: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 575: $server);
576: if (! $answer) {
577: &logthis("No reply on password change request to $server ".
578: "by $uname in domain $udom.");
579: } elsif ($answer =~ "^ok") {
580: &logthis("$uname in $udom successfully changed their password ".
581: "on $server.");
582: } elsif ($answer =~ "^pwchange_failure") {
583: &logthis("$uname in $udom was unable to change their password ".
584: "on $server. The action was blocked by either lcpasswd ".
585: "or pwchange");
586: } elsif ($answer =~ "^non_authorized") {
587: &logthis("$uname in $udom did not get their password correct when ".
588: "attempting to change it on $server.");
589: } elsif ($answer =~ "^auth_mode_error") {
590: &logthis("$uname in $udom attempted to change their password despite ".
591: "not being locally or internally authenticated on $server.");
592: } elsif ($answer =~ "^unknown_user") {
593: &logthis("$uname in $udom attempted to change their password ".
594: "on $server but were unable to because $server is not ".
595: "their home server.");
596: } elsif ($answer =~ "^refused") {
597: &logthis("$server refused to change $uname in $udom password because ".
598: "it was sent an unencrypted request to change the password.");
599: }
600: return $answer;
1.1 albertel 601: }
602:
1.169 harris41 603: # ----------------------- Try to determine user's current authentication scheme
604:
605: sub queryauthenticate {
606: my ($uname,$udom)=@_;
1.456 albertel 607: my $uhome=&homeserver($uname,$udom);
608: if (!$uhome) {
609: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
610: return 'no_host';
611: }
612: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
613: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
614: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 615: }
1.456 albertel 616: return $answer;
1.169 harris41 617: }
618:
1.1 albertel 619: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 620:
1.1 albertel 621: sub authenticate {
622: my ($uname,$upass,$udom)=@_;
1.807 albertel 623: $upass=&escape($upass);
624: $uname= &LONCAPA::clean_username($uname);
1.836 www 625: my $uhome=&homeserver($uname,$udom,1);
626: if ((!$uhome) || ($uhome eq 'no_host')) {
627: # Maybe the machine was offline and only re-appeared again recently?
628: &reconlonc();
629: # One more
630: my $uhome=&homeserver($uname,$udom,1);
631: if ((!$uhome) || ($uhome eq 'no_host')) {
632: &logthis("User $uname at $udom is unknown in authenticate");
633: }
1.471 albertel 634: return 'no_host';
1.1 albertel 635: }
1.471 albertel 636: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
637: if ($answer eq 'authorized') {
638: &logthis("User $uname at $udom authorized by $uhome");
639: return $uhome;
640: }
641: if ($answer eq 'non_authorized') {
642: &logthis("User $uname at $udom rejected by $uhome");
643: return 'no_host';
1.9 www 644: }
1.471 albertel 645: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 646: return 'no_host';
647: }
648:
649: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 650:
1.599 albertel 651: my %homecache;
1.1 albertel 652: sub homeserver {
1.230 stredwic 653: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 654: my $index="$uname:$udom";
1.426 albertel 655:
1.599 albertel 656: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 657:
658: my %servers = &get_servers($udom,'library');
659: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 660: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 661: exists($badServerCache{$tryserver}));
1.841 albertel 662:
663: my $answer=reply("home:$udom:$uname",$tryserver);
664: if ($answer eq 'found') {
665: delete($badServerCache{$tryserver});
666: return $homecache{$index}=$tryserver;
667: } elsif ($answer eq 'no_host') {
668: $badServerCache{$tryserver}=1;
669: }
1.1 albertel 670: }
671: return 'no_host';
1.70 www 672: }
673:
674: # ------------------------------------- Find the usernames behind a list of IDs
675:
676: sub idget {
677: my ($udom,@ids)=@_;
678: my %returnhash=();
679:
1.841 albertel 680: my %servers = &get_servers($udom,'library');
681: foreach my $tryserver (keys(%servers)) {
682: my $idlist=join('&',@ids);
683: $idlist=~tr/A-Z/a-z/;
684: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
685: my @answer=();
686: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
687: @answer=split(/\&/,$reply);
688: } ;
689: my $i;
690: for ($i=0;$i<=$#ids;$i++) {
691: if ($answer[$i]) {
692: $returnhash{$ids[$i]}=$answer[$i];
693: }
694: }
695: }
1.70 www 696: return %returnhash;
697: }
698:
699: # ------------------------------------- Find the IDs behind a list of usernames
700:
701: sub idrget {
702: my ($udom,@unames)=@_;
703: my %returnhash=();
1.800 albertel 704: foreach my $uname (@unames) {
705: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 706: }
1.70 www 707: return %returnhash;
708: }
709:
710: # ------------------------------- Store away a list of names and associated IDs
711:
712: sub idput {
713: my ($udom,%ids)=@_;
714: my %servers=();
1.800 albertel 715: foreach my $uname (keys(%ids)) {
716: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
717: my $uhom=&homeserver($uname,$udom);
1.70 www 718: if ($uhom ne 'no_host') {
1.800 albertel 719: my $id=&escape($ids{$uname});
1.70 www 720: $id=~tr/A-Z/a-z/;
1.800 albertel 721: my $esc_unam=&escape($uname);
1.70 www 722: if ($servers{$uhom}) {
1.800 albertel 723: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 724: } else {
1.800 albertel 725: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 726: }
727: }
1.191 harris41 728: }
1.800 albertel 729: foreach my $server (keys(%servers)) {
730: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 731: }
1.344 www 732: }
733:
1.806 raeburn 734: # ------------------------------------------- get items from domain db files
735:
736: sub get_dom {
1.860 raeburn 737: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 738: my $items='';
739: foreach my $item (@$storearr) {
740: $items.=&escape($item).'&';
741: }
742: $items=~s/\&$//;
1.860 raeburn 743: if (!$udom) {
744: $udom=$env{'user.domain'};
745: if (defined(&domain($udom,'primary'))) {
746: $uhome=&domain($udom,'primary');
747: } else {
748: $uhome eq '';
749: }
750: } else {
751: if (!$uhome) {
752: if (defined(&domain($udom,'primary'))) {
753: $uhome=&domain($udom,'primary');
754: }
755: }
756: }
757: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 758: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 759: my %returnhash;
760: if ($rep =~ /^error: 2 /) {
761: return %returnhash;
762: }
1.806 raeburn 763: my @pairs=split(/\&/,$rep);
764: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
765: return @pairs;
766: }
767: my %returnhash=();
768: my $i=0;
769: foreach my $item (@$storearr) {
770: $returnhash{$item}=&thaw_unescape($pairs[$i]);
771: $i++;
772: }
773: return %returnhash;
774: } else {
1.860 raeburn 775: &logthis("get_dom failed - no homeserver and/or domain");
1.806 raeburn 776: }
777: }
778:
779: # -------------------------------------------- put items in domain db files
780:
781: sub put_dom {
1.860 raeburn 782: my ($namespace,$storehash,$udom,$uhome)=@_;
783: if (!$udom) {
784: $udom=$env{'user.domain'};
785: if (defined(&domain($udom,'primary'))) {
786: $uhome=&domain($udom,'primary');
787: } else {
788: $uhome eq '';
789: }
790: } else {
791: if (!$uhome) {
792: if (defined(&domain($udom,'primary'))) {
793: $uhome=&domain($udom,'primary');
794: }
795: }
796: }
797: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 798: my $items='';
799: foreach my $item (keys(%$storehash)) {
800: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
801: }
802: $items=~s/\&$//;
803: return &reply("putdom:$udom:$namespace:$items",$uhome);
804: } else {
1.860 raeburn 805: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 806: }
807: }
808:
1.837 raeburn 809: sub retrieve_inst_usertypes {
810: my ($udom) = @_;
811: my (%returnhash,@order);
1.846 albertel 812: if (defined(&domain($udom,'primary'))) {
813: my $uhome=&domain($udom,'primary');
1.837 raeburn 814: my $rep=&reply("inst_usertypes:$udom",$uhome);
815: my ($hashitems,$orderitems) = split(/:/,$rep);
816: my @pairs=split(/\&/,$hashitems);
817: foreach my $item (@pairs) {
818: my ($key,$value)=split(/=/,$item,2);
819: $key = &unescape($key);
820: next if ($key =~ /^error: 2 /);
821: $returnhash{$key}=&thaw_unescape($value);
822: }
823: my @esc_order = split(/\&/,$orderitems);
824: foreach my $item (@esc_order) {
825: push(@order,&unescape($item));
826: }
827: } else {
828: &logthis("get_dom failed - no primary domain server for $udom");
829: }
830: return (\%returnhash,\@order);
831: }
832:
1.868 ! raeburn 833: sub is_domainimage {
! 834: my ($url) = @_;
! 835: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
! 836: if (&domain($1) ne '') {
! 837: return '1';
! 838: }
! 839: }
! 840: return;
! 841: }
! 842:
1.344 www 843: # --------------------------------------------------- Assign a key to a student
844:
845: sub assign_access_key {
1.364 www 846: #
847: # a valid key looks like uname:udom#comments
848: # comments are being appended
849: #
1.498 www 850: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
851: $kdom=
1.620 albertel 852: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 853: $knum=
1.620 albertel 854: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 855: $cdom=
1.620 albertel 856: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 857: $cnum=
1.620 albertel 858: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
859: $udom=$env{'user.name'} unless (defined($udom));
860: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 861: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 862: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 863: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 864: # assigned to this person
865: # - this should not happen,
1.345 www 866: # unless something went wrong
867: # the first time around
868: # ready to assign
1.364 www 869: $logentry=$1.'; '.$logentry;
1.496 www 870: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 871: $kdom,$knum) eq 'ok') {
1.345 www 872: # key now belongs to user
1.346 www 873: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 874: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
875: &appenv('environment.'.$envkey => $ckey);
876: return 'ok';
877: } else {
878: return
879: 'error: Count not permanently assign key, will need to be re-entered later.';
880: }
881: } else {
882: return 'error: Could not assign key, try again later.';
883: }
1.364 www 884: } elsif (!$existing{$ckey}) {
1.345 www 885: # the key does not exist
886: return 'error: The key does not exist';
887: } else {
888: # the key is somebody else's
889: return 'error: The key is already in use';
890: }
1.344 www 891: }
892:
1.364 www 893: # ------------------------------------------ put an additional comment on a key
894:
895: sub comment_access_key {
896: #
897: # a valid key looks like uname:udom#comments
898: # comments are being appended
899: #
900: my ($ckey,$cdom,$cnum,$logentry)=@_;
901: $cdom=
1.620 albertel 902: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 903: $cnum=
1.620 albertel 904: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 905: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
906: if ($existing{$ckey}) {
907: $existing{$ckey}.='; '.$logentry;
908: # ready to assign
1.367 www 909: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 910: $cdom,$cnum) eq 'ok') {
911: return 'ok';
912: } else {
913: return 'error: Count not store comment.';
914: }
915: } else {
916: # the key does not exist
917: return 'error: The key does not exist';
918: }
919: }
920:
1.344 www 921: # ------------------------------------------------------ Generate a set of keys
922:
923: sub generate_access_keys {
1.364 www 924: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 925: $cdom=
1.620 albertel 926: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 927: $cnum=
1.620 albertel 928: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 929: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 930: unless (($cdom) && ($cnum)) { return 0; }
931: if ($number>10000) { return 0; }
932: sleep(2); # make sure don't get same seed twice
933: srand(time()^($$+($$<<15))); # from "Programming Perl"
934: my $total=0;
935: for (my $i=1;$i<=$number;$i++) {
936: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
937: sprintf("%lx",int(100000*rand)).'-'.
938: sprintf("%lx",int(100000*rand));
939: $newkey=~s/1/g/g; # folks mix up 1 and l
940: $newkey=~s/0/h/g; # and also 0 and O
941: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
942: if ($existing{$newkey}) {
943: $i--;
944: } else {
1.364 www 945: if (&put('accesskeys',
946: { $newkey => '# generated '.localtime().
1.620 albertel 947: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 948: '; '.$logentry },
949: $cdom,$cnum) eq 'ok') {
1.344 www 950: $total++;
951: }
952: }
953: }
1.620 albertel 954: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 955: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
956: return $total;
957: }
958:
959: # ------------------------------------------------------- Validate an accesskey
960:
961: sub validate_access_key {
962: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
963: $cdom=
1.620 albertel 964: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 965: $cnum=
1.620 albertel 966: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
967: $udom=$env{'user.domain'} unless (defined($udom));
968: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 969: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 970: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 971: }
972:
973: # ------------------------------------- Find the section of student in a course
1.652 albertel 974: sub devalidate_getsection_cache {
975: my ($udom,$unam,$courseid)=@_;
976: my $hashid="$udom:$unam:$courseid";
977: &devalidate_cache_new('getsection',$hashid);
978: }
1.298 matthew 979:
1.815 albertel 980: sub courseid_to_courseurl {
981: my ($courseid) = @_;
982: #already url style courseid
983: return $courseid if ($courseid =~ m{^/});
984:
985: if (exists($env{'course.'.$courseid.'.num'})) {
986: my $cnum = $env{'course.'.$courseid.'.num'};
987: my $cdom = $env{'course.'.$courseid.'.domain'};
988: return "/$cdom/$cnum";
989: }
990:
991: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
992: if (exists($courseinfo{'num'})) {
993: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
994: }
995:
996: return undef;
997: }
998:
1.298 matthew 999: sub getsection {
1000: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1001: my $cachetime=1800;
1.551 albertel 1002:
1003: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1004: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1005: if (defined($cached)) { return $result; }
1006:
1.298 matthew 1007: my %Pending;
1008: my %Expired;
1009: #
1010: # Each role can either have not started yet (pending), be active,
1011: # or have expired.
1012: #
1013: # If there is an active role, we are done.
1014: #
1015: # If there is more than one role which has not started yet,
1016: # choose the one which will start sooner
1017: # If there is one role which has not started yet, return it.
1018: #
1019: # If there is more than one expired role, choose the one which ended last.
1020: # If there is a role which has expired, return it.
1021: #
1.815 albertel 1022: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1023: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1024: foreach my $key (keys(%roleshash)) {
1.479 albertel 1025: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1026: my $section=$1;
1027: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1028: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1029: my $now=time;
1.548 albertel 1030: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1031: $Expired{$end}=$section;
1032: next;
1033: }
1.548 albertel 1034: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1035: $Pending{$start}=$section;
1036: next;
1037: }
1.599 albertel 1038: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1039: }
1040: #
1041: # Presumedly there will be few matching roles from the above
1042: # loop and the sorting time will be negligible.
1043: if (scalar(keys(%Pending))) {
1044: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1045: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1046: }
1047: if (scalar(keys(%Expired))) {
1048: my @sorted = sort {$a <=> $b} keys(%Expired);
1049: my $time = pop(@sorted);
1.599 albertel 1050: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1051: }
1.599 albertel 1052: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1053: }
1.70 www 1054:
1.599 albertel 1055: sub save_cache {
1056: &purge_remembered();
1.722 albertel 1057: #&Apache::loncommon::validate_page();
1.620 albertel 1058: undef(%env);
1.780 albertel 1059: undef($env_loaded);
1.599 albertel 1060: }
1.452 albertel 1061:
1.599 albertel 1062: my $to_remember=-1;
1063: my %remembered;
1064: my %accessed;
1065: my $kicks=0;
1066: my $hits=0;
1.849 albertel 1067: sub make_key {
1068: my ($name,$id) = @_;
1069: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1070: return &escape($name.':'.$id);
1071: }
1072:
1.599 albertel 1073: sub devalidate_cache_new {
1074: my ($name,$id,$debug) = @_;
1075: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1076: $id=&make_key($name,$id);
1.599 albertel 1077: $memcache->delete($id);
1078: delete($remembered{$id});
1079: delete($accessed{$id});
1080: }
1081:
1082: sub is_cached_new {
1083: my ($name,$id,$debug) = @_;
1.849 albertel 1084: $id=&make_key($name,$id);
1.599 albertel 1085: if (exists($remembered{$id})) {
1086: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1087: $accessed{$id}=[&gettimeofday()];
1088: $hits++;
1089: return ($remembered{$id},1);
1090: }
1091: my $value = $memcache->get($id);
1092: if (!(defined($value))) {
1093: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1094: return (undef,undef);
1.416 albertel 1095: }
1.599 albertel 1096: if ($value eq '__undef__') {
1097: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1098: $value=undef;
1099: }
1100: &make_room($id,$value,$debug);
1101: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1102: return ($value,1);
1103: }
1104:
1105: sub do_cache_new {
1106: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1107: $id=&make_key($name,$id);
1.599 albertel 1108: my $setvalue=$value;
1109: if (!defined($setvalue)) {
1110: $setvalue='__undef__';
1111: }
1.623 albertel 1112: if (!defined($time) ) {
1113: $time=600;
1114: }
1.599 albertel 1115: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 1116: $memcache->set($id,$setvalue,$time);
1117: # need to make a copy of $value
1118: #&make_room($id,$value,$debug);
1.599 albertel 1119: return $value;
1120: }
1121:
1122: sub make_room {
1123: my ($id,$value,$debug)=@_;
1124: $remembered{$id}=$value;
1125: if ($to_remember<0) { return; }
1126: $accessed{$id}=[&gettimeofday()];
1127: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1128: my $to_kick;
1129: my $max_time=0;
1130: foreach my $other (keys(%accessed)) {
1131: if (&tv_interval($accessed{$other}) > $max_time) {
1132: $to_kick=$other;
1133: $max_time=&tv_interval($accessed{$other});
1134: }
1135: }
1136: delete($remembered{$to_kick});
1137: delete($accessed{$to_kick});
1138: $kicks++;
1139: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1140: return;
1141: }
1142:
1.599 albertel 1143: sub purge_remembered {
1.604 albertel 1144: #&logthis("Tossing ".scalar(keys(%remembered)));
1145: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1146: undef(%remembered);
1147: undef(%accessed);
1.428 albertel 1148: }
1.70 www 1149: # ------------------------------------- Read an entry from a user's environment
1150:
1151: sub userenvironment {
1152: my ($udom,$unam,@what)=@_;
1153: my %returnhash=();
1154: my @answer=split(/\&/,
1155: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1156: &homeserver($unam,$udom)));
1157: my $i;
1158: for ($i=0;$i<=$#what;$i++) {
1159: $returnhash{$what[$i]}=&unescape($answer[$i]);
1160: }
1161: return %returnhash;
1.1 albertel 1162: }
1163:
1.617 albertel 1164: # ---------------------------------------------------------- Get a studentphoto
1165: sub studentphoto {
1166: my ($udom,$unam,$ext) = @_;
1167: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1168: if (defined($env{'request.course.id'})) {
1.708 raeburn 1169: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1170: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1171: return(&retrievestudentphoto($udom,$unam,$ext));
1172: } else {
1173: my ($result,$perm_reqd)=
1.707 albertel 1174: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1175: if ($result eq 'ok') {
1176: if (!($perm_reqd eq 'yes')) {
1177: return(&retrievestudentphoto($udom,$unam,$ext));
1178: }
1179: }
1180: }
1181: }
1182: } else {
1183: my ($result,$perm_reqd) =
1.707 albertel 1184: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1185: if ($result eq 'ok') {
1186: if (!($perm_reqd eq 'yes')) {
1187: return(&retrievestudentphoto($udom,$unam,$ext));
1188: }
1189: }
1190: }
1191: return '/adm/lonKaputt/lonlogo_broken.gif';
1192: }
1193:
1194: sub retrievestudentphoto {
1195: my ($udom,$unam,$ext,$type) = @_;
1196: my $home=&Apache::lonnet::homeserver($unam,$udom);
1197: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1198: if ($ret eq 'ok') {
1199: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1200: if ($type eq 'thumbnail') {
1201: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1202: }
1203: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1204: return $tokenurl;
1205: } else {
1206: if ($type eq 'thumbnail') {
1207: return '/adm/lonKaputt/genericstudent_tn.gif';
1208: } else {
1209: return '/adm/lonKaputt/lonlogo_broken.gif';
1210: }
1.617 albertel 1211: }
1212: }
1213:
1.263 www 1214: # -------------------------------------------------------------------- New chat
1215:
1216: sub chatsend {
1.724 raeburn 1217: my ($newentry,$anon,$group)=@_;
1.620 albertel 1218: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1219: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1220: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1221: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1222: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1223: &escape($newentry)).':'.$group,$chome);
1.292 www 1224: }
1225:
1226: # ------------------------------------------ Find current version of a resource
1227:
1228: sub getversion {
1229: my $fname=&clutter(shift);
1230: unless ($fname=~/^\/res\//) { return -1; }
1231: return ¤tversion(&filelocation('',$fname));
1232: }
1233:
1234: sub currentversion {
1235: my $fname=shift;
1.599 albertel 1236: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1237: if (defined($cached)) { return $result; }
1.292 www 1238: my $author=$fname;
1239: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1240: my ($udom,$uname)=split(/\//,$author);
1241: my $home=homeserver($uname,$udom);
1242: if ($home eq 'no_host') {
1243: return -1;
1244: }
1245: my $answer=reply("currentversion:$fname",$home);
1246: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1247: return -1;
1248: }
1.599 albertel 1249: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1250: }
1251:
1.1 albertel 1252: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1253:
1.1 albertel 1254: sub subscribe {
1255: my $fname=shift;
1.761 raeburn 1256: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1257: $fname=~s/[\n\r]//g;
1.1 albertel 1258: my $author=$fname;
1259: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1260: my ($udom,$uname)=split(/\//,$author);
1261: my $home=homeserver($uname,$udom);
1.335 albertel 1262: if ($home eq 'no_host') {
1263: return 'not_found';
1.1 albertel 1264: }
1265: my $answer=reply("sub:$fname",$home);
1.64 www 1266: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1267: $answer.=' by '.$home;
1268: }
1.1 albertel 1269: return $answer;
1270: }
1271:
1.8 www 1272: # -------------------------------------------------------------- Replicate file
1273:
1274: sub repcopy {
1275: my $filename=shift;
1.23 www 1276: $filename=~s/\/+/\//g;
1.607 raeburn 1277: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1278: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1279: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1280: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1281: return &repcopy_userfile($filename);
1282: }
1.532 albertel 1283: $filename=~s/[\n\r]//g;
1.8 www 1284: my $transname="$filename.in.transfer";
1.828 www 1285: # FIXME: this should flock
1.607 raeburn 1286: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1287: my $remoteurl=subscribe($filename);
1.64 www 1288: if ($remoteurl =~ /^con_lost by/) {
1289: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1290: return 'unavailable';
1.8 www 1291: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1292: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1293: return 'not_found';
1.64 www 1294: } elsif ($remoteurl =~ /^rejected by/) {
1295: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1296: return 'forbidden';
1.20 www 1297: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1298: return 'ok';
1.8 www 1299: } else {
1.290 www 1300: my $author=$filename;
1301: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1302: my ($udom,$uname)=split(/\//,$author);
1303: my $home=homeserver($uname,$udom);
1304: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1305: my @parts=split(/\//,$filename);
1306: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1307: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1308: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1309: return 'bad_request';
1.8 www 1310: }
1311: my $count;
1312: for ($count=5;$count<$#parts;$count++) {
1313: $path.="/$parts[$count]";
1314: if ((-e $path)!=1) {
1315: mkdir($path,0777);
1316: }
1317: }
1318: my $ua=new LWP::UserAgent;
1319: my $request=new HTTP::Request('GET',"$remoteurl");
1320: my $response=$ua->request($request,$transname);
1321: if ($response->is_error()) {
1322: unlink($transname);
1323: my $message=$response->status_line;
1.672 albertel 1324: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1325: ." LWP get: $message: $filename</font>");
1.607 raeburn 1326: return 'unavailable';
1.8 www 1327: } else {
1.16 www 1328: if ($remoteurl!~/\.meta$/) {
1329: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1330: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1331: if ($mresponse->is_error()) {
1332: unlink($filename.'.meta');
1333: &logthis(
1.672 albertel 1334: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1335: }
1336: }
1.8 www 1337: rename($transname,$filename);
1.607 raeburn 1338: return 'ok';
1.8 www 1339: }
1.290 www 1340: }
1.8 www 1341: }
1.330 www 1342: }
1343:
1344: # ------------------------------------------------ Get server side include body
1345: sub ssi_body {
1.381 albertel 1346: my ($filelink,%form)=@_;
1.606 matthew 1347: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1348: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1349: }
1.330 www 1350: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1351: &ssi($filelink,%form));
1.778 albertel 1352: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1353: $output=~s/^.*?\<body[^\>]*\>//si;
1354: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1355: return $output;
1.8 www 1356: }
1357:
1.15 www 1358: # --------------------------------------------------------- Server Side Include
1359:
1.782 albertel 1360: sub absolute_url {
1361: my ($host_name) = @_;
1362: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1363: if ($host_name eq '') {
1364: $host_name = $ENV{'SERVER_NAME'};
1365: }
1366: return $protocol.$host_name;
1367: }
1368:
1.15 www 1369: sub ssi {
1370:
1.23 www 1371: my ($fn,%form)=@_;
1.15 www 1372:
1373: my $ua=new LWP::UserAgent;
1.23 www 1374:
1375: my $request;
1.711 albertel 1376:
1377: $form{'no_update_last_known'}=1;
1378:
1.23 www 1379: if (%form) {
1.782 albertel 1380: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1381: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1382: } else {
1.782 albertel 1383: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1384: }
1385:
1.15 www 1386: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1387: my $response=$ua->request($request);
1388:
1.324 www 1389: return $response->content;
1390: }
1391:
1392: sub externalssi {
1393: my ($url)=@_;
1394: my $ua=new LWP::UserAgent;
1395: my $request=new HTTP::Request('GET',$url);
1396: my $response=$ua->request($request);
1.15 www 1397: return $response->content;
1398: }
1.254 www 1399:
1.492 albertel 1400: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1401:
1402: sub allowuploaded {
1403: my ($srcurl,$url)=@_;
1404: $url=&clutter(&declutter($url));
1405: my $dir=$url;
1406: $dir=~s/\/[^\/]+$//;
1407: my %httpref=();
1408: my $httpurl=&hreflocation('',$url);
1409: $httpref{'httpref.'.$httpurl}=$srcurl;
1410: &Apache::lonnet::appenv(%httpref);
1.254 www 1411: }
1.477 raeburn 1412:
1.478 albertel 1413: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1414: # input: action, courseID, current domain, intended
1.637 raeburn 1415: # path to file, source of file, instruction to parse file for objects,
1416: # ref to hash for embedded objects,
1417: # ref to hash for codebase of java objects.
1418: #
1.485 raeburn 1419: # output: url to file (if action was uploaddoc),
1420: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1421: #
1.478 albertel 1422: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1423: # course.
1.477 raeburn 1424: #
1.478 albertel 1425: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1426: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1427: # course's home server.
1.477 raeburn 1428: #
1.478 albertel 1429: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1430: # be copied from $source (current location) to
1431: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1432: # and will then be copied to
1433: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1434: # course's home server.
1.485 raeburn 1435: #
1.481 raeburn 1436: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1437: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1438: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1439: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1440: # in course's home server.
1.637 raeburn 1441: #
1.477 raeburn 1442:
1443: sub process_coursefile {
1.638 albertel 1444: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1445: my $fetchresult;
1.638 albertel 1446: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1447: if ($action eq 'propagate') {
1.638 albertel 1448: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1449: $home);
1.481 raeburn 1450: } else {
1.477 raeburn 1451: my $fpath = '';
1452: my $fname = $file;
1.478 albertel 1453: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1454: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1455: my $filepath = &build_filepath($fpath);
1.481 raeburn 1456: if ($action eq 'copy') {
1457: if ($source eq '') {
1458: $fetchresult = 'no source file';
1459: return $fetchresult;
1460: } else {
1461: my $destination = $filepath.'/'.$fname;
1462: rename($source,$destination);
1463: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1464: $home);
1.481 raeburn 1465: }
1466: } elsif ($action eq 'uploaddoc') {
1467: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1468: print $fh $env{'form.'.$source};
1.481 raeburn 1469: close($fh);
1.637 raeburn 1470: if ($parser eq 'parse') {
1471: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1472: unless ($parse_result eq 'ok') {
1473: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1474: }
1475: }
1.477 raeburn 1476: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1477: $home);
1.481 raeburn 1478: if ($fetchresult eq 'ok') {
1479: return '/uploaded/'.$fpath.'/'.$fname;
1480: } else {
1481: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1482: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1483: return '/adm/notfound.html';
1484: }
1.477 raeburn 1485: }
1486: }
1.485 raeburn 1487: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1488: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1489: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1490: }
1491: return $fetchresult;
1492: }
1493:
1.637 raeburn 1494: sub build_filepath {
1495: my ($fpath) = @_;
1496: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1497: unless ($fpath eq '') {
1498: my @parts=split('/',$fpath);
1499: foreach my $part (@parts) {
1500: $filepath.= '/'.$part;
1501: if ((-e $filepath)!=1) {
1502: mkdir($filepath,0777);
1503: }
1504: }
1505: }
1506: return $filepath;
1507: }
1508:
1509: sub store_edited_file {
1.638 albertel 1510: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1511: my $file = $primary_url;
1512: $file =~ s#^/uploaded/$docudom/$docuname/##;
1513: my $fpath = '';
1514: my $fname = $file;
1515: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1516: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1517: my $filepath = &build_filepath($fpath);
1518: open(my $fh,'>'.$filepath.'/'.$fname);
1519: print $fh $content;
1520: close($fh);
1.638 albertel 1521: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1522: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1523: $home);
1.637 raeburn 1524: if ($$fetchresult eq 'ok') {
1525: return '/uploaded/'.$fpath.'/'.$fname;
1526: } else {
1.638 albertel 1527: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1528: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1529: return '/adm/notfound.html';
1530: }
1531: }
1532:
1.531 albertel 1533: sub clean_filename {
1.831 albertel 1534: my ($fname,$args)=@_;
1.315 www 1535: # Replace Windows backslashes by forward slashes
1.257 www 1536: $fname=~s/\\/\//g;
1.831 albertel 1537: if (!$args->{'keep_path'}) {
1538: # Get rid of everything but the actual filename
1539: $fname=~s/^.*\/([^\/]+)$/$1/;
1540: }
1.315 www 1541: # Replace spaces by underscores
1542: $fname=~s/\s+/\_/g;
1543: # Replace all other weird characters by nothing
1.831 albertel 1544: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1545: # Replace all .\d. sequences with _\d. so they no longer look like version
1546: # numbers
1547: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1548: return $fname;
1549: }
1550:
1.608 albertel 1551: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1552: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1553: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1554: # $coursedoc - if true up to the current course
1555: # if false
1556: # $subdir - directory in userfile to store the file into
1.858 raeburn 1557: # $parser - instruction to parse file for objects ($parser = parse)
1558: # $allfiles - reference to hash for embedded objects
1559: # $codebase - reference to hash for codebase of java objects
1560: # $desuname - username for permanent storage of uploaded file
1561: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1562: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1563: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1564: #
1.686 albertel 1565: # output: url of file in userspace, or error: <message>
1566: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1567:
1568:
1.531 albertel 1569: sub userfileupload {
1.860 raeburn 1570: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1571: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1572: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1573: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1574: $fname=&clean_filename($fname);
1.315 www 1575: # See if there is anything left
1.257 www 1576: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1577: chop($env{'form.'.$formname});
1.523 raeburn 1578: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1579: my $now = time;
1580: my $filepath = 'tmp/helprequests/'.$now;
1581: my @parts=split(/\//,$filepath);
1582: my $fullpath = $perlvar{'lonDaemons'};
1583: for (my $i=0;$i<@parts;$i++) {
1584: $fullpath .= '/'.$parts[$i];
1585: if ((-e $fullpath)!=1) {
1586: mkdir($fullpath,0777);
1587: }
1588: }
1589: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1590: print $fh $env{'form.'.$formname};
1.523 raeburn 1591: close($fh);
1.741 raeburn 1592: return $fullpath.'/'.$fname;
1593: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1594: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1595: '_'.$env{'user.domain'}.'/pending';
1596: my @parts=split(/\//,$filepath);
1597: my $fullpath = $perlvar{'lonDaemons'};
1598: for (my $i=0;$i<@parts;$i++) {
1599: $fullpath .= '/'.$parts[$i];
1600: if ((-e $fullpath)!=1) {
1601: mkdir($fullpath,0777);
1602: }
1603: }
1604: open(my $fh,'>'.$fullpath.'/'.$fname);
1605: print $fh $env{'form.'.$formname};
1606: close($fh);
1607: return $fullpath.'/'.$fname;
1.523 raeburn 1608: }
1.719 banghart 1609:
1.258 www 1610: # Create the directory if not present
1.493 albertel 1611: $fname="$subdir/$fname";
1.259 www 1612: if ($coursedoc) {
1.638 albertel 1613: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1614: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1615: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1616: return &finishuserfileupload($docuname,$docudom,
1617: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1618: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1619: } else {
1.620 albertel 1620: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1621: return &process_coursefile('uploaddoc',$docuname,$docudom,
1622: $fname,$formname,$parser,
1623: $allfiles,$codebase);
1.481 raeburn 1624: }
1.719 banghart 1625: } elsif (defined($destuname)) {
1626: my $docuname=$destuname;
1627: my $docudom=$destudom;
1.860 raeburn 1628: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1629: $parser,$allfiles,$codebase,
1630: $thumbwidth,$thumbheight);
1.719 banghart 1631:
1.259 www 1632: } else {
1.638 albertel 1633: my $docuname=$env{'user.name'};
1634: my $docudom=$env{'user.domain'};
1.714 raeburn 1635: if (exists($env{'form.group'})) {
1636: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1637: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1638: }
1.860 raeburn 1639: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1640: $parser,$allfiles,$codebase,
1641: $thumbwidth,$thumbheight);
1.259 www 1642: }
1.271 www 1643: }
1644:
1645: sub finishuserfileupload {
1.860 raeburn 1646: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1647: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1648: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1649: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1650: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1651: $file=$fname;
1652: if ($fname=~m|/|) {
1653: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1654: $path.=$fnamepath.'/';
1655: }
1.259 www 1656: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1657: my $count;
1658: for ($count=4;$count<=$#parts;$count++) {
1659: $filepath.="/$parts[$count]";
1660: if ((-e $filepath)!=1) {
1661: mkdir($filepath,0777);
1662: }
1663: }
1664: # Save the file
1665: {
1.701 albertel 1666: if (!open(FH,'>'.$filepath.'/'.$file)) {
1667: &logthis('Failed to create '.$filepath.'/'.$file);
1668: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1669: return '/adm/notfound.html';
1670: }
1671: if (!print FH ($env{'form.'.$formname})) {
1672: &logthis('Failed to write to '.$filepath.'/'.$file);
1673: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1674: return '/adm/notfound.html';
1675: }
1.570 albertel 1676: close(FH);
1.258 www 1677: }
1.637 raeburn 1678: if ($parser eq 'parse') {
1.638 albertel 1679: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1680: $codebase);
1.637 raeburn 1681: unless ($parse_result eq 'ok') {
1.638 albertel 1682: &logthis('Failed to parse '.$filepath.$file.
1683: ' for embedded media: '.$parse_result);
1.637 raeburn 1684: }
1685: }
1.860 raeburn 1686: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1687: my $input = $filepath.'/'.$file;
1688: my $output = $filepath.'/'.'tn-'.$file;
1689: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1690: system("convert -sample $thumbsize $input $output");
1691: if (-e $filepath.'/'.'tn-'.$file) {
1692: $fetchthumb = 1;
1693: }
1694: }
1.858 raeburn 1695:
1.259 www 1696: # Notify homeserver to grep it
1697: #
1.638 albertel 1698: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1699: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1700: if ($fetchresult eq 'ok') {
1.860 raeburn 1701: if ($fetchthumb) {
1702: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1703: if ($thumbresult ne 'ok') {
1704: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1705: $docuhome.': '.$thumbresult);
1706: }
1707: }
1.259 www 1708: #
1.258 www 1709: # Return the URL to it
1.494 albertel 1710: return '/uploaded/'.$path.$file;
1.263 www 1711: } else {
1.494 albertel 1712: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1713: ': '.$fetchresult);
1.263 www 1714: return '/adm/notfound.html';
1.858 raeburn 1715: }
1.493 albertel 1716: }
1717:
1.637 raeburn 1718: sub extract_embedded_items {
1.648 raeburn 1719: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1720: my @state = ();
1721: my %javafiles = (
1722: codebase => '',
1723: code => '',
1724: archive => ''
1725: );
1726: my %mediafiles = (
1727: src => '',
1728: movie => '',
1729: );
1.648 raeburn 1730: my $p;
1731: if ($content) {
1732: $p = HTML::LCParser->new($content);
1733: } else {
1734: $p = HTML::LCParser->new($filepath.'/'.$file);
1735: }
1.641 albertel 1736: while (my $t=$p->get_token()) {
1.640 albertel 1737: if ($t->[0] eq 'S') {
1738: my ($tagname, $attr) = ($t->[1],$t->[2]);
1739: push (@state, $tagname);
1.648 raeburn 1740: if (lc($tagname) eq 'allow') {
1741: &add_filetype($allfiles,$attr->{'src'},'src');
1742: }
1.640 albertel 1743: if (lc($tagname) eq 'img') {
1744: &add_filetype($allfiles,$attr->{'src'},'src');
1745: }
1.645 raeburn 1746: if (lc($tagname) eq 'script') {
1747: if ($attr->{'archive'} =~ /\.jar$/i) {
1748: &add_filetype($allfiles,$attr->{'archive'},'archive');
1749: } else {
1750: &add_filetype($allfiles,$attr->{'src'},'src');
1751: }
1752: }
1753: if (lc($tagname) eq 'link') {
1754: if (lc($attr->{'rel'}) eq 'stylesheet') {
1755: &add_filetype($allfiles,$attr->{'href'},'href');
1756: }
1757: }
1.640 albertel 1758: if (lc($tagname) eq 'object' ||
1759: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1760: foreach my $item (keys(%javafiles)) {
1761: $javafiles{$item} = '';
1762: }
1763: }
1764: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1765: my $name = lc($attr->{'name'});
1766: foreach my $item (keys(%javafiles)) {
1767: if ($name eq $item) {
1768: $javafiles{$item} = $attr->{'value'};
1769: last;
1770: }
1771: }
1772: foreach my $item (keys(%mediafiles)) {
1773: if ($name eq $item) {
1774: &add_filetype($allfiles, $attr->{'value'}, 'value');
1775: last;
1776: }
1777: }
1778: }
1779: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1780: foreach my $item (keys(%javafiles)) {
1781: if ($attr->{$item}) {
1782: $javafiles{$item} = $attr->{$item};
1783: last;
1784: }
1785: }
1786: foreach my $item (keys(%mediafiles)) {
1787: if ($attr->{$item}) {
1788: &add_filetype($allfiles,$attr->{$item},$item);
1789: last;
1790: }
1791: }
1792: }
1793: } elsif ($t->[0] eq 'E') {
1794: my ($tagname) = ($t->[1]);
1795: if ($javafiles{'codebase'} ne '') {
1796: $javafiles{'codebase'} .= '/';
1797: }
1798: if (lc($tagname) eq 'applet' ||
1799: lc($tagname) eq 'object' ||
1800: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1801: ) {
1802: foreach my $item (keys(%javafiles)) {
1803: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1804: my $file=$javafiles{'codebase'}.$javafiles{$item};
1805: &add_filetype($allfiles,$file,$item);
1806: }
1807: }
1808: }
1809: pop @state;
1810: }
1811: }
1.637 raeburn 1812: return 'ok';
1813: }
1814:
1.639 albertel 1815: sub add_filetype {
1816: my ($allfiles,$file,$type)=@_;
1817: if (exists($allfiles->{$file})) {
1818: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1819: push(@{$allfiles->{$file}}, &escape($type));
1820: }
1821: } else {
1822: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1823: }
1824: }
1825:
1.493 albertel 1826: sub removeuploadedurl {
1827: my ($url)=@_;
1828: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1829: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1830: }
1831:
1832: sub removeuserfile {
1833: my ($docuname,$docudom,$fname)=@_;
1834: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1835: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1836: if ($result eq 'ok') {
1837: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1838: my $metafile = $fname.'.meta';
1839: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 1840: my $url = "/uploaded/$docudom/$docuname/$fname";
1841: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1842: my $sqlresult =
1.823 albertel 1843: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1844: 'portfolio_metadata',$group,
1845: 'delete');
1.798 raeburn 1846: }
1847: }
1848: return $result;
1.257 www 1849: }
1.15 www 1850:
1.530 albertel 1851: sub mkdiruserfile {
1852: my ($docuname,$docudom,$dir)=@_;
1853: my $home=&homeserver($docuname,$docudom);
1854: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1855: }
1856:
1.531 albertel 1857: sub renameuserfile {
1858: my ($docuname,$docudom,$old,$new)=@_;
1859: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1860: my $result = &reply("renameuserfile:$docudom:$docuname:".
1861: &escape("$old").':'.&escape("$new"),$home);
1862: if ($result eq 'ok') {
1863: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1864: my $oldmeta = $old.'.meta';
1865: my $newmeta = $new.'.meta';
1866: my $metaresult =
1867: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 1868: my $url = "/uploaded/$docudom/$docuname/$old";
1869: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1870: my $sqlresult =
1.823 albertel 1871: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1872: 'portfolio_metadata',$group,
1873: 'delete');
1.798 raeburn 1874: }
1875: }
1876: return $result;
1.531 albertel 1877: }
1878:
1.14 www 1879: # ------------------------------------------------------------------------- Log
1880:
1881: sub log {
1882: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1883: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1884: }
1885:
1886: # ------------------------------------------------------------------ Course Log
1.352 www 1887: #
1888: # This routine flushes several buffers of non-mission-critical nature
1889: #
1.157 www 1890:
1891: sub flushcourselogs {
1.352 www 1892: &logthis('Flushing log buffers');
1893: #
1894: # course logs
1895: # This is a log of all transactions in a course, which can be used
1896: # for data mining purposes
1897: #
1898: # It also collects the courseid database, which lists last transaction
1899: # times and course titles for all courseids
1900: #
1901: my %courseidbuffer=();
1.800 albertel 1902: foreach my $crsid (keys %courselogs) {
1.352 www 1903: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1904: &escape($courselogs{$crsid}),
1905: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1906: delete $courselogs{$crsid};
1907: } else {
1908: &logthis('Failed to flush log buffer for '.$crsid);
1909: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1910: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1911: " exceeded maximum size, deleting.</font>");
1912: delete $courselogs{$crsid};
1913: }
1.352 www 1914: }
1915: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1916: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1917: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1918: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1919: } else {
1920: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1921: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1922: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1923: }
1.191 harris41 1924: }
1.352 www 1925: #
1926: # Write course id database (reverse lookup) to homeserver of courses
1927: # Is used in pickcourse
1928: #
1.840 albertel 1929: foreach my $crs_home (keys(%courseidbuffer)) {
1.844 albertel 1930: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840 albertel 1931: $crs_home);
1.352 www 1932: }
1933: #
1934: # File accesses
1935: # Writes to the dynamic metadata of resources to get hit counts, etc.
1936: #
1.449 matthew 1937: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1938: if ($entry =~ /___count$/) {
1939: my ($dom,$name);
1.807 albertel 1940: ($dom,$name,undef)=
1.811 albertel 1941: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 1942: if (! defined($dom) || $dom eq '' ||
1943: ! defined($name) || $name eq '') {
1.620 albertel 1944: my $cid = $env{'request.course.id'};
1945: $dom = $env{'request.'.$cid.'.domain'};
1946: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1947: }
1.450 matthew 1948: my $value = $accesshash{$entry};
1949: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1950: my %temphash=($url => $value);
1.449 matthew 1951: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1952: if ($result eq 'ok') {
1953: delete $accesshash{$entry};
1954: } elsif ($result eq 'unknown_cmd') {
1955: # Target server has old code running on it.
1.450 matthew 1956: my %temphash=($entry => $value);
1.449 matthew 1957: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1958: delete $accesshash{$entry};
1959: }
1960: }
1961: } else {
1.811 albertel 1962: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 1963: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1964: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1965: delete $accesshash{$entry};
1966: }
1.185 www 1967: }
1.191 harris41 1968: }
1.352 www 1969: #
1970: # Roles
1971: # Reverse lookup of user roles for course faculty/staff and co-authorship
1972: #
1.800 albertel 1973: foreach my $entry (keys(%userrolehash)) {
1.351 www 1974: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1975: split(/\:/,$entry);
1976: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1977: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1978: $rudom,$runame) eq 'ok') {
1979: delete $userrolehash{$entry};
1980: }
1981: }
1.662 raeburn 1982: #
1983: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1984: #
1985: my %domrolebuffer = ();
1986: foreach my $entry (keys %domainrolehash) {
1987: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1988: if ($domrolebuffer{$rudom}) {
1989: $domrolebuffer{$rudom}.='&'.&escape($entry).
1990: '='.&escape($domainrolehash{$entry});
1991: } else {
1992: $domrolebuffer{$rudom}.=&escape($entry).
1993: '='.&escape($domainrolehash{$entry});
1994: }
1995: delete $domainrolehash{$entry};
1996: }
1997: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 1998: my %servers = &get_servers($dom,'library');
1999: foreach my $tryserver (keys(%servers)) {
2000: unless (&reply('domroleput:'.$dom.':'.
2001: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2002: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2003: }
1.662 raeburn 2004: }
2005: }
1.186 www 2006: $dumpcount++;
1.157 www 2007: }
2008:
2009: sub courselog {
2010: my $what=shift;
1.158 www 2011: $what=time.':'.$what;
1.620 albertel 2012: unless ($env{'request.course.id'}) { return ''; }
2013: $coursedombuf{$env{'request.course.id'}}=
2014: $env{'course.'.$env{'request.course.id'}.'.domain'};
2015: $coursenumbuf{$env{'request.course.id'}}=
2016: $env{'course.'.$env{'request.course.id'}.'.num'};
2017: $coursehombuf{$env{'request.course.id'}}=
2018: $env{'course.'.$env{'request.course.id'}.'.home'};
2019: $coursedescrbuf{$env{'request.course.id'}}=
2020: $env{'course.'.$env{'request.course.id'}.'.description'};
2021: $courseinstcodebuf{$env{'request.course.id'}}=
2022: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2023: $courseownerbuf{$env{'request.course.id'}}=
2024: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2025: $coursetypebuf{$env{'request.course.id'}}=
2026: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2027: if (defined $courselogs{$env{'request.course.id'}}) {
2028: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2029: } else {
1.620 albertel 2030: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2031: }
1.620 albertel 2032: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2033: &flushcourselogs();
2034: }
1.158 www 2035: }
2036:
2037: sub courseacclog {
2038: my $fnsymb=shift;
1.620 albertel 2039: unless ($env{'request.course.id'}) { return ''; }
2040: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2041: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2042: $what.=':POST';
1.583 matthew 2043: # FIXME: Probably ought to escape things....
1.800 albertel 2044: foreach my $key (keys(%env)) {
2045: if ($key=~/^form\.(.*)/) {
2046: $what.=':'.$1.'='.$env{$key};
1.158 www 2047: }
1.191 harris41 2048: }
1.583 matthew 2049: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2050: # FIXME: We should not be depending on a form parameter that someone
2051: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2052: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2053: $what.= ':POST';
2054: # FIXME: Probably ought to escape things....
2055: foreach my $element ('courseexp','crsfulltext','crsrelated',
2056: 'crsdiscuss') {
1.620 albertel 2057: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2058: }
2059: }
1.158 www 2060: }
2061: &courselog($what);
1.149 www 2062: }
2063:
1.185 www 2064: sub countacc {
2065: my $url=&declutter(shift);
1.458 matthew 2066: return if (! defined($url) || $url eq '');
1.620 albertel 2067: unless ($env{'request.course.id'}) { return ''; }
2068: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2069: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2070: $accesshash{$key}++;
1.185 www 2071: }
1.349 www 2072:
1.361 www 2073: sub linklog {
2074: my ($from,$to)=@_;
2075: $from=&declutter($from);
2076: $to=&declutter($to);
2077: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2078: $accesshash{$to.'___'.$from.'___goto'}=1;
2079: }
2080:
1.349 www 2081: sub userrolelog {
2082: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2083: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2084: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2085: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2086: ($trole=~/^ta/)) {
1.350 www 2087: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2088: $userrolehash
2089: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2090: =$tend.':'.$tstart;
1.662 raeburn 2091: }
2092: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2093: ($trole=~/^li/) || ($trole=~/^li/) ||
2094: ($trole=~/^au/) || ($trole=~/^dg/) ||
2095: ($trole=~/^sc/)) {
2096: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2097: $domainrolehash
2098: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2099: = $tend.':'.$tstart;
2100: }
1.351 www 2101: }
2102:
2103: sub get_course_adv_roles {
2104: my $cid=shift;
1.620 albertel 2105: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2106: my %coursehash=&coursedescription($cid);
1.470 www 2107: my %nothide=();
1.800 albertel 2108: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2109: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2110: }
1.351 www 2111: my %returnhash=();
2112: my %dumphash=
2113: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2114: my $now=time;
1.800 albertel 2115: foreach my $entry (keys %dumphash) {
2116: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2117: if (($tstart) && ($tstart<0)) { next; }
2118: if (($tend) && ($tend<$now)) { next; }
2119: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2120: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2121: if ($username eq '' || $domain eq '') { next; }
1.470 www 2122: if ((&privileged($username,$domain)) &&
2123: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2124: if ($role eq 'cr') { next; }
1.351 www 2125: my $key=&plaintext($role);
2126: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2127: if ($returnhash{$key}) {
2128: $returnhash{$key}.=','.$username.':'.$domain;
2129: } else {
2130: $returnhash{$key}=$username.':'.$domain;
2131: }
1.400 www 2132: }
2133: return %returnhash;
2134: }
2135:
2136: sub get_my_roles {
1.858 raeburn 2137: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2138: unless (defined($uname)) { $uname=$env{'user.name'}; }
2139: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2140: my %dumphash;
2141: if ($context eq 'userroles') {
2142: %dumphash = &dump('roles',$udom,$uname);
2143: } else {
2144: %dumphash=
1.400 www 2145: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2146: }
1.400 www 2147: my %returnhash=();
2148: my $now=time;
1.800 albertel 2149: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2150: my ($role,$tend,$tstart);
2151: if ($context eq 'userroles') {
2152: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2153: } else {
2154: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2155: }
1.400 www 2156: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2157: my $status = 'active';
2158: if (($tend) && ($tend<$now)) {
2159: $status = 'previous';
2160: }
2161: if (($tstart) && ($now<$tstart)) {
2162: $status = 'future';
2163: }
2164: if (ref($types) eq 'ARRAY') {
2165: if (!grep(/^\Q$status\E$/,@{$types})) {
2166: next;
2167: }
2168: } else {
2169: if ($status ne 'active') {
2170: next;
2171: }
2172: }
1.867 raeburn 2173: my ($rolecode,$username,$domain,$section,$area);
2174: if ($context eq 'userroles') {
2175: ($area,$rolecode) = split(/_/,$entry);
2176: (undef,$domain,$username,$section) = split(/\//,$area);
2177: } else {
2178: ($role,$username,$domain,$section) = split(/\:/,$entry);
2179: }
1.832 raeburn 2180: if (ref($roledoms) eq 'ARRAY') {
2181: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2182: next;
2183: }
2184: }
2185: if (ref($roles) eq 'ARRAY') {
2186: if (!grep(/^\Q$role\E$/,@{$roles})) {
2187: next;
2188: }
1.867 raeburn 2189: }
1.400 www 2190: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2191: }
1.373 www 2192: return %returnhash;
1.399 www 2193: }
2194:
2195: # ----------------------------------------------------- Frontpage Announcements
2196: #
2197: #
2198:
2199: sub postannounce {
2200: my ($server,$text)=@_;
1.844 albertel 2201: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2202: unless ($text=~/\w/) { $text=''; }
2203: return &reply('setannounce:'.&escape($text),$server);
2204: }
2205:
2206: sub getannounce {
1.448 albertel 2207:
2208: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2209: my $announcement='';
1.800 albertel 2210: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2211: close($fh);
1.399 www 2212: if ($announcement=~/\w/) {
2213: return
2214: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2215: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2216: } else {
2217: return '';
2218: }
2219: } else {
2220: return '';
2221: }
1.351 www 2222: }
1.353 www 2223:
2224: # ---------------------------------------------------------- Course ID routines
2225: # Deal with domain's nohist_courseid.db files
2226: #
2227:
2228: sub courseidput {
2229: my ($domain,$what,$coursehome)=@_;
2230: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2231: }
2232:
2233: sub courseiddump {
1.791 raeburn 2234: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 2235: my %returnhash=();
1.355 www 2236: unless ($domfilter) { $domfilter=''; }
1.845 albertel 2237: my %libserv = &all_library();
2238: foreach my $tryserver (keys(%libserv)) {
2239: if ( ( $hostidflag == 1
2240: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2241: || (!defined($hostidflag)) ) {
2242:
2243: if ($domfilter eq ''
2244: || (&host_domain($tryserver) eq $domfilter)) {
1.800 albertel 2245: foreach my $line (
1.844 albertel 2246: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571 raeburn 2247: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 2248: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 2249: $tryserver))) {
1.800 albertel 2250: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 2251: if (($key) && ($value)) {
1.516 raeburn 2252: $returnhash{&unescape($key)}=$value;
1.506 raeburn 2253: }
1.353 www 2254: }
2255: }
2256: }
2257: }
2258: return %returnhash;
2259: }
2260:
1.658 raeburn 2261: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2262:
2263: sub dcmailput {
1.685 raeburn 2264: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2265: my $status = &Apache::lonnet::critical(
1.740 www 2266: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2267: &escape($message),$server);
1.662 raeburn 2268: return $status;
2269: }
2270:
1.658 raeburn 2271: sub dcmaildump {
2272: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2273: my %returnhash=();
1.846 albertel 2274:
2275: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2276: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2277: &escape($enddate).':';
2278: my @esc_senders=map { &escape($_)} @$senders;
2279: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2280: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2281: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2282: if (($key) && ($value)) {
2283: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2284: }
2285: }
2286: }
2287: return %returnhash;
2288: }
1.662 raeburn 2289: # ---------------------------------------------------------- Domain roles
2290:
2291: sub get_domain_roles {
2292: my ($dom,$roles,$startdate,$enddate)=@_;
2293: if (undef($startdate) || $startdate eq '') {
2294: $startdate = '.';
2295: }
2296: if (undef($enddate) || $enddate eq '') {
2297: $enddate = '.';
2298: }
2299: my $rolelist = join(':',@{$roles});
2300: my %personnel = ();
1.841 albertel 2301:
2302: my %servers = &get_servers($dom,'library');
2303: foreach my $tryserver (keys(%servers)) {
2304: %{$personnel{$tryserver}}=();
2305: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2306: &escape($startdate).':'.
2307: &escape($enddate).':'.
2308: &escape($rolelist), $tryserver))) {
2309: my ($key,$value) = split(/\=/,$line,2);
2310: if (($key) && ($value)) {
2311: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2312: }
2313: }
1.662 raeburn 2314: }
2315: return %personnel;
2316: }
1.658 raeburn 2317:
1.149 www 2318: # ----------------------------------------------------------- Check out an item
2319:
1.504 albertel 2320: sub get_first_access {
2321: my ($type,$argsymb)=@_;
1.790 albertel 2322: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2323: if ($argsymb) { $symb=$argsymb; }
2324: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2325: if ($type eq 'map') {
2326: $res=&symbread($map);
2327: } else {
2328: $res=$symb;
2329: }
2330: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2331: return $times{"$courseid\0$res"};
1.504 albertel 2332: }
2333:
2334: sub set_first_access {
2335: my ($type)=@_;
1.790 albertel 2336: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2337: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2338: if ($type eq 'map') {
2339: $res=&symbread($map);
2340: } else {
2341: $res=$symb;
2342: }
2343: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2344: if (!$firstaccess) {
1.588 albertel 2345: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2346: }
2347: return 'already_set';
1.504 albertel 2348: }
2349:
1.149 www 2350: sub checkout {
2351: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2352: my $now=time;
2353: my $lonhost=$perlvar{'lonHostID'};
2354: my $infostr=&escape(
1.234 www 2355: 'CHECKOUTTOKEN&'.
1.149 www 2356: $tuname.'&'.
2357: $tudom.'&'.
2358: $tcrsid.'&'.
2359: $symb.'&'.
2360: $now.'&'.$ENV{'REMOTE_ADDR'});
2361: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2362: if ($token=~/^error\:/) {
1.672 albertel 2363: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2364: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2365: "</font>");
2366: return '';
2367: }
2368:
1.149 www 2369: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2370: $token=~tr/a-z/A-Z/;
2371:
1.153 www 2372: my %infohash=('resource.0.outtoken' => $token,
2373: 'resource.0.checkouttime' => $now,
2374: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2375:
2376: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2377: return '';
1.151 www 2378: } else {
1.672 albertel 2379: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2380: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2381: "</font>");
1.149 www 2382: }
2383:
2384: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2385: &escape('Checkout '.$infostr.' - '.
2386: $token)) ne 'ok') {
2387: return '';
1.151 www 2388: } else {
1.672 albertel 2389: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2390: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2391: "</font>");
1.149 www 2392: }
1.151 www 2393: return $token;
1.149 www 2394: }
2395:
2396: # ------------------------------------------------------------ Check in an item
2397:
2398: sub checkin {
2399: my $token=shift;
1.150 www 2400: my $now=time;
2401: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2402: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2403: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2404: $dtoken=~s/\W/\_/g;
1.234 www 2405: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2406: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2407:
1.154 www 2408: unless (($tuname) && ($tudom)) {
2409: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2410: return '';
2411: }
2412:
2413: unless (&allowed('mgr',$tcrsid)) {
2414: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2415: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2416: return '';
2417: }
2418:
1.153 www 2419: my %infohash=('resource.0.intoken' => $token,
2420: 'resource.0.checkintime' => $now,
2421: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2422:
2423: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2424: return '';
2425: }
2426:
2427: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2428: &escape('Checkin - '.$token)) ne 'ok') {
2429: return '';
2430: }
2431:
2432: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2433: }
2434:
2435: # --------------------------------------------- Set Expire Date for Spreadsheet
2436:
2437: sub expirespread {
2438: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2439: my $cid=$env{'request.course.id'};
1.110 www 2440: if ($cid) {
2441: my $now=time;
2442: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2443: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2444: $env{'course.'.$cid.'.num'}.
1.110 www 2445: ':nohist_expirationdates:'.
2446: &escape($key).'='.$now,
1.620 albertel 2447: $env{'course.'.$cid.'.home'})
1.110 www 2448: }
2449: return 'ok';
1.14 www 2450: }
2451:
1.109 www 2452: # ----------------------------------------------------- Devalidate Spreadsheets
2453:
2454: sub devalidate {
1.325 www 2455: my ($symb,$uname,$udom)=@_;
1.620 albertel 2456: my $cid=$env{'request.course.id'};
1.109 www 2457: if ($cid) {
1.391 matthew 2458: # delete the stored spreadsheets for
2459: # - the student level sheet of this user in course's homespace
2460: # - the assessment level sheet for this resource
2461: # for this user in user's homespace
1.553 albertel 2462: # - current conditional state info
1.325 www 2463: my $key=$uname.':'.$udom.':';
1.109 www 2464: my $status=
1.299 matthew 2465: &del('nohist_calculatedsheets',
1.391 matthew 2466: [$key.'studentcalc:'],
1.620 albertel 2467: $env{'course.'.$cid.'.domain'},
2468: $env{'course.'.$cid.'.num'})
1.133 albertel 2469: .' '.
2470: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2471: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2472: unless ($status eq 'ok ok') {
2473: &logthis('Could not devalidate spreadsheet '.
1.325 www 2474: $uname.' at '.$udom.' for '.
1.109 www 2475: $symb.': '.$status);
1.133 albertel 2476: }
1.553 albertel 2477: &delenv('user.state.'.$cid);
1.109 www 2478: }
2479: }
2480:
1.265 albertel 2481: sub get_scalar {
2482: my ($string,$end) = @_;
2483: my $value;
2484: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2485: $value = $1;
2486: } elsif ($$string =~ s/^([^&]*?)&//) {
2487: $value = $1;
2488: }
2489: return &unescape($value);
2490: }
2491:
2492: sub array2str {
2493: my (@array) = @_;
2494: my $result=&arrayref2str(\@array);
2495: $result=~s/^__ARRAY_REF__//;
2496: $result=~s/__END_ARRAY_REF__$//;
2497: return $result;
2498: }
2499:
1.204 albertel 2500: sub arrayref2str {
2501: my ($arrayref) = @_;
1.265 albertel 2502: my $result='__ARRAY_REF__';
1.204 albertel 2503: foreach my $elem (@$arrayref) {
1.265 albertel 2504: if(ref($elem) eq 'ARRAY') {
2505: $result.=&arrayref2str($elem).'&';
2506: } elsif(ref($elem) eq 'HASH') {
2507: $result.=&hashref2str($elem).'&';
2508: } elsif(ref($elem)) {
2509: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2510: } else {
2511: $result.=&escape($elem).'&';
2512: }
2513: }
2514: $result=~s/\&$//;
1.265 albertel 2515: $result .= '__END_ARRAY_REF__';
1.204 albertel 2516: return $result;
2517: }
2518:
1.168 albertel 2519: sub hash2str {
1.204 albertel 2520: my (%hash) = @_;
2521: my $result=&hashref2str(\%hash);
1.265 albertel 2522: $result=~s/^__HASH_REF__//;
2523: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2524: return $result;
2525: }
2526:
2527: sub hashref2str {
2528: my ($hashref)=@_;
1.265 albertel 2529: my $result='__HASH_REF__';
1.800 albertel 2530: foreach my $key (sort(keys(%$hashref))) {
2531: if (ref($key) eq 'ARRAY') {
2532: $result.=&arrayref2str($key).'=';
2533: } elsif (ref($key) eq 'HASH') {
2534: $result.=&hashref2str($key).'=';
2535: } elsif (ref($key)) {
1.265 albertel 2536: $result.='=';
1.800 albertel 2537: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2538: } else {
1.800 albertel 2539: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2540: }
2541:
1.800 albertel 2542: if(ref($hashref->{$key}) eq 'ARRAY') {
2543: $result.=&arrayref2str($hashref->{$key}).'&';
2544: } elsif(ref($hashref->{$key}) eq 'HASH') {
2545: $result.=&hashref2str($hashref->{$key}).'&';
2546: } elsif(ref($hashref->{$key})) {
1.265 albertel 2547: $result.='&';
1.800 albertel 2548: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2549: } else {
1.800 albertel 2550: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2551: }
2552: }
1.168 albertel 2553: $result=~s/\&$//;
1.265 albertel 2554: $result .= '__END_HASH_REF__';
1.168 albertel 2555: return $result;
2556: }
2557:
2558: sub str2hash {
1.265 albertel 2559: my ($string)=@_;
2560: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2561: return %$hash;
2562: }
2563:
2564: sub str2hashref {
1.168 albertel 2565: my ($string) = @_;
1.265 albertel 2566:
2567: my %hash;
2568:
2569: if($string !~ /^__HASH_REF__/) {
2570: if (! ($string eq '' || !defined($string))) {
2571: $hash{'error'}='Not hash reference';
2572: }
2573: return (\%hash, $string);
2574: }
2575:
2576: $string =~ s/^__HASH_REF__//;
2577:
2578: while($string !~ /^__END_HASH_REF__/) {
2579: #key
2580: my $key='';
2581: if($string =~ /^__HASH_REF__/) {
2582: ($key, $string)=&str2hashref($string);
2583: if(defined($key->{'error'})) {
2584: $hash{'error'}='Bad data';
2585: return (\%hash, $string);
2586: }
2587: } elsif($string =~ /^__ARRAY_REF__/) {
2588: ($key, $string)=&str2arrayref($string);
2589: if($key->[0] eq 'Array reference error') {
2590: $hash{'error'}='Bad data';
2591: return (\%hash, $string);
2592: }
2593: } else {
2594: $string =~ s/^(.*?)=//;
1.267 albertel 2595: $key=&unescape($1);
1.265 albertel 2596: }
2597: $string =~ s/^=//;
2598:
2599: #value
2600: my $value='';
2601: if($string =~ /^__HASH_REF__/) {
2602: ($value, $string)=&str2hashref($string);
2603: if(defined($value->{'error'})) {
2604: $hash{'error'}='Bad data';
2605: return (\%hash, $string);
2606: }
2607: } elsif($string =~ /^__ARRAY_REF__/) {
2608: ($value, $string)=&str2arrayref($string);
2609: if($value->[0] eq 'Array reference error') {
2610: $hash{'error'}='Bad data';
2611: return (\%hash, $string);
2612: }
2613: } else {
2614: $value=&get_scalar(\$string,'__END_HASH_REF__');
2615: }
2616: $string =~ s/^&//;
2617:
2618: $hash{$key}=$value;
1.204 albertel 2619: }
1.265 albertel 2620:
2621: $string =~ s/^__END_HASH_REF__//;
2622:
2623: return (\%hash, $string);
1.204 albertel 2624: }
2625:
2626: sub str2array {
1.265 albertel 2627: my ($string)=@_;
2628: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2629: return @$array;
2630: }
2631:
2632: sub str2arrayref {
1.204 albertel 2633: my ($string) = @_;
1.265 albertel 2634: my @array;
2635:
2636: if($string !~ /^__ARRAY_REF__/) {
2637: if (! ($string eq '' || !defined($string))) {
2638: $array[0]='Array reference error';
2639: }
2640: return (\@array, $string);
2641: }
2642:
2643: $string =~ s/^__ARRAY_REF__//;
2644:
2645: while($string !~ /^__END_ARRAY_REF__/) {
2646: my $value='';
2647: if($string =~ /^__HASH_REF__/) {
2648: ($value, $string)=&str2hashref($string);
2649: if(defined($value->{'error'})) {
2650: $array[0] ='Array reference error';
2651: return (\@array, $string);
2652: }
2653: } elsif($string =~ /^__ARRAY_REF__/) {
2654: ($value, $string)=&str2arrayref($string);
2655: if($value->[0] eq 'Array reference error') {
2656: $array[0] ='Array reference error';
2657: return (\@array, $string);
2658: }
2659: } else {
2660: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2661: }
2662: $string =~ s/^&//;
2663:
2664: push(@array, $value);
1.191 harris41 2665: }
1.265 albertel 2666:
2667: $string =~ s/^__END_ARRAY_REF__//;
2668:
2669: return (\@array, $string);
1.168 albertel 2670: }
2671:
1.167 albertel 2672: # -------------------------------------------------------------------Temp Store
2673:
1.168 albertel 2674: sub tmpreset {
2675: my ($symb,$namespace,$domain,$stuname) = @_;
2676: if (!$symb) {
2677: $symb=&symbread();
1.620 albertel 2678: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2679: }
2680: $symb=escape($symb);
2681:
1.620 albertel 2682: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2683: $namespace=~s/\//\_/g;
2684: $namespace=~s/\W//g;
2685:
1.620 albertel 2686: if (!$domain) { $domain=$env{'user.domain'}; }
2687: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2688: if ($domain eq 'public' && $stuname eq 'public') {
2689: $stuname=$ENV{'REMOTE_ADDR'};
2690: }
1.168 albertel 2691: my $path=$perlvar{'lonDaemons'}.'/tmp';
2692: my %hash;
2693: if (tie(%hash,'GDBM_File',
2694: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2695: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2696: foreach my $key (keys %hash) {
1.180 albertel 2697: if ($key=~ /:$symb/) {
1.168 albertel 2698: delete($hash{$key});
2699: }
2700: }
2701: }
2702: }
2703:
1.167 albertel 2704: sub tmpstore {
1.168 albertel 2705: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2706:
2707: if (!$symb) {
2708: $symb=&symbread();
1.620 albertel 2709: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2710: }
2711: $symb=escape($symb);
2712:
2713: if (!$namespace) {
2714: # I don't think we would ever want to store this for a course.
2715: # it seems this will only be used if we don't have a course.
1.620 albertel 2716: #$namespace=$env{'request.course.id'};
1.168 albertel 2717: #if (!$namespace) {
1.620 albertel 2718: $namespace=$env{'request.state'};
1.168 albertel 2719: #}
2720: }
2721: $namespace=~s/\//\_/g;
2722: $namespace=~s/\W//g;
1.620 albertel 2723: if (!$domain) { $domain=$env{'user.domain'}; }
2724: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2725: if ($domain eq 'public' && $stuname eq 'public') {
2726: $stuname=$ENV{'REMOTE_ADDR'};
2727: }
1.168 albertel 2728: my $now=time;
2729: my %hash;
2730: my $path=$perlvar{'lonDaemons'}.'/tmp';
2731: if (tie(%hash,'GDBM_File',
2732: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2733: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2734: $hash{"version:$symb"}++;
2735: my $version=$hash{"version:$symb"};
2736: my $allkeys='';
2737: foreach my $key (keys(%$storehash)) {
2738: $allkeys.=$key.':';
1.591 albertel 2739: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2740: }
2741: $hash{"$version:$symb:timestamp"}=$now;
2742: $allkeys.='timestamp';
2743: $hash{"$version:keys:$symb"}=$allkeys;
2744: if (untie(%hash)) {
2745: return 'ok';
2746: } else {
2747: return "error:$!";
2748: }
2749: } else {
2750: return "error:$!";
2751: }
2752: }
1.167 albertel 2753:
1.168 albertel 2754: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2755:
1.168 albertel 2756: sub tmprestore {
2757: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2758:
1.168 albertel 2759: if (!$symb) {
2760: $symb=&symbread();
1.620 albertel 2761: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2762: }
2763: $symb=escape($symb);
2764:
1.620 albertel 2765: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2766:
1.620 albertel 2767: if (!$domain) { $domain=$env{'user.domain'}; }
2768: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2769: if ($domain eq 'public' && $stuname eq 'public') {
2770: $stuname=$ENV{'REMOTE_ADDR'};
2771: }
1.168 albertel 2772: my %returnhash;
2773: $namespace=~s/\//\_/g;
2774: $namespace=~s/\W//g;
2775: my %hash;
2776: my $path=$perlvar{'lonDaemons'}.'/tmp';
2777: if (tie(%hash,'GDBM_File',
2778: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2779: &GDBM_READER(),0640)) {
1.168 albertel 2780: my $version=$hash{"version:$symb"};
2781: $returnhash{'version'}=$version;
2782: my $scope;
2783: for ($scope=1;$scope<=$version;$scope++) {
2784: my $vkeys=$hash{"$scope:keys:$symb"};
2785: my @keys=split(/:/,$vkeys);
2786: my $key;
2787: $returnhash{"$scope:keys"}=$vkeys;
2788: foreach $key (@keys) {
1.591 albertel 2789: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2790: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2791: }
2792: }
1.168 albertel 2793: if (!(untie(%hash))) {
2794: return "error:$!";
2795: }
2796: } else {
2797: return "error:$!";
2798: }
2799: return %returnhash;
1.167 albertel 2800: }
2801:
1.9 www 2802: # ----------------------------------------------------------------------- Store
2803:
2804: sub store {
1.124 www 2805: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2806: my $home='';
2807:
1.168 albertel 2808: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2809:
1.213 www 2810: $symb=&symbclean($symb);
1.122 albertel 2811: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2812:
1.620 albertel 2813: if (!$domain) { $domain=$env{'user.domain'}; }
2814: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2815:
2816: &devalidate($symb,$stuname,$domain);
1.109 www 2817:
2818: $symb=escape($symb);
1.187 www 2819: if (!$namespace) {
1.620 albertel 2820: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2821: return '';
2822: }
2823: }
1.620 albertel 2824: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2825:
2826: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2827: $$storehash{'host'}=$perlvar{'lonHostID'};
2828:
1.12 www 2829: my $namevalue='';
1.800 albertel 2830: foreach my $key (keys(%$storehash)) {
2831: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2832: }
1.12 www 2833: $namevalue=~s/\&$//;
1.187 www 2834: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2835: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2836: }
2837:
1.47 www 2838: # -------------------------------------------------------------- Critical Store
2839:
2840: sub cstore {
1.124 www 2841: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2842: my $home='';
2843:
1.168 albertel 2844: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2845:
1.213 www 2846: $symb=&symbclean($symb);
1.122 albertel 2847: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2848:
1.620 albertel 2849: if (!$domain) { $domain=$env{'user.domain'}; }
2850: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2851:
2852: &devalidate($symb,$stuname,$domain);
1.109 www 2853:
2854: $symb=escape($symb);
1.187 www 2855: if (!$namespace) {
1.620 albertel 2856: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2857: return '';
2858: }
2859: }
1.620 albertel 2860: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2861:
2862: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2863: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2864:
1.47 www 2865: my $namevalue='';
1.800 albertel 2866: foreach my $key (keys(%$storehash)) {
2867: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2868: }
1.47 www 2869: $namevalue=~s/\&$//;
1.187 www 2870: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2871: return critical
2872: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2873: }
2874:
1.9 www 2875: # --------------------------------------------------------------------- Restore
2876:
2877: sub restore {
1.124 www 2878: my ($symb,$namespace,$domain,$stuname) = @_;
2879: my $home='';
2880:
1.168 albertel 2881: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2882:
1.122 albertel 2883: if (!$symb) {
2884: unless ($symb=escape(&symbread())) { return ''; }
2885: } else {
1.213 www 2886: $symb=&escape(&symbclean($symb));
1.122 albertel 2887: }
1.188 www 2888: if (!$namespace) {
1.620 albertel 2889: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2890: return '';
2891: }
2892: }
1.620 albertel 2893: if (!$domain) { $domain=$env{'user.domain'}; }
2894: if (!$stuname) { $stuname=$env{'user.name'}; }
2895: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2896: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2897:
1.12 www 2898: my %returnhash=();
1.800 albertel 2899: foreach my $line (split(/\&/,$answer)) {
2900: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2901: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2902: }
1.75 www 2903: my $version;
2904: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2905: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2906: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2907: }
1.75 www 2908: }
1.13 www 2909: return %returnhash;
1.34 www 2910: }
2911:
2912: # ---------------------------------------------------------- Course Description
2913:
2914: sub coursedescription {
1.731 albertel 2915: my ($courseid,$args)=@_;
1.34 www 2916: $courseid=~s/^\///;
1.49 www 2917: $courseid=~s/\_/\//g;
1.34 www 2918: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2919: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2920: my $normalid=$cdomain.'_'.$cnum;
2921: # need to always cache even if we get errors otherwise we keep
2922: # trying and trying and trying to get the course description.
2923: my %envhash=();
2924: my %returnhash=();
1.731 albertel 2925:
2926: my $expiretime=600;
2927: if ($env{'request.course.id'} eq $normalid) {
2928: $expiretime=120;
2929: }
2930:
2931: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2932: if (!$args->{'freshen_cache'}
2933: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2934: foreach my $key (keys(%env)) {
2935: next if ($key !~ /^\Q$prefix\E(.*)/);
2936: my ($setting) = $1;
2937: $returnhash{$setting} = $env{$key};
2938: }
2939: return %returnhash;
2940: }
2941:
2942: # get the data agin
2943: if (!$args->{'one_time'}) {
2944: $envhash{'course.'.$normalid.'.last_cache'}=time;
2945: }
1.811 albertel 2946:
1.34 www 2947: if ($chome ne 'no_host') {
1.302 albertel 2948: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2949: if (!exists($returnhash{'con_lost'})) {
2950: $returnhash{'home'}= $chome;
2951: $returnhash{'domain'} = $cdomain;
2952: $returnhash{'num'} = $cnum;
1.741 raeburn 2953: if (!defined($returnhash{'type'})) {
2954: $returnhash{'type'} = 'Course';
2955: }
1.130 albertel 2956: while (my ($name,$value) = each %returnhash) {
1.53 www 2957: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2958: }
1.270 www 2959: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2960: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2961: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2962: $envhash{'course.'.$normalid.'.home'}=$chome;
2963: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2964: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2965: }
2966: }
1.731 albertel 2967: if (!$args->{'one_time'}) {
2968: &appenv(%envhash);
2969: }
1.302 albertel 2970: return %returnhash;
1.461 www 2971: }
2972:
2973: # -------------------------------------------------See if a user is privileged
2974:
2975: sub privileged {
2976: my ($username,$domain)=@_;
2977: my $rolesdump=&reply("dump:$domain:$username:roles",
2978: &homeserver($username,$domain));
2979: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2980: my $now=time;
2981: if ($rolesdump ne '') {
1.800 albertel 2982: foreach my $entry (split(/&/,$rolesdump)) {
2983: if ($entry!~/^rolesdef_/) {
2984: my ($area,$role)=split(/=/,$entry);
1.461 www 2985: $area=~s/\_\w\w$//;
2986: my ($trole,$tend,$tstart)=split(/_/,$role);
2987: if (($trole eq 'dc') || ($trole eq 'su')) {
2988: my $active=1;
2989: if ($tend) {
2990: if ($tend<$now) { $active=0; }
2991: }
2992: if ($tstart) {
2993: if ($tstart>$now) { $active=0; }
2994: }
2995: if ($active) { return 1; }
2996: }
2997: }
2998: }
2999: }
3000: return 0;
1.9 www 3001: }
1.1 albertel 3002:
1.103 harris41 3003: # -------------------------------------------------------- Get user privileges
1.11 www 3004:
3005: sub rolesinit {
3006: my ($domain,$username,$authhost)=@_;
3007: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3008: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3009: my %allroles=();
1.678 raeburn 3010: my %allgroups=();
1.11 www 3011: my $now=time;
1.743 albertel 3012: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3013: my $group_privs;
1.11 www 3014:
3015: if ($rolesdump ne '') {
1.800 albertel 3016: foreach my $entry (split(/&/,$rolesdump)) {
3017: if ($entry!~/^rolesdef_/) {
3018: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3019: $area=~s/\_\w\w$//;
1.678 raeburn 3020: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3021: if ($role=~/^cr/) {
1.807 albertel 3022: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3023: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3024: ($tend,$tstart)=split('_',$trest);
3025: } else {
3026: $trole=$role;
3027: }
1.678 raeburn 3028: } elsif ($role =~ m|^gr/|) {
3029: ($trole,$tend,$tstart) = split(/_/,$role);
3030: ($trole,$group_privs) = split(/\//,$trole);
3031: $group_privs = &unescape($group_privs);
1.587 albertel 3032: } else {
3033: ($trole,$tend,$tstart)=split(/_/,$role);
3034: }
1.743 albertel 3035: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3036: $username);
3037: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3038: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3039: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3040: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3041: my $spec=$trole.'.'.$area;
3042: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3043: if ($trole =~ /^cr\//) {
1.567 raeburn 3044: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3045: } elsif ($trole eq 'gr') {
3046: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3047: } else {
1.567 raeburn 3048: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3049: }
1.12 www 3050: }
1.662 raeburn 3051: }
1.191 harris41 3052: }
1.743 albertel 3053: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3054: $userroles{'user.adv'} = $adv;
3055: $userroles{'user.author'} = $author;
1.620 albertel 3056: $env{'user.adv'}=$adv;
1.11 www 3057: }
1.743 albertel 3058: return \%userroles;
1.11 www 3059: }
3060:
1.567 raeburn 3061: sub set_arearole {
3062: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3063: # log the associated role with the area
3064: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3065: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3066: }
3067:
3068: sub custom_roleprivs {
3069: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3070: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3071: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3072: if (&hostname($homsvr) ne '') {
1.567 raeburn 3073: my ($rdummy,$roledef)=
3074: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3075: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3076: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3077: if (defined($syspriv)) {
3078: $$allroles{'cm./'}.=':'.$syspriv;
3079: $$allroles{$spec.'./'}.=':'.$syspriv;
3080: }
3081: if ($tdomain ne '') {
3082: if (defined($dompriv)) {
3083: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3084: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3085: }
3086: if (($trest ne '') && (defined($coursepriv))) {
3087: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3088: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3089: }
3090: }
3091: }
3092: }
3093: }
3094:
1.678 raeburn 3095: sub group_roleprivs {
3096: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3097: my $access = 1;
3098: my $now = time;
3099: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3100: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3101: if ($access) {
1.811 albertel 3102: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3103: $$allgroups{$course}{$group} .=':'.$group_privs;
3104: }
3105: }
1.567 raeburn 3106:
3107: sub standard_roleprivs {
3108: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3109: if (defined($pr{$trole.':s'})) {
3110: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3111: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3112: }
3113: if ($tdomain ne '') {
3114: if (defined($pr{$trole.':d'})) {
3115: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3116: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3117: }
3118: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3119: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3120: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3121: }
3122: }
3123: }
3124:
3125: sub set_userprivs {
1.678 raeburn 3126: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3127: my $author=0;
3128: my $adv=0;
1.678 raeburn 3129: my %grouproles = ();
3130: if (keys(%{$allgroups}) > 0) {
3131: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3132: my ($trole,$area,$sec,$extendedarea);
1.811 albertel 3133: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678 raeburn 3134: $trole = $1;
3135: $area = $2;
1.681 raeburn 3136: $sec = $3;
3137: $extendedarea = $area.$sec;
3138: if (exists($$allgroups{$area})) {
3139: foreach my $group (keys(%{$$allgroups{$area}})) {
3140: my $spec = $trole.'.'.$extendedarea;
3141: $grouproles{$spec.'.'.$area.'/'.$group} =
3142: $$allgroups{$area}{$group};
1.678 raeburn 3143: }
3144: }
3145: }
3146: }
3147: }
1.800 albertel 3148: foreach my $group (keys(%grouproles)) {
3149: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3150: }
1.800 albertel 3151: foreach my $role (keys(%{$allroles})) {
3152: my %thesepriv;
3153: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3154: foreach my $item (split(/:/,$$allroles{$role})) {
3155: if ($item ne '') {
3156: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3157: if ($restrictions eq '') {
3158: $thesepriv{$privilege}='F';
3159: } elsif ($thesepriv{$privilege} ne 'F') {
3160: $thesepriv{$privilege}.=$restrictions;
3161: }
3162: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3163: }
3164: }
3165: my $thesestr='';
1.800 albertel 3166: foreach my $priv (keys(%thesepriv)) {
3167: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3168: }
3169: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3170: }
3171: return ($author,$adv);
3172: }
3173:
1.12 www 3174: # --------------------------------------------------------------- get interface
3175:
3176: sub get {
1.131 albertel 3177: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3178: my $items='';
1.800 albertel 3179: foreach my $item (@$storearr) {
3180: $items.=&escape($item).'&';
1.191 harris41 3181: }
1.12 www 3182: $items=~s/\&$//;
1.620 albertel 3183: if (!$udomain) { $udomain=$env{'user.domain'}; }
3184: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3185: my $uhome=&homeserver($uname,$udomain);
3186:
1.133 albertel 3187: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3188: my @pairs=split(/\&/,$rep);
1.273 albertel 3189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3190: return @pairs;
3191: }
1.15 www 3192: my %returnhash=();
1.42 www 3193: my $i=0;
1.800 albertel 3194: foreach my $item (@$storearr) {
3195: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3196: $i++;
1.191 harris41 3197: }
1.15 www 3198: return %returnhash;
1.27 www 3199: }
3200:
3201: # --------------------------------------------------------------- del interface
3202:
3203: sub del {
1.133 albertel 3204: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3205: my $items='';
1.800 albertel 3206: foreach my $item (@$storearr) {
3207: $items.=&escape($item).'&';
1.191 harris41 3208: }
1.27 www 3209: $items=~s/\&$//;
1.620 albertel 3210: if (!$udomain) { $udomain=$env{'user.domain'}; }
3211: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3212: my $uhome=&homeserver($uname,$udomain);
3213:
3214: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3215: }
3216:
3217: # -------------------------------------------------------------- dump interface
3218:
3219: sub dump {
1.755 albertel 3220: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3221: if (!$udomain) { $udomain=$env{'user.domain'}; }
3222: if (!$uname) { $uname=$env{'user.name'}; }
3223: my $uhome=&homeserver($uname,$udomain);
3224: if ($regexp) {
3225: $regexp=&escape($regexp);
3226: } else {
3227: $regexp='.';
3228: }
3229: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3230: my @pairs=split(/\&/,$rep);
3231: my %returnhash=();
3232: foreach my $item (@pairs) {
3233: my ($key,$value)=split(/=/,$item,2);
3234: $key = &unescape($key);
3235: next if ($key =~ /^error: 2 /);
3236: $returnhash{$key}=&thaw_unescape($value);
3237: }
3238: return %returnhash;
1.407 www 3239: }
3240:
1.717 albertel 3241: # --------------------------------------------------------- dumpstore interface
3242:
3243: sub dumpstore {
3244: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3245: if (!$udomain) { $udomain=$env{'user.domain'}; }
3246: if (!$uname) { $uname=$env{'user.name'}; }
3247: my $uhome=&homeserver($uname,$udomain);
3248: if ($regexp) {
3249: $regexp=&escape($regexp);
3250: } else {
3251: $regexp='.';
3252: }
3253: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3254: my @pairs=split(/\&/,$rep);
3255: my %returnhash=();
3256: foreach my $item (@pairs) {
3257: my ($key,$value)=split(/=/,$item,2);
3258: next if ($key =~ /^error: 2 /);
3259: $returnhash{$key}=&thaw_unescape($value);
3260: }
3261: return %returnhash;
1.717 albertel 3262: }
3263:
1.407 www 3264: # -------------------------------------------------------------- keys interface
3265:
3266: sub getkeys {
3267: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3268: if (!$udomain) { $udomain=$env{'user.domain'}; }
3269: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3270: my $uhome=&homeserver($uname,$udomain);
3271: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3272: my @keyarray=();
1.800 albertel 3273: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3274: next if ($key =~ /^error: 2 /);
1.800 albertel 3275: push(@keyarray,&unescape($key));
1.407 www 3276: }
3277: return @keyarray;
1.318 matthew 3278: }
3279:
1.319 matthew 3280: # --------------------------------------------------------------- currentdump
3281: sub currentdump {
1.328 matthew 3282: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3283: $courseid = $env{'request.course.id'} if (! defined($courseid));
3284: $sdom = $env{'user.domain'} if (! defined($sdom));
3285: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3286: my $uhome = &homeserver($sname,$sdom);
3287: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3288: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3289: #
1.318 matthew 3290: my %returnhash=();
1.319 matthew 3291: #
3292: if ($rep eq "unknown_cmd") {
3293: # an old lond will not know currentdump
3294: # Do a dump and make it look like a currentdump
1.822 albertel 3295: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3296: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3297: my %hash = @tmp;
3298: @tmp=();
1.424 matthew 3299: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3300: } else {
3301: my @pairs=split(/\&/,$rep);
1.800 albertel 3302: foreach my $pair (@pairs) {
3303: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3304: my ($symb,$param) = split(/:/,$key);
3305: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3306: &thaw_unescape($value);
1.319 matthew 3307: }
1.191 harris41 3308: }
1.12 www 3309: return %returnhash;
1.424 matthew 3310: }
3311:
3312: sub convert_dump_to_currentdump{
3313: my %hash = %{shift()};
3314: my %returnhash;
3315: # Code ripped from lond, essentially. The only difference
3316: # here is the unescaping done by lonnet::dump(). Conceivably
3317: # we might run in to problems with parameter names =~ /^v\./
3318: while (my ($key,$value) = each(%hash)) {
3319: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3320: $symb = &unescape($symb);
3321: $param = &unescape($param);
1.424 matthew 3322: next if ($v eq 'version' || $symb eq 'keys');
3323: next if (exists($returnhash{$symb}) &&
3324: exists($returnhash{$symb}->{$param}) &&
3325: $returnhash{$symb}->{'v.'.$param} > $v);
3326: $returnhash{$symb}->{$param}=$value;
3327: $returnhash{$symb}->{'v.'.$param}=$v;
3328: }
3329: #
3330: # Remove all of the keys in the hashes which keep track of
3331: # the version of the parameter.
3332: while (my ($symb,$param_hash) = each(%returnhash)) {
3333: # use a foreach because we are going to delete from the hash.
3334: foreach my $key (keys(%$param_hash)) {
3335: delete($param_hash->{$key}) if ($key =~ /^v\./);
3336: }
3337: }
3338: return \%returnhash;
1.12 www 3339: }
3340:
1.627 albertel 3341: # ------------------------------------------------------ critical inc interface
3342:
3343: sub cinc {
3344: return &inc(@_,'critical');
3345: }
3346:
1.449 matthew 3347: # --------------------------------------------------------------- inc interface
3348:
3349: sub inc {
1.627 albertel 3350: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3351: if (!$udomain) { $udomain=$env{'user.domain'}; }
3352: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3353: my $uhome=&homeserver($uname,$udomain);
3354: my $items='';
3355: if (! ref($store)) {
3356: # got a single value, so use that instead
3357: $items = &escape($store).'=&';
3358: } elsif (ref($store) eq 'SCALAR') {
3359: $items = &escape($$store).'=&';
3360: } elsif (ref($store) eq 'ARRAY') {
3361: $items = join('=&',map {&escape($_);} @{$store});
3362: } elsif (ref($store) eq 'HASH') {
3363: while (my($key,$value) = each(%{$store})) {
3364: $items.= &escape($key).'='.&escape($value).'&';
3365: }
3366: }
3367: $items=~s/\&$//;
1.627 albertel 3368: if ($critical) {
3369: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3370: } else {
3371: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3372: }
1.449 matthew 3373: }
3374:
1.12 www 3375: # --------------------------------------------------------------- put interface
3376:
3377: sub put {
1.134 albertel 3378: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3379: if (!$udomain) { $udomain=$env{'user.domain'}; }
3380: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3381: my $uhome=&homeserver($uname,$udomain);
1.12 www 3382: my $items='';
1.800 albertel 3383: foreach my $item (keys(%$storehash)) {
3384: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3385: }
1.12 www 3386: $items=~s/\&$//;
1.134 albertel 3387: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3388: }
3389:
1.631 albertel 3390: # ------------------------------------------------------------ newput interface
3391:
3392: sub newput {
3393: my ($namespace,$storehash,$udomain,$uname)=@_;
3394: if (!$udomain) { $udomain=$env{'user.domain'}; }
3395: if (!$uname) { $uname=$env{'user.name'}; }
3396: my $uhome=&homeserver($uname,$udomain);
3397: my $items='';
3398: foreach my $key (keys(%$storehash)) {
3399: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3400: }
3401: $items=~s/\&$//;
3402: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3403: }
3404:
3405: # --------------------------------------------------------- putstore interface
3406:
1.524 raeburn 3407: sub putstore {
1.715 albertel 3408: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3409: if (!$udomain) { $udomain=$env{'user.domain'}; }
3410: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3411: my $uhome=&homeserver($uname,$udomain);
3412: my $items='';
1.715 albertel 3413: foreach my $key (keys(%$storehash)) {
3414: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3415: }
1.715 albertel 3416: $items=~s/\&$//;
1.716 albertel 3417: my $esc_symb=&escape($symb);
3418: my $esc_v=&escape($version);
1.715 albertel 3419: my $reply =
1.716 albertel 3420: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3421: $uhome);
3422: if ($reply eq 'unknown_cmd') {
1.716 albertel 3423: # gfall back to way things use to be done
1.715 albertel 3424: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3425: $uname);
1.524 raeburn 3426: }
1.715 albertel 3427: return $reply;
3428: }
3429:
3430: sub old_putstore {
1.716 albertel 3431: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3432: if (!$udomain) { $udomain=$env{'user.domain'}; }
3433: if (!$uname) { $uname=$env{'user.name'}; }
3434: my $uhome=&homeserver($uname,$udomain);
3435: my %newstorehash;
1.800 albertel 3436: foreach my $item (keys(%$storehash)) {
3437: my $key = $version.':'.&escape($symb).':'.$item;
3438: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3439: }
3440: my $items='';
3441: my %allitems = ();
1.800 albertel 3442: foreach my $item (keys(%newstorehash)) {
3443: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3444: my $key = $1.':keys:'.$2;
3445: $allitems{$key} .= $3.':';
3446: }
1.800 albertel 3447: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3448: }
1.800 albertel 3449: foreach my $item (keys(%allitems)) {
3450: $allitems{$item} =~ s/\:$//;
3451: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3452: }
3453: $items=~s/\&$//;
3454: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3455: }
3456:
1.47 www 3457: # ------------------------------------------------------ critical put interface
3458:
3459: sub cput {
1.134 albertel 3460: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3461: if (!$udomain) { $udomain=$env{'user.domain'}; }
3462: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3463: my $uhome=&homeserver($uname,$udomain);
1.47 www 3464: my $items='';
1.800 albertel 3465: foreach my $item (keys(%$storehash)) {
3466: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3467: }
1.47 www 3468: $items=~s/\&$//;
1.134 albertel 3469: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3470: }
3471:
3472: # -------------------------------------------------------------- eget interface
3473:
3474: sub eget {
1.133 albertel 3475: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3476: my $items='';
1.800 albertel 3477: foreach my $item (@$storearr) {
3478: $items.=&escape($item).'&';
1.191 harris41 3479: }
1.12 www 3480: $items=~s/\&$//;
1.620 albertel 3481: if (!$udomain) { $udomain=$env{'user.domain'}; }
3482: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3483: my $uhome=&homeserver($uname,$udomain);
3484: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3485: my @pairs=split(/\&/,$rep);
3486: my %returnhash=();
1.42 www 3487: my $i=0;
1.800 albertel 3488: foreach my $item (@$storearr) {
3489: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3490: $i++;
1.191 harris41 3491: }
1.12 www 3492: return %returnhash;
3493: }
3494:
1.667 albertel 3495: # ------------------------------------------------------------ tmpput interface
3496: sub tmpput {
1.802 raeburn 3497: my ($storehash,$server,$context)=@_;
1.667 albertel 3498: my $items='';
1.800 albertel 3499: foreach my $item (keys(%$storehash)) {
3500: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3501: }
3502: $items=~s/\&$//;
1.802 raeburn 3503: if (defined($context)) {
3504: $items .= ':'.&escape($context);
3505: }
1.667 albertel 3506: return &reply("tmpput:$items",$server);
3507: }
3508:
3509: # ------------------------------------------------------------ tmpget interface
3510: sub tmpget {
1.688 albertel 3511: my ($token,$server)=@_;
3512: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3513: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3514: my %returnhash;
3515: foreach my $item (split(/\&/,$rep)) {
3516: my ($key,$value)=split(/=/,$item);
3517: $returnhash{&unescape($key)}=&thaw_unescape($value);
3518: }
3519: return %returnhash;
3520: }
3521:
1.688 albertel 3522: # ------------------------------------------------------------ tmpget interface
3523: sub tmpdel {
3524: my ($token,$server)=@_;
3525: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3526: return &reply("tmpdel:$token",$server);
3527: }
3528:
1.765 albertel 3529: # -------------------------------------------------- portfolio access checking
3530:
3531: sub portfolio_access {
1.766 albertel 3532: my ($requrl) = @_;
1.765 albertel 3533: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3534: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3535: if ($result) {
3536: my %setters;
3537: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3538: my ($startblock,$endblock) =
3539: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3540: if ($startblock && $endblock) {
3541: return 'B';
3542: }
3543: } else {
3544: my ($startblock,$endblock) =
3545: &Apache::loncommon::blockcheck(\%setters,'port');
3546: if ($startblock && $endblock) {
3547: return 'B';
3548: }
3549: }
3550: }
1.765 albertel 3551: if ($result eq 'ok') {
1.766 albertel 3552: return 'F';
1.765 albertel 3553: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3554: return 'A';
1.765 albertel 3555: }
1.766 albertel 3556: return '';
1.765 albertel 3557: }
3558:
3559: sub get_portfolio_access {
1.767 albertel 3560: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3561:
3562: if (!ref($access_hash)) {
3563: my $current_perms = &get_portfile_permissions($udom,$unum);
3564: my %access_controls = &get_access_controls($current_perms,$group,
3565: $file_name);
3566: $access_hash = $access_controls{$file_name};
3567: }
3568:
1.765 albertel 3569: my ($public,$guest,@domains,@users,@courses,@groups);
3570: my $now = time;
3571: if (ref($access_hash) eq 'HASH') {
3572: foreach my $key (keys(%{$access_hash})) {
3573: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3574: if ($start > $now) {
3575: next;
3576: }
3577: if ($end && $end<$now) {
3578: next;
3579: }
3580: if ($scope eq 'public') {
3581: $public = $key;
3582: last;
3583: } elsif ($scope eq 'guest') {
3584: $guest = $key;
3585: } elsif ($scope eq 'domains') {
3586: push(@domains,$key);
3587: } elsif ($scope eq 'users') {
3588: push(@users,$key);
3589: } elsif ($scope eq 'course') {
3590: push(@courses,$key);
3591: } elsif ($scope eq 'group') {
3592: push(@groups,$key);
3593: }
3594: }
3595: if ($public) {
3596: return 'ok';
3597: }
3598: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3599: if ($guest) {
3600: return $guest;
3601: }
3602: } else {
3603: if (@domains > 0) {
3604: foreach my $domkey (@domains) {
3605: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3606: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3607: return 'ok';
3608: }
3609: }
3610: }
3611: }
3612: if (@users > 0) {
3613: foreach my $userkey (@users) {
1.865 raeburn 3614: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3615: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3616: if (ref($item) eq 'HASH') {
3617: if (($item->{'uname'} eq $env{'user.name'}) &&
3618: ($item->{'udom'} eq $env{'user.domain'})) {
3619: return 'ok';
3620: }
3621: }
3622: }
3623: }
1.765 albertel 3624: }
3625: }
3626: my %roleshash;
3627: my @courses_and_groups = @courses;
3628: push(@courses_and_groups,@groups);
3629: if (@courses_and_groups > 0) {
3630: my (%allgroups,%allroles);
3631: my ($start,$end,$role,$sec,$group);
3632: foreach my $envkey (%env) {
1.811 albertel 3633: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3634: my $cid = $2.'_'.$3;
3635: if ($1 eq 'gr') {
3636: $group = $4;
3637: $allgroups{$cid}{$group} = $env{$envkey};
3638: } else {
3639: if ($4 eq '') {
3640: $sec = 'none';
3641: } else {
3642: $sec = $4;
3643: }
3644: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3645: }
1.811 albertel 3646: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3647: my $cid = $2.'_'.$3;
3648: if ($4 eq '') {
3649: $sec = 'none';
3650: } else {
3651: $sec = $4;
3652: }
3653: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3654: }
3655: }
3656: if (keys(%allroles) == 0) {
3657: return;
3658: }
3659: foreach my $key (@courses_and_groups) {
3660: my %content = %{$$access_hash{$key}};
3661: my $cnum = $content{'number'};
3662: my $cdom = $content{'domain'};
3663: my $cid = $cdom.'_'.$cnum;
3664: if (!exists($allroles{$cid})) {
3665: next;
3666: }
3667: foreach my $role_id (keys(%{$content{'roles'}})) {
3668: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3669: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3670: my @status = @{$content{'roles'}{$role_id}{'access'}};
3671: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3672: foreach my $role (keys(%{$allroles{$cid}})) {
3673: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3674: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3675: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3676: if (grep/^all$/,@sections) {
3677: return 'ok';
3678: } else {
3679: if (grep/^$sec$/,@sections) {
3680: return 'ok';
3681: }
3682: }
3683: }
3684: }
3685: if (keys(%{$allgroups{$cid}}) == 0) {
3686: if (grep/^none$/,@groups) {
3687: return 'ok';
3688: }
3689: } else {
3690: if (grep/^all$/,@groups) {
3691: return 'ok';
3692: }
3693: foreach my $group (keys(%{$allgroups{$cid}})) {
3694: if (grep/^$group$/,@groups) {
3695: return 'ok';
3696: }
3697: }
3698: }
3699: }
3700: }
3701: }
3702: }
3703: }
3704: if ($guest) {
3705: return $guest;
3706: }
3707: }
3708: }
3709: return;
3710: }
3711:
3712: sub course_group_datechecker {
3713: my ($dates,$now,$status) = @_;
3714: my ($start,$end) = split(/\./,$dates);
3715: if (!$start && !$end) {
3716: return 'ok';
3717: }
3718: if (grep/^active$/,@{$status}) {
3719: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3720: return 'ok';
3721: }
3722: }
3723: if (grep/^previous$/,@{$status}) {
3724: if ($end > $now ) {
3725: return 'ok';
3726: }
3727: }
3728: if (grep/^future$/,@{$status}) {
3729: if ($start > $now) {
3730: return 'ok';
3731: }
3732: }
3733: return;
3734: }
3735:
3736: sub parse_portfolio_url {
3737: my ($url) = @_;
3738:
3739: my ($type,$udom,$unum,$group,$file_name);
3740:
1.823 albertel 3741: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 3742: $type = 1;
3743: $udom = $1;
3744: $unum = $2;
3745: $file_name = $3;
1.823 albertel 3746: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 3747: $type = 2;
3748: $udom = $1;
3749: $unum = $2;
3750: $group = $3;
3751: $file_name = $3.'/'.$4;
3752: }
3753: if (wantarray) {
3754: return ($type,$udom,$unum,$file_name,$group);
3755: }
3756: return $type;
3757: }
3758:
3759: sub is_portfolio_url {
3760: my ($url) = @_;
3761: return scalar(&parse_portfolio_url($url));
3762: }
3763:
1.798 raeburn 3764: sub is_portfolio_file {
3765: my ($file) = @_;
1.820 raeburn 3766: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 3767: return 1;
3768: }
3769: return;
3770: }
3771:
3772:
1.341 www 3773: # ---------------------------------------------- Custom access rule evaluation
3774:
3775: sub customaccess {
3776: my ($priv,$uri)=@_;
1.807 albertel 3777: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 3778: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 3779: $udom = &LONCAPA::clean_domain($udom);
3780: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 3781: my $access=0;
1.800 albertel 3782: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3783: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3784: if ($role) {
3785: if ($role ne $urole) { next; }
3786: }
1.800 albertel 3787: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3788: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3789: if ($tdom) {
3790: if ($tdom ne $udom) { next; }
3791: }
3792: if ($tcrs) {
3793: if ($tcrs ne $ucrs) { next; }
3794: }
3795: if ($tsec) {
3796: if ($tsec ne $usec) { next; }
3797: }
3798: $access=($effect eq 'allow');
3799: last;
1.342 www 3800: }
1.402 bowersj2 3801: if ($realm eq '' && $role eq '') {
3802: $access=($effect eq 'allow');
3803: }
1.341 www 3804: }
3805: return $access;
3806: }
3807:
1.103 harris41 3808: # ------------------------------------------------- Check for a user privilege
1.12 www 3809:
3810: sub allowed {
1.810 raeburn 3811: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 3812: my $ver_orguri=$uri;
1.439 www 3813: $uri=&deversion($uri);
1.152 www 3814: my $orguri=$uri;
1.52 www 3815: $uri=&declutter($uri);
1.809 raeburn 3816:
1.810 raeburn 3817: if ($priv eq 'evb') {
3818: # Evade communication block restrictions for specified role in a course
3819: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3820: return $1;
3821: } else {
3822: return;
3823: }
3824: }
3825:
1.620 albertel 3826: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3827: # Free bre access to adm and meta resources
1.775 albertel 3828: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3829: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3830: && ($priv eq 'bre')) {
1.14 www 3831: return 'F';
1.159 www 3832: }
3833:
1.545 banghart 3834: # Free bre access to user's own portfolio contents
1.714 raeburn 3835: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3836: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3837: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 3838: my %setters;
3839: my ($startblock,$endblock) =
3840: &Apache::loncommon::blockcheck(\%setters,'port');
3841: if ($startblock && $endblock) {
3842: return 'B';
3843: } else {
3844: return 'F';
3845: }
1.545 banghart 3846: }
3847:
1.762 raeburn 3848: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3849: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3850: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3851: if (exists($env{'request.course.id'})) {
3852: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3853: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3854: if (($domain eq $cdom) && ($name eq $cnum)) {
3855: my $courseprivid=$env{'request.course.id'};
3856: $courseprivid=~s/\_/\//;
3857: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3858: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3859: return $1;
1.762 raeburn 3860: } else {
3861: if ($env{'request.course.sec'}) {
3862: $courseprivid.='/'.$env{'request.course.sec'};
3863: }
3864: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3865: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3866: return $2;
3867: }
1.714 raeburn 3868: }
3869: }
3870: }
3871: }
3872:
1.159 www 3873: # Free bre to public access
3874:
3875: if ($priv eq 'bre') {
1.238 www 3876: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3877: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3878: return 'F';
3879: }
1.238 www 3880: if ($copyright eq 'priv') {
3881: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3882: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3883: return '';
3884: }
3885: }
3886: if ($copyright eq 'domain') {
3887: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3888: unless (($env{'user.domain'} eq $1) ||
3889: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3890: return '';
3891: }
1.262 matthew 3892: }
1.620 albertel 3893: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3894: # Library role, so allow browsing of resources in this domain.
3895: return 'F';
1.238 www 3896: }
1.341 www 3897: if ($copyright eq 'custom') {
3898: unless (&customaccess($priv,$uri)) { return ''; }
3899: }
1.14 www 3900: }
1.264 matthew 3901: # Domain coordinator is trying to create a course
1.620 albertel 3902: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3903: # uri is the requested domain in this case.
3904: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3905: # a role of dc for the domain in question.
1.620 albertel 3906: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3907: }
1.29 www 3908:
1.52 www 3909: my $thisallowed='';
3910: my $statecond=0;
3911: my $courseprivid='';
3912:
3913: # Course
3914:
1.620 albertel 3915: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3916: $thisallowed.=$1;
3917: }
1.29 www 3918:
1.52 www 3919: # Domain
3920:
1.620 albertel 3921: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3922: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3923: $thisallowed.=$1;
3924: }
1.52 www 3925:
3926: # Course: uri itself is a course
1.66 www 3927: my $courseuri=$uri;
3928: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3929: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3930:
1.620 albertel 3931: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3932: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3933: $thisallowed.=$1;
3934: }
1.29 www 3935:
1.665 albertel 3936: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3937: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3938: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3939: $thisallowed='';
1.671 raeburn 3940: my ($match)=&is_on_map($uri);
3941: if ($match) {
3942: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3943: =~/\Q$priv\E\&([^\:]*)/) {
3944: $thisallowed.=$1;
3945: }
3946: } else {
1.705 albertel 3947: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3948: if ($refuri) {
3949: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3950: $thisallowed='F';
1.671 raeburn 3951: } else {
3952: $refuri=&declutter($refuri);
3953: my ($match) = &is_on_map($refuri);
3954: if ($match) {
3955: $thisallowed='F';
3956: }
1.669 raeburn 3957: }
1.671 raeburn 3958: }
3959: }
1.314 www 3960: }
1.492 albertel 3961:
1.766 albertel 3962: if ($priv eq 'bre'
3963: && $thisallowed ne 'F'
3964: && $thisallowed ne '2'
3965: && &is_portfolio_url($uri)) {
3966: $thisallowed = &portfolio_access($uri);
3967: }
3968:
1.52 www 3969: # Full access at system, domain or course-wide level? Exit.
1.29 www 3970:
3971: if ($thisallowed=~/F/) {
3972: return 'F';
3973: }
3974:
1.52 www 3975: # If this is generating or modifying users, exit with special codes
1.29 www 3976:
1.643 www 3977: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3978: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3979: my ($audom,$auname)=split('/',$uri);
1.643 www 3980: # no author name given, so this just checks on the general right to make a co-author in this domain
3981: unless ($auname) { return $thisallowed; }
3982: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3983: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3984: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3985: ($audom ne $env{'request.role.domain'}))) { return ''; }
3986: }
1.52 www 3987: return $thisallowed;
3988: }
3989: #
1.103 harris41 3990: # Gathered so far: system, domain and course wide privileges
1.52 www 3991: #
3992: # Course: See if uri or referer is an individual resource that is part of
3993: # the course
3994:
1.620 albertel 3995: if ($env{'request.course.id'}) {
1.232 www 3996:
1.620 albertel 3997: $courseprivid=$env{'request.course.id'};
3998: if ($env{'request.course.sec'}) {
3999: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4000: }
4001: $courseprivid=~s/\_/\//;
4002: my $checkreferer=1;
1.232 www 4003: my ($match,$cond)=&is_on_map($uri);
4004: if ($match) {
4005: $statecond=$cond;
1.620 albertel 4006: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4007: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4008: $thisallowed.=$1;
4009: $checkreferer=0;
4010: }
1.29 www 4011: }
1.83 www 4012:
1.148 www 4013: if ($checkreferer) {
1.620 albertel 4014: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4015: unless ($refuri) {
1.800 albertel 4016: foreach my $key (keys(%env)) {
4017: if ($key=~/^httpref\..*\*/) {
4018: my $pattern=$key;
1.156 www 4019: $pattern=~s/^httpref\.\/res\///;
1.148 www 4020: $pattern=~s/\*/\[\^\/\]\+/g;
4021: $pattern=~s/\//\\\//g;
1.152 www 4022: if ($orguri=~/$pattern/) {
1.800 albertel 4023: $refuri=$env{$key};
1.148 www 4024: }
4025: }
1.191 harris41 4026: }
1.148 www 4027: }
1.232 www 4028:
1.148 www 4029: if ($refuri) {
1.152 www 4030: $refuri=&declutter($refuri);
1.232 www 4031: my ($match,$cond)=&is_on_map($refuri);
4032: if ($match) {
4033: my $refstatecond=$cond;
1.620 albertel 4034: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4035: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4036: $thisallowed.=$1;
1.53 www 4037: $uri=$refuri;
4038: $statecond=$refstatecond;
1.52 www 4039: }
4040: }
1.148 www 4041: }
1.29 www 4042: }
1.52 www 4043: }
1.29 www 4044:
1.52 www 4045: #
1.103 harris41 4046: # Gathered now: all privileges that could apply, and condition number
1.52 www 4047: #
4048: #
4049: # Full or no access?
4050: #
1.29 www 4051:
1.52 www 4052: if ($thisallowed=~/F/) {
4053: return 'F';
4054: }
1.29 www 4055:
1.52 www 4056: unless ($thisallowed) {
4057: return '';
4058: }
1.29 www 4059:
1.52 www 4060: # Restrictions exist, deal with them
4061: #
4062: # C:according to course preferences
4063: # R:according to resource settings
4064: # L:unless locked
4065: # X:according to user session state
4066: #
4067:
4068: # Possibly locked functionality, check all courses
1.54 www 4069: # Locks might take effect only after 10 minutes cache expiration for other
4070: # courses, and 2 minutes for current course
1.52 www 4071:
4072: my $envkey;
4073: if ($thisallowed=~/L/) {
1.620 albertel 4074: foreach $envkey (keys %env) {
1.54 www 4075: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4076: my $courseid=$2;
4077: my $roleid=$1.'.'.$2;
1.92 www 4078: $courseid=~s/^\///;
1.54 www 4079: my $expiretime=600;
1.620 albertel 4080: if ($env{'request.role'} eq $roleid) {
1.54 www 4081: $expiretime=120;
4082: }
4083: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4084: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4085: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4086: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4087: }
1.620 albertel 4088: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4089: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4090: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4091: &log($env{'user.domain'},$env{'user.name'},
4092: $env{'user.home'},
1.57 www 4093: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4094: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4095: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4096: return '';
4097: }
4098: }
1.620 albertel 4099: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4100: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4101: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4102: &log($env{'user.domain'},$env{'user.name'},
4103: $env{'user.home'},
1.57 www 4104: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4105: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4106: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4107: return '';
4108: }
4109: }
4110: }
1.29 www 4111: }
1.52 www 4112: }
4113:
4114: #
4115: # Rest of the restrictions depend on selected course
4116: #
4117:
1.620 albertel 4118: unless ($env{'request.course.id'}) {
1.766 albertel 4119: if ($thisallowed eq 'A') {
4120: return 'A';
1.814 raeburn 4121: } elsif ($thisallowed eq 'B') {
4122: return 'B';
1.766 albertel 4123: } else {
4124: return '1';
4125: }
1.52 www 4126: }
1.29 www 4127:
1.52 www 4128: #
4129: # Now user is definitely in a course
4130: #
1.53 www 4131:
4132:
4133: # Course preferences
4134:
4135: if ($thisallowed=~/C/) {
1.620 albertel 4136: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4137: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4138: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4139: =~/\Q$rolecode\E/) {
1.689 albertel 4140: if ($priv ne 'pch') {
4141: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4142: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4143: $env{'request.course.id'});
4144: }
1.237 www 4145: return '';
4146: }
4147:
1.620 albertel 4148: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4149: =~/\Q$unamedom\E/) {
1.689 albertel 4150: if ($priv ne 'pch') {
4151: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4152: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4153: $env{'request.course.id'});
4154: }
1.54 www 4155: return '';
4156: }
1.53 www 4157: }
4158:
4159: # Resource preferences
4160:
4161: if ($thisallowed=~/R/) {
1.620 albertel 4162: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4163: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4164: if ($priv ne 'pch') {
4165: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4166: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4167: }
4168: return '';
1.54 www 4169: }
1.53 www 4170: }
1.30 www 4171:
1.246 www 4172: # Restricted by state or randomout?
1.30 www 4173:
1.52 www 4174: if ($thisallowed=~/X/) {
1.620 albertel 4175: if ($env{'acc.randomout'}) {
1.579 albertel 4176: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4177: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4178: return '';
4179: }
1.247 www 4180: }
4181: if (&condval($statecond)) {
1.52 www 4182: return '2';
4183: } else {
4184: return '';
4185: }
4186: }
1.30 www 4187:
1.766 albertel 4188: if ($thisallowed eq 'A') {
4189: return 'A';
1.814 raeburn 4190: } elsif ($thisallowed eq 'B') {
4191: return 'B';
1.766 albertel 4192: }
1.52 www 4193: return 'F';
1.232 www 4194: }
4195:
1.710 albertel 4196: sub split_uri_for_cond {
4197: my $uri=&deversion(&declutter(shift));
4198: my @uriparts=split(/\//,$uri);
4199: my $filename=pop(@uriparts);
4200: my $pathname=join('/',@uriparts);
4201: return ($pathname,$filename);
4202: }
1.232 www 4203: # --------------------------------------------------- Is a resource on the map?
4204:
4205: sub is_on_map {
1.710 albertel 4206: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4207: #Trying to find the conditional for the file
1.620 albertel 4208: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4209: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4210: if ($match) {
1.289 bowersj2 4211: return (1,$1);
4212: } else {
1.434 www 4213: return (0,0);
1.289 bowersj2 4214: }
1.12 www 4215: }
4216:
1.427 www 4217: # --------------------------------------------------------- Get symb from alias
4218:
4219: sub get_symb_from_alias {
4220: my $symb=shift;
4221: my ($map,$resid,$url)=&decode_symb($symb);
4222: # Already is a symb
4223: if ($url) { return $symb; }
4224: # Must be an alias
4225: my $aliassymb='';
4226: my %bighash;
1.620 albertel 4227: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4228: &GDBM_READER(),0640)) {
4229: my $rid=$bighash{'mapalias_'.$symb};
4230: if ($rid) {
4231: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4232: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4233: $resid,$bighash{'src_'.$rid});
1.427 www 4234: }
4235: untie %bighash;
4236: }
4237: return $aliassymb;
4238: }
4239:
1.12 www 4240: # ----------------------------------------------------------------- Define Role
4241:
4242: sub definerole {
4243: if (allowed('mcr','/')) {
4244: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4245: foreach my $role (split(':',$sysrole)) {
4246: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4247: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4248: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4249: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4250: return "refused:s:$crole&$cqual";
4251: }
4252: }
1.191 harris41 4253: }
1.800 albertel 4254: foreach my $role (split(':',$domrole)) {
4255: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4256: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4257: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4258: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4259: return "refused:d:$crole&$cqual";
4260: }
4261: }
1.191 harris41 4262: }
1.800 albertel 4263: foreach my $role (split(':',$courole)) {
4264: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4265: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4266: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4267: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4268: return "refused:c:$crole&$cqual";
4269: }
4270: }
1.191 harris41 4271: }
1.620 albertel 4272: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4273: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4274: "rolesdef_$rolename=".
4275: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4276: return reply($command,$env{'user.home'});
1.12 www 4277: } else {
4278: return 'refused';
4279: }
1.105 harris41 4280: }
4281:
4282: # ---------------- Make a metadata query against the network of library servers
4283:
4284: sub metadata_query {
1.244 matthew 4285: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4286: my %rhash;
1.845 albertel 4287: my %libserv = &all_library();
1.244 matthew 4288: my @server_list = (defined($server_array) ? @$server_array
4289: : keys(%libserv) );
4290: for my $server (@server_list) {
1.118 harris41 4291: unless ($custom or $customshow) {
4292: my $reply=&reply("querysend:".&escape($query),$server);
4293: $rhash{$server}=$reply;
4294: }
4295: else {
4296: my $reply=&reply("querysend:".&escape($query).':'.
4297: &escape($custom).':'.&escape($customshow),
4298: $server);
4299: $rhash{$server}=$reply;
4300: }
1.112 harris41 4301: }
1.118 harris41 4302: return \%rhash;
1.240 www 4303: }
4304:
4305: # ----------------------------------------- Send log queries and wait for reply
4306:
4307: sub log_query {
4308: my ($uname,$udom,$query,%filters)=@_;
4309: my $uhome=&homeserver($uname,$udom);
4310: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4311: my $uhost=&hostname($uhome);
1.800 albertel 4312: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4313: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4314: $uhome);
1.479 albertel 4315: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4316: return get_query_reply($queryid);
4317: }
4318:
1.818 raeburn 4319: # -------------------------- Update MySQL table for portfolio file
4320:
4321: sub update_portfolio_table {
1.821 raeburn 4322: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4323: my $homeserver = &homeserver($uname,$udom);
4324: my $queryid=
1.821 raeburn 4325: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4326: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4327: my $reply = &get_query_reply($queryid);
4328: return $reply;
4329: }
4330:
1.508 raeburn 4331: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4332:
4333: sub fetch_enrollment_query {
1.511 raeburn 4334: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4335: my $homeserver;
1.547 raeburn 4336: my $maxtries = 1;
1.508 raeburn 4337: if ($context eq 'automated') {
4338: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4339: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4340: } else {
4341: $homeserver = &homeserver($cnum,$dom);
4342: }
1.838 albertel 4343: my $host=&hostname($homeserver);
1.506 raeburn 4344: my $cmd = '';
1.800 albertel 4345: foreach my $affiliate (keys %{$affiliatesref}) {
4346: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4347: }
4348: $cmd =~ s/%%$//;
4349: $cmd = &escape($cmd);
4350: my $query = 'fetchenrollment';
1.620 albertel 4351: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4352: unless ($queryid=~/^\Q$host\E\_/) {
4353: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4354: return 'error: '.$queryid;
4355: }
1.506 raeburn 4356: my $reply = &get_query_reply($queryid);
1.547 raeburn 4357: my $tries = 1;
4358: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4359: $reply = &get_query_reply($queryid);
4360: $tries ++;
4361: }
1.526 raeburn 4362: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4363: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4364: } else {
1.515 raeburn 4365: my @responses = split/:/,$reply;
4366: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4367: foreach my $line (@responses) {
4368: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4369: $$replyref{$key} = $value;
4370: }
4371: } else {
1.506 raeburn 4372: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4373: foreach my $line (@responses) {
4374: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4375: $$replyref{$key} = $value;
4376: if ($value > 0) {
1.800 albertel 4377: foreach my $item (@{$$affiliatesref{$key}}) {
4378: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4379: my $destname = $pathname.'/'.$filename;
4380: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4381: if ($xml_classlist =~ /^error/) {
4382: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4383: } else {
1.506 raeburn 4384: if ( open(FILE,">$destname") ) {
4385: print FILE &unescape($xml_classlist);
4386: close(FILE);
1.526 raeburn 4387: } else {
4388: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4389: }
4390: }
4391: }
4392: }
4393: }
4394: }
4395: return 'ok';
4396: }
4397: return 'error';
4398: }
4399:
1.242 www 4400: sub get_query_reply {
4401: my $queryid=shift;
1.240 www 4402: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4403: my $reply='';
4404: for (1..100) {
4405: sleep 2;
4406: if (-e $replyfile.'.end') {
1.448 albertel 4407: if (open(my $fh,$replyfile)) {
1.240 www 4408: $reply.=<$fh>;
1.448 albertel 4409: close($fh);
1.240 www 4410: } else { return 'error: reply_file_error'; }
1.242 www 4411: return &unescape($reply);
4412: }
1.240 www 4413: }
1.242 www 4414: return 'timeout:'.$queryid;
1.240 www 4415: }
4416:
4417: sub courselog_query {
1.241 www 4418: #
4419: # possible filters:
4420: # url: url or symb
4421: # username
4422: # domain
4423: # action: view, submit, grade
4424: # start: timestamp
4425: # end: timestamp
4426: #
1.240 www 4427: my (%filters)=@_;
1.620 albertel 4428: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4429: if ($filters{'url'}) {
4430: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4431: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4432: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4433: }
1.620 albertel 4434: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4435: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4436: return &log_query($cname,$cdom,'courselog',%filters);
4437: }
4438:
4439: sub userlog_query {
1.858 raeburn 4440: #
4441: # possible filters:
4442: # action: log check role
4443: # start: timestamp
4444: # end: timestamp
4445: #
1.240 www 4446: my ($uname,$udom,%filters)=@_;
4447: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4448: }
4449:
1.506 raeburn 4450: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4451:
4452: sub auto_run {
1.508 raeburn 4453: my ($cnum,$cdom) = @_;
4454: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4455: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4456: return $response;
4457: }
1.776 albertel 4458:
1.506 raeburn 4459: sub auto_get_sections {
1.508 raeburn 4460: my ($cnum,$cdom,$inst_coursecode) = @_;
4461: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4462: my @secs = ();
1.511 raeburn 4463: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4464: unless ($response eq 'refused') {
4465: @secs = split/:/,$response;
4466: }
4467: return @secs;
4468: }
1.776 albertel 4469:
1.506 raeburn 4470: sub auto_new_course {
1.508 raeburn 4471: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4472: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4473: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4474: return $response;
4475: }
1.776 albertel 4476:
1.506 raeburn 4477: sub auto_validate_courseID {
1.508 raeburn 4478: my ($cnum,$cdom,$inst_course_id) = @_;
4479: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4480: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4481: return $response;
4482: }
1.776 albertel 4483:
1.506 raeburn 4484: sub auto_create_password {
1.508 raeburn 4485: my ($cnum,$cdom,$authparam) = @_;
4486: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4487: my $create_passwd = 0;
4488: my $authchk = '';
1.511 raeburn 4489: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4490: if ($response eq 'refused') {
4491: $authchk = 'refused';
4492: } else {
4493: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4494: }
4495: return ($authparam,$create_passwd,$authchk);
4496: }
4497:
1.706 raeburn 4498: sub auto_photo_permission {
4499: my ($cnum,$cdom,$students) = @_;
4500: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4501: my ($outcome,$perm_reqd,$conditions) =
4502: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4503: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4504: return (undef,undef);
4505: }
1.706 raeburn 4506: return ($outcome,$perm_reqd,$conditions);
4507: }
4508:
4509: sub auto_checkphotos {
4510: my ($uname,$udom,$pid) = @_;
4511: my $homeserver = &homeserver($uname,$udom);
4512: my ($result,$resulttype);
4513: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4514: &escape($uname).':'.&escape($pid),
4515: $homeserver));
1.709 albertel 4516: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4517: return (undef,undef);
4518: }
1.706 raeburn 4519: if ($outcome) {
4520: ($result,$resulttype) = split(/:/,$outcome);
4521: }
4522: return ($result,$resulttype);
4523: }
4524:
4525: sub auto_photochoice {
4526: my ($cnum,$cdom) = @_;
4527: my $homeserver = &homeserver($cnum,$cdom);
4528: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4529: &escape($cdom),
4530: $homeserver)));
1.709 albertel 4531: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4532: return (undef,undef);
4533: }
1.706 raeburn 4534: return ($update,$comment);
4535: }
4536:
4537: sub auto_photoupdate {
4538: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4539: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4540: my $host=&hostname($homeserver);
1.706 raeburn 4541: my $cmd = '';
4542: my $maxtries = 1;
1.800 albertel 4543: foreach my $affiliate (keys(%{$affiliatesref})) {
4544: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4545: }
4546: $cmd =~ s/%%$//;
4547: $cmd = &escape($cmd);
4548: my $query = 'institutionalphotos';
4549: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4550: unless ($queryid=~/^\Q$host\E\_/) {
4551: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4552: return 'error: '.$queryid;
4553: }
4554: my $reply = &get_query_reply($queryid);
4555: my $tries = 1;
4556: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4557: $reply = &get_query_reply($queryid);
4558: $tries ++;
4559: }
4560: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4561: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4562: } else {
4563: my @responses = split(/:/,$reply);
4564: my $outcome = shift(@responses);
4565: foreach my $item (@responses) {
4566: my ($key,$value) = split(/=/,$item);
4567: $$photo{$key} = $value;
4568: }
4569: return $outcome;
4570: }
4571: return 'error';
4572: }
4573:
1.521 raeburn 4574: sub auto_instcode_format {
1.793 albertel 4575: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4576: $cat_order) = @_;
1.521 raeburn 4577: my $courses = '';
1.772 raeburn 4578: my @homeservers;
1.521 raeburn 4579: if ($caller eq 'global') {
1.841 albertel 4580: my %servers = &get_servers($codedom,'library');
4581: foreach my $tryserver (keys(%servers)) {
4582: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4583: push(@homeservers,$tryserver);
4584: }
1.584 raeburn 4585: }
1.521 raeburn 4586: } else {
1.772 raeburn 4587: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4588: }
1.793 albertel 4589: foreach my $code (keys(%{$instcodes})) {
4590: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4591: }
4592: chop($courses);
1.772 raeburn 4593: my $ok_response = 0;
4594: my $response;
4595: while (@homeservers > 0 && $ok_response == 0) {
4596: my $server = shift(@homeservers);
4597: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4598: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4599: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4600: split/:/,$response;
1.772 raeburn 4601: %{$codes} = (%{$codes},&str2hash($codes_str));
4602: push(@{$codetitles},&str2array($codetitles_str));
4603: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4604: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4605: $ok_response = 1;
4606: }
4607: }
4608: if ($ok_response) {
1.521 raeburn 4609: return 'ok';
1.772 raeburn 4610: } else {
4611: return $response;
1.521 raeburn 4612: }
4613: }
4614:
1.792 raeburn 4615: sub auto_instcode_defaults {
4616: my ($domain,$returnhash,$code_order) = @_;
4617: my @homeservers;
1.841 albertel 4618:
4619: my %servers = &get_servers($domain,'library');
4620: foreach my $tryserver (keys(%servers)) {
4621: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4622: push(@homeservers,$tryserver);
4623: }
1.792 raeburn 4624: }
1.841 albertel 4625:
1.792 raeburn 4626: my $response;
1.841 albertel 4627: foreach my $server (@homeservers) {
1.792 raeburn 4628: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4629: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4630:
4631: foreach my $pair (split(/\&/,$response)) {
4632: my ($name,$value)=split(/\=/,$pair);
4633: if ($name eq 'code_order') {
4634: @{$code_order} = split(/\&/,&unescape($value));
4635: } else {
4636: $returnhash->{&unescape($name)}=&unescape($value);
4637: }
4638: }
4639: return 'ok';
1.792 raeburn 4640: }
1.841 albertel 4641:
4642: return $response;
1.792 raeburn 4643: }
4644:
1.777 albertel 4645: sub auto_validate_class_sec {
1.773 raeburn 4646: my ($cdom,$cnum,$owner,$inst_class) = @_;
4647: my $homeserver = &homeserver($cnum,$cdom);
4648: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4649: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4650: return $response;
4651: }
4652:
1.679 raeburn 4653: # ------------------------------------------------------- Course Group routines
4654:
4655: sub get_coursegroups {
1.809 raeburn 4656: my ($cdom,$cnum,$group,$namespace) = @_;
4657: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 4658: }
4659:
1.679 raeburn 4660: sub modify_coursegroup {
4661: my ($cdom,$cnum,$groupsettings) = @_;
4662: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4663: }
4664:
1.809 raeburn 4665: sub toggle_coursegroup_status {
4666: my ($cdom,$cnum,$group,$action) = @_;
4667: my ($from_namespace,$to_namespace);
4668: if ($action eq 'delete') {
4669: $from_namespace = 'coursegroups';
4670: $to_namespace = 'deleted_groups';
4671: } else {
4672: $from_namespace = 'deleted_groups';
4673: $to_namespace = 'coursegroups';
4674: }
4675: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 4676: if (my $tmp = &error(%curr_group)) {
4677: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4678: return ('read error',$tmp);
4679: } else {
4680: my %savedsettings = %curr_group;
1.809 raeburn 4681: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 4682: my $deloutcome;
4683: if ($result eq 'ok') {
1.809 raeburn 4684: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 4685: } else {
4686: return ('write error',$result);
4687: }
4688: if ($deloutcome eq 'ok') {
4689: return 'ok';
4690: } else {
4691: return ('delete error',$deloutcome);
4692: }
4693: }
4694: }
4695:
1.679 raeburn 4696: sub modify_group_roles {
4697: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4698: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4699: my $role = 'gr/'.&escape($userprivs);
4700: my ($uname,$udom) = split(/:/,$user);
4701: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4702: if ($result eq 'ok') {
4703: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4704: }
1.679 raeburn 4705: return $result;
4706: }
4707:
4708: sub modify_coursegroup_membership {
4709: my ($cdom,$cnum,$membership) = @_;
4710: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4711: return $result;
4712: }
4713:
1.682 raeburn 4714: sub get_active_groups {
4715: my ($udom,$uname,$cdom,$cnum) = @_;
4716: my $now = time;
4717: my %groups = ();
4718: foreach my $key (keys(%env)) {
1.811 albertel 4719: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 4720: my ($start,$end) = split(/\./,$env{$key});
4721: if (($end!=0) && ($end<$now)) { next; }
4722: if (($start!=0) && ($start>$now)) { next; }
4723: if ($1 eq $cdom && $2 eq $cnum) {
4724: $groups{$3} = $env{$key} ;
4725: }
4726: }
4727: }
4728: return %groups;
4729: }
4730:
1.683 raeburn 4731: sub get_group_membership {
4732: my ($cdom,$cnum,$group) = @_;
4733: return(&dump('groupmembership',$cdom,$cnum,$group));
4734: }
4735:
4736: sub get_users_groups {
4737: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4738: my @usersgroups;
1.683 raeburn 4739: my $cachetime=1800;
4740:
4741: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4742: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4743: if (defined($cached)) {
1.734 albertel 4744: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4745: } else {
4746: $grouplist = '';
1.816 raeburn 4747: my $courseurl = &courseid_to_courseurl($courseid);
4748: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 4749: my $access_end = $env{'course.'.$courseid.
4750: '.default_enrollment_end_date'};
4751: my $now = time;
4752: foreach my $key (keys(%roleshash)) {
4753: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4754: my $group = $1;
4755: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4756: my $start = $2;
4757: my $end = $1;
4758: if ($start == -1) { next; } # deleted from group
4759: if (($start!=0) && ($start>$now)) { next; }
4760: if (($end!=0) && ($end<$now)) {
4761: if ($access_end && $access_end < $now) {
4762: if ($access_end - $end < 86400) {
4763: push(@usersgroups,$group);
1.733 raeburn 4764: }
4765: }
1.817 raeburn 4766: next;
1.733 raeburn 4767: }
1.817 raeburn 4768: push(@usersgroups,$group);
1.683 raeburn 4769: }
4770: }
4771: }
1.817 raeburn 4772: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4773: $grouplist = join(':',@usersgroups);
4774: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4775: }
1.733 raeburn 4776: return @usersgroups;
1.683 raeburn 4777: }
4778:
4779: sub devalidate_getgroups_cache {
4780: my ($udom,$uname,$cdom,$cnum)=@_;
4781: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 4782:
1.683 raeburn 4783: my $hashid="$udom:$uname:$courseid";
4784: &devalidate_cache_new('getgroups',$hashid);
4785: }
4786:
1.12 www 4787: # ------------------------------------------------------------------ Plain Text
4788:
4789: sub plaintext {
1.742 raeburn 4790: my ($short,$type,$cid) = @_;
1.758 albertel 4791: if ($short =~ /^cr/) {
4792: return (split('/',$short))[-1];
4793: }
1.742 raeburn 4794: if (!defined($cid)) {
4795: $cid = $env{'request.course.id'};
4796: }
4797: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4798: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4799: '.plaintext'});
4800: }
4801: my %rolenames = (
4802: Course => 'std',
4803: Group => 'alt1',
4804: );
4805: if (defined($type) &&
4806: defined($rolenames{$type}) &&
4807: defined($prp{$short}{$rolenames{$type}})) {
4808: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4809: } else {
4810: return &Apache::lonlocal::mt($prp{$short}{'std'});
4811: }
1.12 www 4812: }
4813:
4814: # ----------------------------------------------------------------- Assign Role
4815:
4816: sub assignrole {
1.357 www 4817: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4818: my $mrole;
4819: if ($role =~ /^cr\//) {
1.393 www 4820: my $cwosec=$url;
1.811 albertel 4821: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 4822: unless (&allowed('ccr',$cwosec)) {
1.104 www 4823: &logthis('Refused custom assignrole: '.
4824: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4825: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4826: return 'refused';
4827: }
1.21 www 4828: $mrole='cr';
1.678 raeburn 4829: } elsif ($role =~ /^gr\//) {
4830: my $cwogrp=$url;
1.811 albertel 4831: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 4832: unless (&allowed('mdg',$cwogrp)) {
4833: &logthis('Refused group assignrole: '.
4834: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4835: $env{'user.name'}.' at '.$env{'user.domain'});
4836: return 'refused';
4837: }
4838: $mrole='gr';
1.21 www 4839: } else {
1.82 www 4840: my $cwosec=$url;
1.811 albertel 4841: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 4842: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4843: &logthis('Refused assignrole: '.
4844: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4845: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4846: return 'refused';
4847: }
1.21 www 4848: $mrole=$role;
4849: }
1.620 albertel 4850: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4851: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4852: if ($end) { $command.='_'.$end; }
1.21 www 4853: if ($start) {
4854: if ($end) {
1.81 www 4855: $command.='_'.$start;
1.21 www 4856: } else {
1.81 www 4857: $command.='_0_'.$start;
1.21 www 4858: }
4859: }
1.739 raeburn 4860: my $origstart = $start;
4861: my $origend = $end;
1.357 www 4862: # actually delete
4863: if ($deleteflag) {
1.373 www 4864: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4865: # modify command to delete the role
1.620 albertel 4866: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4867: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4868: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4869: # set start and finish to negative values for userrolelog
4870: $start=-1;
4871: $end=-1;
4872: }
4873: }
4874: # send command
1.349 www 4875: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4876: # log new user role if status is ok
1.349 www 4877: if ($answer eq 'ok') {
1.663 raeburn 4878: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4879: # for course roles, perform group memberships changes triggered by role change.
4880: unless ($role =~ /^gr/) {
4881: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4882: $origstart);
4883: }
1.349 www 4884: }
4885: return $answer;
1.169 harris41 4886: }
4887:
4888: # -------------------------------------------------- Modify user authentication
1.197 www 4889: # Overrides without validation
4890:
1.169 harris41 4891: sub modifyuserauth {
4892: my ($udom,$uname,$umode,$upass)=@_;
4893: my $uhome=&homeserver($uname,$udom);
1.197 www 4894: unless (&allowed('mau',$udom)) { return 'refused'; }
4895: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4896: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4897: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4898: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4899: &escape($upass),$uhome);
1.620 albertel 4900: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4901: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4902: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4903: &log($udom,,$uname,$uhome,
1.620 albertel 4904: 'Authentication changed by '.$env{'user.domain'}.', '.
4905: $env{'user.name'}.', '.$umode.
1.197 www 4906: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4907: unless ($reply eq 'ok') {
1.197 www 4908: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4909: return 'error: '.$reply;
4910: }
1.170 harris41 4911: return 'ok';
1.80 www 4912: }
4913:
1.81 www 4914: # --------------------------------------------------------------- Modify a user
1.80 www 4915:
1.81 www 4916: sub modifyuser {
1.206 matthew 4917: my ($udom, $uname, $uid,
4918: $umode, $upass, $first,
4919: $middle, $last, $gene,
1.387 www 4920: $forceid, $desiredhome, $email)=@_;
1.807 albertel 4921: $udom= &LONCAPA::clean_domain($udom);
4922: $uname=&LONCAPA::clean_username($uname);
1.81 www 4923: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4924: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4925: $last.', '.$gene.'(forceid: '.$forceid.')'.
4926: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4927: ' desiredhome not specified').
1.620 albertel 4928: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4929: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4930: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4931: # ----------------------------------------------------------------- Create User
1.406 albertel 4932: if (($uhome eq 'no_host') &&
4933: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4934: my $unhome='';
1.844 albertel 4935: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 4936: $unhome = $desiredhome;
1.620 albertel 4937: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4938: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4939: } else { # load balancing routine for determining $unhome
1.81 www 4940: my $loadm=10000000;
1.841 albertel 4941: my %servers = &get_servers($udom,'library');
4942: foreach my $tryserver (keys(%servers)) {
4943: my $answer=reply('load',$tryserver);
4944: if (($answer=~/\d+/) && ($answer<$loadm)) {
4945: $loadm=$answer;
4946: $unhome=$tryserver;
4947: }
1.80 www 4948: }
4949: }
4950: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4951: return 'error: unable to find a home server for '.$uname.
4952: ' in domain '.$udom;
1.80 www 4953: }
4954: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4955: &escape($upass),$unhome);
4956: unless ($reply eq 'ok') {
4957: return 'error: '.$reply;
4958: }
1.230 stredwic 4959: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4960: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4961: return 'error: unable verify users home machine.';
1.80 www 4962: }
1.209 matthew 4963: } # End of creation of new user
1.80 www 4964: # ---------------------------------------------------------------------- Add ID
4965: if ($uid) {
4966: $uid=~tr/A-Z/a-z/;
4967: my %uidhash=&idrget($udom,$uname);
1.196 www 4968: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4969: && (!$forceid)) {
1.80 www 4970: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4971: return 'error: user id "'.$uid.'" does not match '.
4972: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4973: }
4974: } else {
4975: &idput($udom,($uname => $uid));
4976: }
4977: }
4978: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4979: my @tmp=&get('environment',
1.134 albertel 4980: ['firstname','middlename','lastname','generation'],
4981: $udom,$uname);
1.313 matthew 4982: my %names;
4983: if ($tmp[0] =~ m/^error:.*/) {
4984: %names=();
4985: } else {
4986: %names = @tmp;
4987: }
1.388 www 4988: #
4989: # Make sure to not trash student environment if instructor does not bother
4990: # to supply name and email information
4991: #
4992: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4993: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4994: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4995: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4996: if ($email) {
4997: $email=~s/[^\w\@\.\-\,]//gs;
4998: if ($email=~/\@/) { $names{'notification'} = $email;
4999: $names{'critnotification'} = $email;
5000: $names{'permanentemail'} = $email; }
5001: }
1.134 albertel 5002: my $reply = &put('environment', \%names, $udom,$uname);
5003: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 5004: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5005: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5006: $umode.', '.$first.', '.$middle.', '.
5007: $last.', '.$gene.' by '.
1.620 albertel 5008: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5009: return 'ok';
1.80 www 5010: }
5011:
1.81 www 5012: # -------------------------------------------------------------- Modify student
1.80 www 5013:
1.81 www 5014: sub modifystudent {
5015: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5016: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5017: if (!$cid) {
1.620 albertel 5018: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5019: return 'not_in_class';
5020: }
1.80 www 5021: }
5022: # --------------------------------------------------------------- Make the user
1.81 www 5023: my $reply=&modifyuser
1.209 matthew 5024: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5025: $desiredhome,$email);
1.80 www 5026: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5027: # This will cause &modify_student_enrollment to get the uid from the
5028: # students environment
5029: $uid = undef if (!$forceid);
1.455 albertel 5030: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5031: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5032: return $reply;
5033: }
5034:
5035: sub modify_student_enrollment {
1.515 raeburn 5036: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5037: my ($cdom,$cnum,$chome);
5038: if (!$cid) {
1.620 albertel 5039: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5040: return 'not_in_class';
5041: }
1.620 albertel 5042: $cdom=$env{'course.'.$cid.'.domain'};
5043: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5044: } else {
5045: ($cdom,$cnum)=split(/_/,$cid);
5046: }
1.620 albertel 5047: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5048: if (!$chome) {
1.457 raeburn 5049: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5050: }
1.455 albertel 5051: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5052: # Make sure the user exists
1.81 www 5053: my $uhome=&homeserver($uname,$udom);
5054: if (($uhome eq '') || ($uhome eq 'no_host')) {
5055: return 'error: no such user';
5056: }
1.297 matthew 5057: # Get student data if we were not given enough information
5058: if (!defined($first) || $first eq '' ||
5059: !defined($last) || $last eq '' ||
5060: !defined($uid) || $uid eq '' ||
5061: !defined($middle) || $middle eq '' ||
5062: !defined($gene) || $gene eq '') {
1.294 matthew 5063: # They did not supply us with enough data to enroll the student, so
5064: # we need to pick up more information.
1.297 matthew 5065: my %tmp = &get('environment',
1.294 matthew 5066: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5067: ,$udom,$uname);
5068:
1.800 albertel 5069: #foreach my $key (keys(%tmp)) {
5070: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5071: #}
1.294 matthew 5072: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5073: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5074: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5075: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5076: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5077: }
1.556 albertel 5078: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5079: my $reply=cput('classlist',
5080: {"$uname:$udom" =>
1.515 raeburn 5081: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5082: $cdom,$cnum);
1.81 www 5083: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5084: return 'error: '.$reply;
1.652 albertel 5085: } else {
5086: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5087: }
1.297 matthew 5088: # Add student role to user
1.83 www 5089: my $uurl='/'.$cid;
1.81 www 5090: $uurl=~s/\_/\//g;
5091: if ($usec) {
5092: $uurl.='/'.$usec;
5093: }
5094: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5095: }
5096:
1.556 albertel 5097: sub format_name {
5098: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5099: my $name;
5100: if ($first ne 'lastname') {
5101: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5102: } else {
5103: if ($lastname=~/\S/) {
5104: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5105: $name=~s/\s+,/,/;
5106: } else {
5107: $name.= $firstname.' '.$middlename.' '.$generation;
5108: }
5109: }
5110: $name=~s/^\s+//;
5111: $name=~s/\s+$//;
5112: $name=~s/\s+/ /g;
5113: return $name;
5114: }
5115:
1.84 www 5116: # ------------------------------------------------- Write to course preferences
5117:
5118: sub writecoursepref {
5119: my ($courseid,%prefs)=@_;
5120: $courseid=~s/^\///;
5121: $courseid=~s/\_/\//g;
5122: my ($cdomain,$cnum)=split(/\//,$courseid);
5123: my $chome=homeserver($cnum,$cdomain);
5124: if (($chome eq '') || ($chome eq 'no_host')) {
5125: return 'error: no such course';
5126: }
5127: my $cstring='';
1.800 albertel 5128: foreach my $pref (keys(%prefs)) {
5129: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5130: }
1.84 www 5131: $cstring=~s/\&$//;
5132: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5133: }
5134:
5135: # ---------------------------------------------------------- Make/modify course
5136:
5137: sub createcourse {
1.741 raeburn 5138: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5139: $course_owner,$crstype)=@_;
1.84 www 5140: $url=&declutter($url);
5141: my $cid='';
1.264 matthew 5142: unless (&allowed('ccc',$udom)) {
1.84 www 5143: return 'refused';
5144: }
5145: # ------------------------------------------------------------------- Create ID
1.674 www 5146: my $uname=int(1+rand(9)).
5147: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5148: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5149: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5150: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5151: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5152: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5153: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5154: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5155: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5156: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5157: return 'error: unable to generate unique course-ID';
5158: }
5159: }
1.264 matthew 5160: # ------------------------------------------------ Check supplied server name
1.620 albertel 5161: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5162: if (! &is_library($course_server)) {
1.264 matthew 5163: return 'error:bad server name '.$course_server;
5164: }
1.84 www 5165: # ------------------------------------------------------------- Make the course
5166: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5167: $course_server);
1.84 www 5168: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5169: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5170: if (($uhome eq '') || ($uhome eq 'no_host')) {
5171: return 'error: no such course';
5172: }
1.271 www 5173: # ----------------------------------------------------------------- Course made
1.516 raeburn 5174: # log existence
5175: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 5176: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5177: &escape($crstype),$uhome);
1.358 www 5178: &flushcourselogs();
5179: # set toplevel url
1.271 www 5180: my $topurl=$url;
5181: unless ($nonstandard) {
5182: # ------------------------------------------ For standard courses, make top url
5183: my $mapurl=&clutter($url);
1.278 www 5184: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5185: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5186: <map>
5187: <resource id="1" type="start"></resource>
5188: <resource id="2" src="$mapurl"></resource>
5189: <resource id="3" type="finish"></resource>
5190: <link index="1" from="1" to="2"></link>
5191: <link index="2" from="2" to="3"></link>
5192: </map>
5193: ENDINITMAP
5194: $topurl=&declutter(
1.638 albertel 5195: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5196: );
5197: }
5198: # ----------------------------------------------------------- Write preferences
1.84 www 5199: &writecoursepref($udom.'_'.$uname,
5200: ('description' => $description,
1.271 www 5201: 'url' => $topurl));
1.84 www 5202: return '/'.$udom.'/'.$uname;
5203: }
5204:
1.813 albertel 5205: sub is_course {
5206: my ($cdom,$cnum) = @_;
5207: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5208: undef,'.');
5209: if (exists($courses{$cdom.'_'.$cnum})) {
5210: return 1;
5211: }
5212: return 0;
5213: }
5214:
1.21 www 5215: # ---------------------------------------------------------- Assign Custom Role
5216:
5217: sub assigncustomrole {
1.357 www 5218: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5219: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5220: $end,$start,$deleteflag);
1.21 www 5221: }
5222:
5223: # ----------------------------------------------------------------- Revoke Role
5224:
5225: sub revokerole {
1.357 www 5226: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5227: my $now=time;
1.357 www 5228: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5229: }
5230:
5231: # ---------------------------------------------------------- Revoke Custom Role
5232:
5233: sub revokecustomrole {
1.357 www 5234: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5235: my $now=time;
1.357 www 5236: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5237: $deleteflag);
1.17 www 5238: }
5239:
1.533 banghart 5240: # ------------------------------------------------------------ Disk usage
1.535 albertel 5241: sub diskusage {
1.533 banghart 5242: my ($udom,$uname,$directoryRoot)=@_;
5243: $directoryRoot =~ s/\/$//;
1.535 albertel 5244: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5245: return $listing;
1.512 banghart 5246: }
5247:
1.566 banghart 5248: sub is_locked {
5249: my ($file_name, $domain, $user) = @_;
5250: my @check;
5251: my $is_locked;
5252: push @check, $file_name;
1.613 albertel 5253: my %locked = &get('file_permissions',\@check,
1.620 albertel 5254: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5255: my ($tmp)=keys(%locked);
5256: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5257:
1.566 banghart 5258: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5259: $is_locked = 'false';
5260: foreach my $entry (@{$locked{$file_name}}) {
5261: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5262: $is_locked = 'true';
5263: last;
1.745 raeburn 5264: }
5265: }
1.566 banghart 5266: } else {
5267: $is_locked = 'false';
5268: }
5269: }
5270:
1.759 albertel 5271: sub declutter_portfile {
5272: my ($file) = @_;
1.833 albertel 5273: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5274: return $file;
5275: }
5276:
1.559 banghart 5277: # ------------------------------------------------------------- Mark as Read Only
5278:
5279: sub mark_as_readonly {
5280: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5281: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5282: my ($tmp)=keys(%current_permissions);
5283: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5284: foreach my $file (@{$files}) {
1.759 albertel 5285: $file = &declutter_portfile($file);
1.561 banghart 5286: push(@{$current_permissions{$file}},$what);
1.559 banghart 5287: }
1.613 albertel 5288: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5289: return;
5290: }
5291:
1.572 banghart 5292: # ------------------------------------------------------------Save Selected Files
5293:
5294: sub save_selected_files {
5295: my ($user, $path, @files) = @_;
5296: my $filename = $user."savedfiles";
1.573 banghart 5297: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 5298: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5299: foreach my $file (@files) {
1.620 albertel 5300: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5301: }
5302: foreach my $file (@other_files) {
1.574 banghart 5303: print (OUT $file."\n");
1.572 banghart 5304: }
1.574 banghart 5305: close (OUT);
1.572 banghart 5306: return 'ok';
5307: }
5308:
1.574 banghart 5309: sub clear_selected_files {
5310: my ($user) = @_;
5311: my $filename = $user."savedfiles";
5312: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5313: print (OUT undef);
5314: close (OUT);
5315: return ("ok");
5316: }
5317:
1.572 banghart 5318: sub files_in_path {
5319: my ($user, $path) = @_;
5320: my $filename = $user."savedfiles";
5321: my %return_files;
1.574 banghart 5322: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5323: while (my $line_in = <IN>) {
1.574 banghart 5324: chomp ($line_in);
5325: my @paths_and_file = split (m!/!, $line_in);
5326: my $file_part = pop (@paths_and_file);
5327: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5328: $path_part.='/';
5329: my $path_and_file = $path_part.$file_part;
5330: if ($path_part eq $path) {
5331: $return_files{$file_part}= 'selected';
5332: }
5333: }
1.574 banghart 5334: close (IN);
5335: return (\%return_files);
1.572 banghart 5336: }
5337:
5338: # called in portfolio select mode, to show files selected NOT in current directory
5339: sub files_not_in_path {
5340: my ($user, $path) = @_;
5341: my $filename = $user."savedfiles";
5342: my @return_files;
5343: my $path_part;
1.800 albertel 5344: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5345: while (my $line = <IN>) {
1.572 banghart 5346: #ok, I know it's clunky, but I want it to work
1.800 albertel 5347: my @paths_and_file = split(m|/|, $line);
5348: my $file_part = pop(@paths_and_file);
5349: chomp($file_part);
5350: my $path_part = join('/', @paths_and_file);
1.572 banghart 5351: $path_part .= '/';
5352: my $path_and_file = $path_part.$file_part;
5353: if ($path_part ne $path) {
1.800 albertel 5354: push(@return_files, ($path_and_file));
1.572 banghart 5355: }
5356: }
1.800 albertel 5357: close(OUT);
1.574 banghart 5358: return (@return_files);
1.572 banghart 5359: }
5360:
1.745 raeburn 5361: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5362:
1.745 raeburn 5363: sub get_portfile_permissions {
5364: my ($domain,$user) = @_;
1.613 albertel 5365: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5366: my ($tmp)=keys(%current_permissions);
5367: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5368: return \%current_permissions;
5369: }
5370:
5371: #---------------------------------------------Get portfolio file access controls
5372:
1.749 raeburn 5373: sub get_access_controls {
1.745 raeburn 5374: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5375: my %access;
5376: my $real_file = $file;
5377: $file =~ s/\.meta$//;
1.745 raeburn 5378: if (defined($file)) {
1.749 raeburn 5379: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5380: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5381: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5382: }
5383: }
1.745 raeburn 5384: } else {
1.749 raeburn 5385: foreach my $key (keys(%{$current_permissions})) {
5386: if ($key =~ /\0accesscontrol$/) {
5387: if (defined($group)) {
5388: if ($key !~ m-^\Q$group\E/-) {
5389: next;
5390: }
5391: }
5392: my ($fullpath) = split(/\0/,$key);
5393: if (ref($$current_permissions{$key}) eq 'HASH') {
5394: foreach my $control (keys(%{$$current_permissions{$key}})) {
5395: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5396: }
5397: }
5398: }
5399: }
5400: }
5401: return %access;
5402: }
5403:
5404: sub modify_access_controls {
5405: my ($file_name,$changes,$domain,$user)=@_;
5406: my ($outcome,$deloutcome);
5407: my %store_permissions;
5408: my %new_values;
5409: my %new_control;
5410: my %translation;
5411: my @deletions = ();
5412: my $now = time;
5413: if (exists($$changes{'activate'})) {
5414: if (ref($$changes{'activate'}) eq 'HASH') {
5415: my @newitems = sort(keys(%{$$changes{'activate'}}));
5416: my $numnew = scalar(@newitems);
5417: for (my $i=0; $i<$numnew; $i++) {
5418: my $newkey = $newitems[$i];
5419: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5420: if ($newkey =~ /^\d+:/) {
5421: $newkey =~ s/^(\d+)/$newid/;
5422: $translation{$1} = $newid;
5423: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5424: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5425: $translation{$1} = $newid;
5426: }
1.749 raeburn 5427: $new_values{$file_name."\0".$newkey} =
5428: $$changes{'activate'}{$newitems[$i]};
5429: $new_control{$newkey} = $now;
5430: }
5431: }
5432: }
5433: my %todelete;
5434: my %changed_items;
5435: foreach my $action ('delete','update') {
5436: if (exists($$changes{$action})) {
5437: if (ref($$changes{$action}) eq 'HASH') {
5438: foreach my $key (keys(%{$$changes{$action}})) {
5439: my ($itemnum) = ($key =~ /^([^:]+):/);
5440: if ($action eq 'delete') {
5441: $todelete{$itemnum} = 1;
5442: } else {
5443: $changed_items{$itemnum} = $key;
5444: }
5445: }
1.745 raeburn 5446: }
5447: }
1.749 raeburn 5448: }
5449: # get lock on access controls for file.
5450: my $lockhash = {
5451: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5452: ':'.$env{'user.domain'},
5453: };
5454: my $tries = 0;
5455: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5456:
5457: while (($gotlock ne 'ok') && $tries <3) {
5458: $tries ++;
5459: sleep 1;
5460: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5461: }
5462: if ($gotlock eq 'ok') {
5463: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5464: my ($tmp)=keys(%curr_permissions);
5465: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5466: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5467: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5468: if (ref($curr_controls) eq 'HASH') {
5469: foreach my $control_item (keys(%{$curr_controls})) {
5470: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5471: if (defined($todelete{$itemnum})) {
5472: push(@deletions,$file_name."\0".$control_item);
5473: } else {
5474: if (defined($changed_items{$itemnum})) {
5475: $new_control{$changed_items{$itemnum}} = $now;
5476: push(@deletions,$file_name."\0".$control_item);
5477: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5478: } else {
5479: $new_control{$control_item} = $$curr_controls{$control_item};
5480: }
5481: }
1.745 raeburn 5482: }
5483: }
5484: }
1.749 raeburn 5485: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5486: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5487: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5488: # remove lock
5489: my @del_lock = ($file_name."\0".'locked_access_records');
5490: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5491: my ($file,$group);
5492: if (&is_course($domain,$user)) {
5493: ($group,$file) = split(/\//,$file_name,2);
5494: } else {
5495: $file = $file_name;
5496: }
5497: my $sqlresult =
5498: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5499: $group);
1.749 raeburn 5500: } else {
5501: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5502: }
1.749 raeburn 5503: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5504: }
5505:
1.827 raeburn 5506: sub make_public_indefinitely {
5507: my ($requrl) = @_;
5508: my $now = time;
5509: my $action = 'activate';
5510: my $aclnum = 0;
5511: if (&is_portfolio_url($requrl)) {
5512: my (undef,$udom,$unum,$file_name,$group) =
5513: &parse_portfolio_url($requrl);
5514: my $current_perms = &get_portfile_permissions($udom,$unum);
5515: my %access_controls = &get_access_controls($current_perms,
5516: $group,$file_name);
5517: foreach my $key (keys(%{$access_controls{$file_name}})) {
5518: my ($num,$scope,$end,$start) =
5519: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5520: if ($scope eq 'public') {
5521: if ($start <= $now && $end == 0) {
5522: $action = 'none';
5523: } else {
5524: $action = 'update';
5525: $aclnum = $num;
5526: }
5527: last;
5528: }
5529: }
5530: if ($action eq 'none') {
5531: return 'ok';
5532: } else {
5533: my %changes;
5534: my $newend = 0;
5535: my $newstart = $now;
5536: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5537: $changes{$action}{$newkey} = {
5538: type => 'public',
5539: time => {
5540: start => $newstart,
5541: end => $newend,
5542: },
5543: };
5544: my ($outcome,$deloutcome,$new_values,$translation) =
5545: &modify_access_controls($file_name,\%changes,$udom,$unum);
5546: return $outcome;
5547: }
5548: } else {
5549: return 'invalid';
5550: }
5551: }
5552:
1.745 raeburn 5553: #------------------------------------------------------Get Marked as Read Only
5554:
5555: sub get_marked_as_readonly {
5556: my ($domain,$user,$what,$group) = @_;
5557: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5558: my @readonly_files;
1.629 banghart 5559: my $cmp1=$what;
5560: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5561: while (my ($file_name,$value) = each(%{$current_permissions})) {
5562: if (defined($group)) {
5563: if ($file_name !~ m-^\Q$group\E/-) {
5564: next;
5565: }
5566: }
1.561 banghart 5567: if (ref($value) eq "ARRAY"){
5568: foreach my $stored_what (@{$value}) {
1.629 banghart 5569: my $cmp2=$stored_what;
1.759 albertel 5570: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5571: $cmp2=join('',@{$stored_what});
1.745 raeburn 5572: }
1.629 banghart 5573: if ($cmp1 eq $cmp2) {
1.561 banghart 5574: push(@readonly_files, $file_name);
1.745 raeburn 5575: last;
1.563 banghart 5576: } elsif (!defined($what)) {
5577: push(@readonly_files, $file_name);
1.745 raeburn 5578: last;
1.561 banghart 5579: }
5580: }
1.745 raeburn 5581: }
1.561 banghart 5582: }
5583: return @readonly_files;
5584: }
1.577 banghart 5585: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5586:
1.577 banghart 5587: sub get_marked_as_readonly_hash {
1.745 raeburn 5588: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5589: my %readonly_files;
1.745 raeburn 5590: while (my ($file_name,$value) = each(%{$current_permissions})) {
5591: if (defined($group)) {
5592: if ($file_name !~ m-^\Q$group\E/-) {
5593: next;
5594: }
5595: }
1.577 banghart 5596: if (ref($value) eq "ARRAY"){
5597: foreach my $stored_what (@{$value}) {
1.745 raeburn 5598: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5599: foreach my $lock_descriptor(@{$stored_what}) {
5600: if ($lock_descriptor eq 'graded') {
5601: $readonly_files{$file_name} = 'graded';
5602: } elsif ($lock_descriptor eq 'handback') {
5603: $readonly_files{$file_name} = 'handback';
5604: } else {
5605: if (!exists($readonly_files{$file_name})) {
5606: $readonly_files{$file_name} = 'locked';
5607: }
5608: }
1.745 raeburn 5609: }
1.750 banghart 5610: }
1.577 banghart 5611: }
5612: }
5613: }
5614: return %readonly_files;
5615: }
1.559 banghart 5616: # ------------------------------------------------------------ Unmark as Read Only
5617:
5618: sub unmark_as_readonly {
1.629 banghart 5619: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5620: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5621: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5622: $file_name = &declutter_portfile($file_name);
1.634 albertel 5623: my $symb_crs = $what;
5624: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5625: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5626: my ($tmp)=keys(%current_permissions);
5627: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5628: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5629: foreach my $file (@readonly_files) {
1.759 albertel 5630: my $clean_file = &declutter_portfile($file);
5631: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5632: my $current_locks = $current_permissions{$file};
1.563 banghart 5633: my @new_locks;
5634: my @del_keys;
5635: if (ref($current_locks) eq "ARRAY"){
5636: foreach my $locker (@{$current_locks}) {
1.632 albertel 5637: my $compare=$locker;
1.749 raeburn 5638: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5639: $compare=join('',@{$locker});
1.746 raeburn 5640: if ($compare ne $symb_crs) {
5641: push(@new_locks, $locker);
5642: }
1.563 banghart 5643: }
5644: }
1.650 albertel 5645: if (scalar(@new_locks) > 0) {
1.563 banghart 5646: $current_permissions{$file} = \@new_locks;
5647: } else {
5648: push(@del_keys, $file);
1.613 albertel 5649: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5650: delete($current_permissions{$file});
1.563 banghart 5651: }
5652: }
1.561 banghart 5653: }
1.613 albertel 5654: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5655: return;
5656: }
1.512 banghart 5657:
1.17 www 5658: # ------------------------------------------------------------ Directory lister
5659:
5660: sub dirlist {
1.253 stredwic 5661: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5662:
1.18 www 5663: $uri=~s/^\///;
5664: $uri=~s/\/$//;
1.253 stredwic 5665: my ($udom, $uname);
5666: (undef,$udom,$uname)=split(/\//,$uri);
5667: if(defined($userdomain)) {
5668: $udom = $userdomain;
5669: }
5670: if(defined($username)) {
5671: $uname = $username;
5672: }
5673:
5674: my $dirRoot = $perlvar{'lonDocRoot'};
5675: if(defined($alternateDirectoryRoot)) {
5676: $dirRoot = $alternateDirectoryRoot;
5677: $dirRoot =~ s/\/$//;
1.751 banghart 5678: }
1.253 stredwic 5679:
5680: if($udom) {
5681: if($uname) {
1.800 albertel 5682: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5683: &homeserver($uname,$udom));
1.605 matthew 5684: my @listing_results;
5685: if ($listing eq 'unknown_cmd') {
1.800 albertel 5686: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5687: &homeserver($uname,$udom));
1.605 matthew 5688: @listing_results = split(/:/,$listing);
5689: } else {
5690: @listing_results = map { &unescape($_); } split(/:/,$listing);
5691: }
5692: return @listing_results;
1.253 stredwic 5693: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5694: my %allusers;
1.841 albertel 5695: my %servers = &get_servers($udom,'library');
5696: foreach my $tryserver (keys(%servers)) {
5697: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5698: $udom, $tryserver);
5699: my @listing_results;
5700: if ($listing eq 'unknown_cmd') {
5701: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5702: $udom, $tryserver);
5703: @listing_results = split(/:/,$listing);
5704: } else {
5705: @listing_results =
5706: map { &unescape($_); } split(/:/,$listing);
5707: }
5708: if ($listing_results[0] ne 'no_such_dir' &&
5709: $listing_results[0] ne 'empty' &&
5710: $listing_results[0] ne 'con_lost') {
5711: foreach my $line (@listing_results) {
5712: my ($entry) = split(/&/,$line,2);
5713: $allusers{$entry} = 1;
5714: }
5715: }
1.253 stredwic 5716: }
5717: my $alluserstr='';
1.800 albertel 5718: foreach my $user (sort(keys(%allusers))) {
5719: $alluserstr.=$user.'&user:';
1.253 stredwic 5720: }
5721: $alluserstr=~s/:$//;
5722: return split(/:/,$alluserstr);
5723: } else {
1.800 albertel 5724: return ('missing user name');
1.253 stredwic 5725: }
5726: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 5727: my @all_domains = sort(&all_domains());
5728: foreach my $domain (@all_domains) {
5729: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5730: }
5731: return @all_domains;
5732: } else {
1.800 albertel 5733: return ('missing domain');
1.275 stredwic 5734: }
5735: }
5736:
5737: # --------------------------------------------- GetFileTimestamp
5738: # This function utilizes dirlist and returns the date stamp for
5739: # when it was last modified. It will also return an error of -1
5740: # if an error occurs
5741:
1.410 matthew 5742: ##
5743: ## FIXME: This subroutine assumes its caller knows something about the
5744: ## directory structure of the home server for the student ($root).
5745: ## Not a good assumption to make. Since this is for looking up files
5746: ## in user directories, the full path should be constructed by lond, not
5747: ## whatever machine we request data from.
5748: ##
1.275 stredwic 5749: sub GetFileTimestamp {
5750: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 5751: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5752: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 5753: my $subdir=$studentName.'__';
5754: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5755: my $proname="$studentDomain/$subdir/$studentName";
5756: $proname .= '/'.$filename;
1.375 matthew 5757: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5758: $studentName, $root);
1.275 stredwic 5759: my @stats = split('&', $fileStat);
5760: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5761: # @stats contains first the filename, then the stat output
5762: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5763: } else {
5764: return -1;
1.253 stredwic 5765: }
1.26 www 5766: }
5767:
1.712 albertel 5768: sub stat_file {
5769: my ($uri) = @_;
1.787 albertel 5770: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5771:
1.712 albertel 5772: my ($udom,$uname,$file,$dir);
5773: if ($uri =~ m-^/(uploaded|editupload)/-) {
5774: ($udom,$uname,$file) =
1.811 albertel 5775: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 5776: $file = 'userfiles/'.$file;
1.740 www 5777: $dir = &propath($udom,$uname);
1.712 albertel 5778: }
5779: if ($uri =~ m-^/res/-) {
5780: ($udom,$uname) =
1.807 albertel 5781: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 5782: $file = $uri;
5783: }
5784:
5785: if (!$udom || !$uname || !$file) {
5786: # unable to handle the uri
5787: return ();
5788: }
5789:
5790: my ($result) = &dirlist($file,$udom,$uname,$dir);
5791: my @stats = split('&', $result);
1.721 banghart 5792:
1.712 albertel 5793: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5794: shift(@stats); #filename is first
5795: return @stats;
5796: }
5797: return ();
5798: }
5799:
1.26 www 5800: # -------------------------------------------------------- Value of a Condition
5801:
1.713 albertel 5802: # gets the value of a specific preevaluated condition
5803: # stored in the string $env{user.state.<cid>}
5804: # or looks up a condition reference in the bighash and if if hasn't
5805: # already been evaluated recurses into docondval to get the value of
5806: # the condition, then memoizing it to
5807: # $env{user.state.<cid>.<condition>}
1.40 www 5808: sub directcondval {
5809: my $number=shift;
1.620 albertel 5810: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5811: &Apache::lonuserstate::evalstate();
5812: }
1.713 albertel 5813: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5814: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5815: } elsif ($number =~ /^_/) {
5816: my $sub_condition;
5817: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5818: &GDBM_READER(),0640)) {
5819: $sub_condition=$bighash{'conditions'.$number};
5820: untie(%bighash);
5821: }
5822: my $value = &docondval($sub_condition);
5823: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5824: return $value;
5825: }
1.620 albertel 5826: if ($env{'user.state.'.$env{'request.course.id'}}) {
5827: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5828: } else {
5829: return 2;
5830: }
5831: }
5832:
1.713 albertel 5833: # get the collection of conditions for this resource
1.26 www 5834: sub condval {
5835: my $condidx=shift;
1.54 www 5836: my $allpathcond='';
1.713 albertel 5837: foreach my $cond (split(/\|/,$condidx)) {
5838: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5839: $allpathcond.=
5840: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5841: }
1.191 harris41 5842: }
1.54 www 5843: $allpathcond=~s/\|$//;
1.713 albertel 5844: return &docondval($allpathcond);
5845: }
5846:
5847: #evaluates an expression of conditions
5848: sub docondval {
5849: my ($allpathcond) = @_;
5850: my $result=0;
5851: if ($env{'request.course.id'}
5852: && defined($allpathcond)) {
5853: my $operand='|';
5854: my @stack;
5855: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5856: if ($chunk eq '(') {
5857: push @stack,($operand,$result);
5858: } elsif ($chunk eq ')') {
5859: my $before=pop @stack;
5860: if (pop @stack eq '&') {
5861: $result=$result>$before?$before:$result;
5862: } else {
5863: $result=$result>$before?$result:$before;
5864: }
5865: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5866: $operand=$chunk;
5867: } else {
5868: my $new=directcondval($chunk);
5869: if ($operand eq '&') {
5870: $result=$result>$new?$new:$result;
5871: } else {
5872: $result=$result>$new?$result:$new;
5873: }
5874: }
5875: }
1.26 www 5876: }
5877: return $result;
1.421 albertel 5878: }
5879:
5880: # ---------------------------------------------------- Devalidate courseresdata
5881:
5882: sub devalidatecourseresdata {
5883: my ($coursenum,$coursedomain)=@_;
5884: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5885: &devalidate_cache_new('courseres',$hashid);
1.28 www 5886: }
5887:
1.763 www 5888:
1.200 www 5889: # --------------------------------------------------- Course Resourcedata Query
5890:
1.624 albertel 5891: sub get_courseresdata {
5892: my ($coursenum,$coursedomain)=@_;
1.200 www 5893: my $coursehom=&homeserver($coursenum,$coursedomain);
5894: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5895: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5896: my %dumpreply;
1.417 albertel 5897: unless (defined($cached)) {
1.624 albertel 5898: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5899: $result=\%dumpreply;
1.251 albertel 5900: my ($tmp) = keys(%dumpreply);
5901: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5902: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5903: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5904: return $tmp;
1.416 albertel 5905: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5906: $result=undef;
1.599 albertel 5907: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5908: }
5909: }
1.624 albertel 5910: return $result;
5911: }
5912:
1.633 albertel 5913: sub devalidateuserresdata {
5914: my ($uname,$udom)=@_;
5915: my $hashid="$udom:$uname";
5916: &devalidate_cache_new('userres',$hashid);
5917: }
5918:
1.624 albertel 5919: sub get_userresdata {
5920: my ($uname,$udom)=@_;
5921: #most student don\'t have any data set, check if there is some data
5922: if (&EXT_cache_status($udom,$uname)) { return undef; }
5923:
5924: my $hashid="$udom:$uname";
5925: my ($result,$cached)=&is_cached_new('userres',$hashid);
5926: if (!defined($cached)) {
5927: my %resourcedata=&dump('resourcedata',$udom,$uname);
5928: $result=\%resourcedata;
5929: &do_cache_new('userres',$hashid,$result,600);
5930: }
5931: my ($tmp)=keys(%$result);
5932: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5933: return $result;
5934: }
5935: #error 2 occurs when the .db doesn't exist
5936: if ($tmp!~/error: 2 /) {
1.672 albertel 5937: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5938: " Trying to get resource data for ".
5939: $uname." at ".$udom.": ".
5940: $tmp."</font>");
5941: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5942: #&EXT_cache_set($udom,$uname);
5943: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5944: undef($tmp); # not really an error so don't send it back
1.624 albertel 5945: }
5946: return $tmp;
5947: }
5948:
5949: sub resdata {
5950: my ($name,$domain,$type,@which)=@_;
5951: my $result;
5952: if ($type eq 'course') {
5953: $result=&get_courseresdata($name,$domain);
5954: } elsif ($type eq 'user') {
5955: $result=&get_userresdata($name,$domain);
5956: }
5957: if (!ref($result)) { return $result; }
1.251 albertel 5958: foreach my $item (@which) {
1.417 albertel 5959: if (defined($result->{$item})) {
5960: return $result->{$item};
1.251 albertel 5961: }
1.250 albertel 5962: }
1.291 albertel 5963: return undef;
1.200 www 5964: }
5965:
1.379 matthew 5966: #
5967: # EXT resource caching routines
5968: #
5969:
5970: sub clear_EXT_cache_status {
1.383 albertel 5971: &delenv('cache.EXT.');
1.379 matthew 5972: }
5973:
5974: sub EXT_cache_status {
5975: my ($target_domain,$target_user) = @_;
1.383 albertel 5976: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5977: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5978: # We know already the user has no data
5979: return 1;
5980: } else {
5981: return 0;
5982: }
5983: }
5984:
5985: sub EXT_cache_set {
5986: my ($target_domain,$target_user) = @_;
1.383 albertel 5987: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5988: #&appenv($cachename => time);
1.379 matthew 5989: }
5990:
1.28 www 5991: # --------------------------------------------------------- Value of a Variable
1.58 www 5992: sub EXT {
1.715 albertel 5993:
1.395 albertel 5994: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5995: unless ($varname) { return ''; }
1.218 albertel 5996: #get real user name/domain, courseid and symb
5997: my $courseid;
1.359 albertel 5998: my $publicuser;
1.427 www 5999: if ($symbparm) {
6000: $symbparm=&get_symb_from_alias($symbparm);
6001: }
1.218 albertel 6002: if (!($uname && $udom)) {
1.790 albertel 6003: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6004: if (!$symbparm) { $symbparm=$cursymb; }
6005: } else {
1.620 albertel 6006: $courseid=$env{'request.course.id'};
1.218 albertel 6007: }
1.48 www 6008: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6009: my $rest;
1.320 albertel 6010: if (defined($therest[0])) {
1.48 www 6011: $rest=join('.',@therest);
6012: } else {
6013: $rest='';
6014: }
1.320 albertel 6015:
1.57 www 6016: my $qualifierrest=$qualifier;
6017: if ($rest) { $qualifierrest.='.'.$rest; }
6018: my $spacequalifierrest=$space;
6019: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6020: if ($realm eq 'user') {
1.48 www 6021: # --------------------------------------------------------------- user.resource
6022: if ($space eq 'resource') {
1.651 albertel 6023: if ( (defined($Apache::lonhomework::parsing_a_problem)
6024: || defined($Apache::lonhomework::parsing_a_task))
6025: &&
1.744 albertel 6026: ($symbparm eq &symbread()) ) {
6027: # if we are in the middle of processing the resource the
6028: # get the value we are planning on committing
6029: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6030: return $Apache::lonhomework::results{$qualifierrest};
6031: } else {
6032: return $Apache::lonhomework::history{$qualifierrest};
6033: }
1.335 albertel 6034: } else {
1.359 albertel 6035: my %restored;
1.620 albertel 6036: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6037: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6038: } else {
6039: %restored=&restore($symbparm,$courseid,$udom,$uname);
6040: }
1.335 albertel 6041: return $restored{$qualifierrest};
6042: }
1.48 www 6043: # ----------------------------------------------------------------- user.access
6044: } elsif ($space eq 'access') {
1.218 albertel 6045: # FIXME - not supporting calls for a specific user
1.48 www 6046: return &allowed($qualifier,$rest);
6047: # ------------------------------------------ user.preferences, user.environment
6048: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6049: if (($uname eq $env{'user.name'}) &&
6050: ($udom eq $env{'user.domain'})) {
6051: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6052: } else {
1.359 albertel 6053: my %returnhash;
6054: if (!$publicuser) {
6055: %returnhash=&userenvironment($udom,$uname,
6056: $qualifierrest);
6057: }
1.218 albertel 6058: return $returnhash{$qualifierrest};
6059: }
1.48 www 6060: # ----------------------------------------------------------------- user.course
6061: } elsif ($space eq 'course') {
1.218 albertel 6062: # FIXME - not supporting calls for a specific user
1.620 albertel 6063: return $env{join('.',('request.course',$qualifier))};
1.48 www 6064: # ------------------------------------------------------------------- user.role
6065: } elsif ($space eq 'role') {
1.218 albertel 6066: # FIXME - not supporting calls for a specific user
1.620 albertel 6067: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6068: if ($qualifier eq 'value') {
6069: return $role;
6070: } elsif ($qualifier eq 'extent') {
6071: return $where;
6072: }
6073: # ----------------------------------------------------------------- user.domain
6074: } elsif ($space eq 'domain') {
1.218 albertel 6075: return $udom;
1.48 www 6076: # ------------------------------------------------------------------- user.name
6077: } elsif ($space eq 'name') {
1.218 albertel 6078: return $uname;
1.48 www 6079: # ---------------------------------------------------- Any other user namespace
1.29 www 6080: } else {
1.359 albertel 6081: my %reply;
6082: if (!$publicuser) {
6083: %reply=&get($space,[$qualifierrest],$udom,$uname);
6084: }
6085: return $reply{$qualifierrest};
1.48 www 6086: }
1.236 www 6087: } elsif ($realm eq 'query') {
6088: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6089: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6090: [$spacequalifierrest]);
1.620 albertel 6091: return $env{'form.'.$spacequalifierrest};
1.236 www 6092: } elsif ($realm eq 'request') {
1.48 www 6093: # ------------------------------------------------------------- request.browser
6094: if ($space eq 'browser') {
1.430 www 6095: if ($qualifier eq 'textremote') {
1.676 albertel 6096: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6097: return 1;
6098: } else {
6099: return 0;
6100: }
6101: } else {
1.620 albertel 6102: return $env{'browser.'.$qualifier};
1.430 www 6103: }
1.57 www 6104: # ------------------------------------------------------------ request.filename
6105: } else {
1.620 albertel 6106: return $env{'request.'.$spacequalifierrest};
1.29 www 6107: }
1.28 www 6108: } elsif ($realm eq 'course') {
1.48 www 6109: # ---------------------------------------------------------- course.description
1.620 albertel 6110: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6111: } elsif ($realm eq 'resource') {
1.165 www 6112:
1.620 albertel 6113: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6114: if (!$symbparm) { $symbparm=&symbread(); }
6115: }
1.693 albertel 6116:
6117: if ($space eq 'title') {
6118: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6119: return &gettitle($symbparm);
6120: }
6121:
6122: if ($space eq 'map') {
6123: my ($map) = &decode_symb($symbparm);
6124: return &symbread($map);
6125: }
6126:
6127: my ($section, $group, @groups);
1.593 albertel 6128: my ($courselevelm,$courselevel);
1.539 albertel 6129: if ($symbparm && defined($courseid) &&
1.620 albertel 6130: $courseid eq $env{'request.course.id'}) {
1.165 www 6131:
1.218 albertel 6132: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6133:
1.60 www 6134: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6135: my $symbp=$symbparm;
1.735 albertel 6136: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6137:
6138: my $symbparm=$symbp.'.'.$spacequalifierrest;
6139: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6140:
1.620 albertel 6141: if (($env{'user.name'} eq $uname) &&
6142: ($env{'user.domain'} eq $udom)) {
6143: $section=$env{'request.course.sec'};
1.733 raeburn 6144: @groups = split(/:/,$env{'request.course.groups'});
6145: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6146: } else {
1.539 albertel 6147: if (! defined($usection)) {
1.551 albertel 6148: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6149: } else {
6150: $section = $usection;
6151: }
1.733 raeburn 6152: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6153: }
6154:
6155: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6156: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6157: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6158:
1.593 albertel 6159: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6160: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6161: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6162:
1.60 www 6163: # ----------------------------------------------------------- first, check user
1.624 albertel 6164:
6165: my $userreply=&resdata($uname,$udom,'user',
6166: ($courselevelr,$courselevelm,
6167: $courselevel));
6168: if (defined($userreply)) { return $userreply; }
1.95 www 6169:
1.594 albertel 6170: # ------------------------------------------------ second, check some of course
1.684 raeburn 6171: my $coursereply;
1.691 raeburn 6172: if (@groups > 0) {
6173: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6174: $mapparm,$spacequalifierrest);
1.684 raeburn 6175: if (defined($coursereply)) { return $coursereply; }
6176: }
1.96 www 6177:
1.684 raeburn 6178: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6179: $env{'course.'.$courseid.'.domain'},
6180: 'course',
6181: ($seclevelr,$seclevelm,$seclevel,
6182: $courselevelr));
1.287 albertel 6183: if (defined($coursereply)) { return $coursereply; }
1.200 www 6184:
1.60 www 6185: # ------------------------------------------------------ third, check map parms
1.218 albertel 6186: my %parmhash=();
6187: my $thisparm='';
6188: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6189: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6190: &GDBM_READER(),0640)) {
1.218 albertel 6191: $thisparm=$parmhash{$symbparm};
6192: untie(%parmhash);
6193: }
6194: if ($thisparm) { return $thisparm; }
6195: }
1.594 albertel 6196: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6197:
1.218 albertel 6198: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6199: my $filename;
6200: if (!$symbparm) { $symbparm=&symbread(); }
6201: if ($symbparm) {
1.409 www 6202: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6203: } else {
1.620 albertel 6204: $filename=$env{'request.filename'};
1.282 albertel 6205: }
6206: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6207: if (defined($metadata)) { return $metadata; }
1.282 albertel 6208: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6209: if (defined($metadata)) { return $metadata; }
1.142 www 6210:
1.594 albertel 6211: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6212: if ($symbparm && defined($courseid) &&
1.620 albertel 6213: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6214: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6215: $env{'course.'.$courseid.'.domain'},
6216: 'course',
6217: ($courselevelm,$courselevel));
1.593 albertel 6218: if (defined($coursereply)) { return $coursereply; }
6219: }
1.145 www 6220: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6221: unless ($space eq '0') {
1.336 albertel 6222: my @parts=split(/_/,$space);
6223: my $id=pop(@parts);
6224: my $part=join('_',@parts);
6225: if ($part eq '') { $part='0'; }
6226: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6227: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6228: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6229: }
1.395 albertel 6230: if ($recurse) { return undef; }
6231: my $pack_def=&packages_tab_default($filename,$varname);
6232: if (defined($pack_def)) { return $pack_def; }
1.71 www 6233:
1.48 www 6234: # ---------------------------------------------------- Any other user namespace
6235: } elsif ($realm eq 'environment') {
6236: # ----------------------------------------------------------------- environment
1.620 albertel 6237: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6238: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6239: } else {
1.770 albertel 6240: if ($uname eq 'anonymous' && $udom eq '') {
6241: return '';
6242: }
1.219 albertel 6243: my %returnhash=&userenvironment($udom,$uname,
6244: $spacequalifierrest);
6245: return $returnhash{$spacequalifierrest};
6246: }
1.28 www 6247: } elsif ($realm eq 'system') {
1.48 www 6248: # ----------------------------------------------------------------- system.time
6249: if ($space eq 'time') {
6250: return time;
6251: }
1.696 albertel 6252: } elsif ($realm eq 'server') {
6253: # ----------------------------------------------------------------- system.time
6254: if ($space eq 'name') {
6255: return $ENV{'SERVER_NAME'};
6256: }
1.28 www 6257: }
1.48 www 6258: return '';
1.61 www 6259: }
6260:
1.691 raeburn 6261: sub check_group_parms {
6262: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6263: my @groupitems = ();
6264: my $resultitem;
6265: my @levels = ($symbparm,$mapparm,$what);
6266: foreach my $group (@{$groups}) {
6267: foreach my $level (@levels) {
6268: my $item = $courseid.'.['.$group.'].'.$level;
6269: push(@groupitems,$item);
6270: }
6271: }
6272: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6273: $env{'course.'.$courseid.'.domain'},
6274: 'course',@groupitems);
6275: return $coursereply;
6276: }
6277:
6278: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6279: my ($courseid,@groups) = @_;
6280: @groups = sort(@groups);
1.691 raeburn 6281: return @groups;
6282: }
6283:
1.395 albertel 6284: sub packages_tab_default {
6285: my ($uri,$varname)=@_;
6286: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6287:
6288: my (@extension,@specifics,$do_default);
6289: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6290: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6291: if ($pack_type eq 'default') {
6292: $do_default=1;
6293: } elsif ($pack_type eq 'extension') {
6294: push(@extension,[$package,$pack_type,$pack_part]);
1.848 albertel 6295: } elsif ($pack_part eq $part) {
6296: # only look at packages defaults for packages that this id is
1.738 albertel 6297: push(@specifics,[$package,$pack_type,$pack_part]);
6298: }
6299: }
6300: # first look for a package that matches the requested part id
6301: foreach my $package (@specifics) {
6302: my (undef,$pack_type,$pack_part)=@{$package};
6303: next if ($pack_part ne $part);
6304: if (defined($packagetab{"$pack_type&$name&default"})) {
6305: return $packagetab{"$pack_type&$name&default"};
6306: }
6307: }
6308: # look for any possible matching non extension_ package
6309: foreach my $package (@specifics) {
6310: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6311: if (defined($packagetab{"$pack_type&$name&default"})) {
6312: return $packagetab{"$pack_type&$name&default"};
6313: }
1.585 albertel 6314: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6315: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6316: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6317: }
6318: }
1.738 albertel 6319: # look for any posible extension_ match
6320: foreach my $package (@extension) {
6321: my ($package,$pack_type)=@{$package};
6322: if (defined($packagetab{"$pack_type&$name&default"})) {
6323: return $packagetab{"$pack_type&$name&default"};
6324: }
6325: if (defined($packagetab{$package."&$name&default"})) {
6326: return $packagetab{$package."&$name&default"};
6327: }
6328: }
6329: # look for a global default setting
6330: if ($do_default && defined($packagetab{"default&$name&default"})) {
6331: return $packagetab{"default&$name&default"};
6332: }
1.395 albertel 6333: return undef;
6334: }
6335:
1.334 albertel 6336: sub add_prefix_and_part {
6337: my ($prefix,$part)=@_;
6338: my $keyroot;
6339: if (defined($prefix) && $prefix !~ /^__/) {
6340: # prefix that has a part already
6341: $keyroot=$prefix;
6342: } elsif (defined($prefix)) {
6343: # prefix that is missing a part
6344: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6345: } else {
6346: # no prefix at all
6347: if (defined($part)) { $keyroot='_'.$part; }
6348: }
6349: return $keyroot;
6350: }
6351:
1.71 www 6352: # ---------------------------------------------------------------- Get metadata
6353:
1.599 albertel 6354: my %metaentry;
1.71 www 6355: sub metadata {
1.176 www 6356: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6357: $uri=&declutter($uri);
1.288 albertel 6358: # if it is a non metadata possible uri return quickly
1.529 albertel 6359: if (($uri eq '') ||
6360: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6361: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6362: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6363: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6364: return undef;
1.288 albertel 6365: }
1.73 www 6366: my $filename=$uri;
6367: $uri=~s/\.meta$//;
1.172 www 6368: #
6369: # Is the metadata already cached?
1.177 www 6370: # Look at timestamp of caching
1.172 www 6371: # Everything is cached by the main uri, libraries are never directly cached
6372: #
1.428 albertel 6373: if (!defined($liburi)) {
1.599 albertel 6374: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6375: if (defined($cached)) { return $result->{':'.$what}; }
6376: }
6377: {
1.172 www 6378: #
6379: # Is this a recursive call for a library?
6380: #
1.599 albertel 6381: # if (! exists($metacache{$uri})) {
6382: # $metacache{$uri}={};
6383: # }
1.171 www 6384: if ($liburi) {
6385: $liburi=&declutter($liburi);
6386: $filename=$liburi;
1.401 bowersj2 6387: } else {
1.599 albertel 6388: &devalidate_cache_new('meta',$uri);
6389: undef(%metaentry);
1.401 bowersj2 6390: }
1.140 www 6391: my %metathesekeys=();
1.73 www 6392: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6393: my $metastring;
1.768 albertel 6394: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6395: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6396: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6397: $metastring=&getfile($file);
1.489 albertel 6398: }
1.208 albertel 6399: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6400: my $token;
1.140 www 6401: undef %metathesekeys;
1.71 www 6402: while ($token=$parser->get_token) {
1.339 albertel 6403: if ($token->[0] eq 'S') {
6404: if (defined($token->[2]->{'package'})) {
1.172 www 6405: #
6406: # This is a package - get package info
6407: #
1.339 albertel 6408: my $package=$token->[2]->{'package'};
6409: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6410: if (defined($token->[2]->{'id'})) {
6411: $keyroot.='_'.$token->[2]->{'id'};
6412: }
1.599 albertel 6413: if ($metaentry{':packages'}) {
6414: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6415: } else {
1.599 albertel 6416: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6417: }
1.736 albertel 6418: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6419: my $part=$keyroot;
6420: $part=~s/^\_//;
1.736 albertel 6421: if ($pack_entry=~/^\Q$package\E\&/ ||
6422: $pack_entry=~/^\Q$package\E_0\&/) {
6423: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6424: # ignore package.tab specified default values
6425: # here &package_tab_default() will fetch those
6426: if ($subp eq 'default') { next; }
1.736 albertel 6427: my $value=$packagetab{$pack_entry};
1.432 albertel 6428: my $unikey;
6429: if ($pack =~ /_0$/) {
6430: $unikey='parameter_0_'.$name;
6431: $part=0;
6432: } else {
6433: $unikey='parameter'.$keyroot.'_'.$name;
6434: }
1.339 albertel 6435: if ($subp eq 'display') {
6436: $value.=' [Part: '.$part.']';
6437: }
1.599 albertel 6438: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6439: $metathesekeys{$unikey}=1;
1.599 albertel 6440: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6441: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6442: }
1.599 albertel 6443: if (defined($metaentry{':'.$unikey.'.default'})) {
6444: $metaentry{':'.$unikey}=
6445: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6446: }
1.339 albertel 6447: }
6448: }
6449: } else {
1.172 www 6450: #
6451: # This is not a package - some other kind of start tag
1.339 albertel 6452: #
6453: my $entry=$token->[1];
6454: my $unikey;
6455: if ($entry eq 'import') {
6456: $unikey='';
6457: } else {
6458: $unikey=$entry;
6459: }
6460: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6461:
6462: if (defined($token->[2]->{'id'})) {
6463: $unikey.='_'.$token->[2]->{'id'};
6464: }
1.175 www 6465:
1.339 albertel 6466: if ($entry eq 'import') {
1.175 www 6467: #
6468: # Importing a library here
1.339 albertel 6469: #
6470: if ($depthcount<20) {
6471: my $location=$parser->get_text('/import');
6472: my $dir=$filename;
6473: $dir=~s|[^/]*$||;
6474: $location=&filelocation($dir,$location);
1.736 albertel 6475: my $metadata =
6476: &metadata($uri,'keys', $location,$unikey,
6477: $depthcount+1);
6478: foreach my $meta (split(',',$metadata)) {
6479: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6480: $metathesekeys{$meta}=1;
1.339 albertel 6481: }
6482: }
6483: } else {
6484:
6485: if (defined($token->[2]->{'name'})) {
6486: $unikey.='_'.$token->[2]->{'name'};
6487: }
6488: $metathesekeys{$unikey}=1;
1.736 albertel 6489: foreach my $param (@{$token->[3]}) {
6490: $metaentry{':'.$unikey.'.'.$param} =
6491: $token->[2]->{$param};
1.339 albertel 6492: }
6493: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6494: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6495: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6496: # only ws inside the tag, and not in default, so use default
6497: # as value
1.599 albertel 6498: $metaentry{':'.$unikey}=$default;
1.339 albertel 6499: } else {
1.321 albertel 6500: # either something interesting inside the tag or default
6501: # uninteresting
1.599 albertel 6502: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6503: }
1.172 www 6504: # end of not-a-package not-a-library import
1.339 albertel 6505: }
1.172 www 6506: # end of not-a-package start tag
1.339 albertel 6507: }
1.172 www 6508: # the next is the end of "start tag"
1.339 albertel 6509: }
6510: }
1.483 albertel 6511: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6512: foreach my $key (keys(%packagetab)) {
1.483 albertel 6513: #no specific packages #how's our extension
6514: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6515: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6516: \%metathesekeys);
6517: }
1.599 albertel 6518: if (!exists($metaentry{':packages'})) {
1.737 albertel 6519: foreach my $key (keys(%packagetab)) {
1.483 albertel 6520: #no specific packages well let's get default then
6521: if ($key!~/^default&/) { next; }
1.488 albertel 6522: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6523: \%metathesekeys);
6524: }
6525: }
1.338 www 6526: # are there custom rights to evaluate
1.599 albertel 6527: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6528:
1.338 www 6529: #
6530: # Importing a rights file here
1.339 albertel 6531: #
6532: unless ($depthcount) {
1.599 albertel 6533: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6534: my $dir=$filename;
6535: $dir=~s|[^/]*$||;
6536: $location=&filelocation($dir,$location);
1.736 albertel 6537: my $rights_metadata =
6538: &metadata($uri,'keys',$location,'_rights',
6539: $depthcount+1);
6540: foreach my $rights (split(',',$rights_metadata)) {
6541: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6542: $metathesekeys{$rights}=1;
1.339 albertel 6543: }
6544: }
6545: }
1.737 albertel 6546: # uniqifiy package listing
6547: my %seen;
6548: my @uniq_packages =
6549: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6550: $metaentry{':packages'} = join(',',@uniq_packages);
6551:
6552: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6553: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6554: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6555: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6556: # this is the end of "was not already recently cached
1.71 www 6557: }
1.599 albertel 6558: return $metaentry{':'.$what};
1.261 albertel 6559: }
6560:
1.488 albertel 6561: sub metadata_create_package_def {
1.483 albertel 6562: my ($uri,$key,$package,$metathesekeys)=@_;
6563: my ($pack,$name,$subp)=split(/\&/,$key);
6564: if ($subp eq 'default') { next; }
6565:
1.599 albertel 6566: if (defined($metaentry{':packages'})) {
6567: $metaentry{':packages'}.=','.$package;
1.483 albertel 6568: } else {
1.599 albertel 6569: $metaentry{':packages'}=$package;
1.483 albertel 6570: }
6571: my $value=$packagetab{$key};
6572: my $unikey;
6573: $unikey='parameter_0_'.$name;
1.599 albertel 6574: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6575: $$metathesekeys{$unikey}=1;
1.599 albertel 6576: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6577: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6578: }
1.599 albertel 6579: if (defined($metaentry{':'.$unikey.'.default'})) {
6580: $metaentry{':'.$unikey}=
6581: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6582: }
6583: }
6584:
1.261 albertel 6585: sub metadata_generate_part0 {
6586: my ($metadata,$metacache,$uri) = @_;
6587: my %allnames;
1.737 albertel 6588: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6589: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6590: my $part=$$metacache{':'.$metakey.'.part'};
6591: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6592: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6593: $allnames{$name}=$part;
6594: }
6595: }
6596: }
6597: foreach my $name (keys(%allnames)) {
6598: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6599: my $key=":parameter_0_$name";
1.261 albertel 6600: $$metacache{"$key.part"}='0';
6601: $$metacache{"$key.name"}=$name;
1.428 albertel 6602: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6603: $allnames{$name}.'_'.$name.
6604: '.type'};
1.428 albertel 6605: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6606: '.display'};
1.644 www 6607: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6608: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6609: $$metacache{"$key.display"}=$olddis;
6610: }
1.71 www 6611: }
6612:
1.764 albertel 6613: # ------------------------------------------------------ Devalidate title cache
6614:
6615: sub devalidate_title_cache {
6616: my ($url)=@_;
6617: if (!$env{'request.course.id'}) { return; }
6618: my $symb=&symbread($url);
6619: if (!$symb) { return; }
6620: my $key=$env{'request.course.id'}."\0".$symb;
6621: &devalidate_cache_new('title',$key);
6622: }
6623:
1.301 www 6624: # ------------------------------------------------- Get the title of a resource
6625:
6626: sub gettitle {
6627: my $urlsymb=shift;
6628: my $symb=&symbread($urlsymb);
1.534 albertel 6629: if ($symb) {
1.620 albertel 6630: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6631: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6632: if (defined($cached)) {
6633: return $result;
6634: }
1.534 albertel 6635: my ($map,$resid,$url)=&decode_symb($symb);
6636: my $title='';
6637: my %bighash;
1.620 albertel 6638: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6639: &GDBM_READER(),0640)) {
6640: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6641: $title=$bighash{'title_'.$mapid.'.'.$resid};
6642: untie %bighash;
6643: }
6644: $title=~s/\&colon\;/\:/gs;
6645: if ($title) {
1.599 albertel 6646: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6647: }
6648: $urlsymb=$url;
6649: }
6650: my $title=&metadata($urlsymb,'title');
6651: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6652: return $title;
1.301 www 6653: }
1.613 albertel 6654:
1.614 albertel 6655: sub get_slot {
6656: my ($which,$cnum,$cdom)=@_;
6657: if (!$cnum || !$cdom) {
1.790 albertel 6658: (undef,my $courseid)=&whichuser();
1.620 albertel 6659: $cdom=$env{'course.'.$courseid.'.domain'};
6660: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6661: }
1.703 albertel 6662: my $key=join("\0",'slots',$cdom,$cnum,$which);
6663: my %slotinfo;
6664: if (exists($remembered{$key})) {
6665: $slotinfo{$which} = $remembered{$key};
6666: } else {
6667: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6668: &Apache::lonhomework::showhash(%slotinfo);
6669: my ($tmp)=keys(%slotinfo);
6670: if ($tmp=~/^error:/) { return (); }
6671: $remembered{$key} = $slotinfo{$which};
6672: }
1.616 albertel 6673: if (ref($slotinfo{$which}) eq 'HASH') {
6674: return %{$slotinfo{$which}};
6675: }
6676: return $slotinfo{$which};
1.614 albertel 6677: }
1.31 www 6678: # ------------------------------------------------- Update symbolic store links
6679:
6680: sub symblist {
6681: my ($mapname,%newhash)=@_;
1.438 www 6682: $mapname=&deversion(&declutter($mapname));
1.31 www 6683: my %hash;
1.620 albertel 6684: if (($env{'request.course.fn'}) && (%newhash)) {
6685: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6686: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6687: foreach my $url (keys %newhash) {
6688: next if ($url eq 'last_known'
6689: && $env{'form.no_update_last_known'});
6690: $hash{declutter($url)}=&encode_symb($mapname,
6691: $newhash{$url}->[1],
6692: $newhash{$url}->[0]);
1.191 harris41 6693: }
1.31 www 6694: if (untie(%hash)) {
6695: return 'ok';
6696: }
6697: }
6698: }
6699: return 'error';
1.212 www 6700: }
6701:
6702: # --------------------------------------------------------------- Verify a symb
6703:
6704: sub symbverify {
1.510 www 6705: my ($symb,$thisurl)=@_;
6706: my $thisfn=$thisurl;
1.439 www 6707: $thisfn=&declutter($thisfn);
1.215 www 6708: # direct jump to resource in page or to a sequence - will construct own symbs
6709: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6710: # check URL part
1.409 www 6711: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6712:
1.431 www 6713: unless ($url eq $thisfn) { return 0; }
1.213 www 6714:
1.216 www 6715: $symb=&symbclean($symb);
1.510 www 6716: $thisurl=&deversion($thisurl);
1.439 www 6717: $thisfn=&deversion($thisfn);
1.213 www 6718:
6719: my %bighash;
6720: my $okay=0;
1.431 www 6721:
1.620 albertel 6722: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6723: &GDBM_READER(),0640)) {
1.510 www 6724: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6725: unless ($ids) {
1.510 www 6726: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6727: }
6728: if ($ids) {
6729: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6730: foreach my $id (split(/\,/,$ids)) {
6731: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6732: if (
6733: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6734: eq $symb) {
1.620 albertel 6735: if (($env{'request.role.adv'}) ||
1.800 albertel 6736: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6737: $okay=1;
6738: }
6739: }
1.216 www 6740: }
6741: }
1.213 www 6742: untie(%bighash);
6743: }
6744: return $okay;
1.31 www 6745: }
6746:
1.210 www 6747: # --------------------------------------------------------------- Clean-up symb
6748:
6749: sub symbclean {
6750: my $symb=shift;
1.568 albertel 6751: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6752: # remove version from map
6753: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6754:
1.210 www 6755: # remove version from URL
6756: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6757:
1.507 www 6758: # remove wrapper
6759:
1.510 www 6760: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6761: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6762: return $symb;
1.409 www 6763: }
6764:
6765: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6766:
6767: sub encode_symb {
6768: my ($map,$resid,$url)=@_;
6769: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6770: }
1.409 www 6771:
6772: sub decode_symb {
1.568 albertel 6773: my $symb=shift;
6774: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6775: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6776: return (&fixversion($map),$resid,&fixversion($url));
6777: }
6778:
6779: sub fixversion {
6780: my $fn=shift;
1.609 banghart 6781: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6782: my %bighash;
6783: my $uri=&clutter($fn);
1.620 albertel 6784: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6785: # is this cached?
1.599 albertel 6786: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6787: if (defined($cached)) { return $result; }
6788: # unfortunately not cached, or expired
1.620 albertel 6789: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6790: &GDBM_READER(),0640)) {
6791: if ($bighash{'version_'.$uri}) {
6792: my $version=$bighash{'version_'.$uri};
1.444 www 6793: unless (($version eq 'mostrecent') ||
6794: ($version==&getversion($uri))) {
1.440 www 6795: $uri=~s/\.(\w+)$/\.$version\.$1/;
6796: }
6797: }
6798: untie %bighash;
1.413 www 6799: }
1.599 albertel 6800: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6801: }
6802:
6803: sub deversion {
6804: my $url=shift;
6805: $url=~s/\.\d+\.(\w+)$/\.$1/;
6806: return $url;
1.210 www 6807: }
6808:
1.31 www 6809: # ------------------------------------------------------ Return symb list entry
6810:
6811: sub symbread {
1.249 www 6812: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6813: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6814: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6815: # no filename provided? try from environment
1.44 www 6816: unless ($thisfn) {
1.620 albertel 6817: if ($env{'request.symb'}) {
6818: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6819: }
1.620 albertel 6820: $thisfn=$env{'request.filename'};
1.44 www 6821: }
1.569 albertel 6822: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6823: # is that filename actually a symb? Verify, clean, and return
6824: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6825: if (&symbverify($thisfn,$1)) {
1.620 albertel 6826: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6827: }
1.242 www 6828: }
1.44 www 6829: $thisfn=declutter($thisfn);
1.31 www 6830: my %hash;
1.37 www 6831: my %bighash;
6832: my $syval='';
1.620 albertel 6833: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6834: my $targetfn = $thisfn;
1.609 banghart 6835: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6836: $targetfn = 'adm/wrapper/'.$thisfn;
6837: }
1.687 albertel 6838: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6839: $targetfn=$1;
6840: }
1.620 albertel 6841: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6842: &GDBM_READER(),0640)) {
1.481 raeburn 6843: $syval=$hash{$targetfn};
1.37 www 6844: untie(%hash);
6845: }
6846: # ---------------------------------------------------------- There was an entry
6847: if ($syval) {
1.601 albertel 6848: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6849: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6850: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6851: #return $env{$cache_str}='';
1.601 albertel 6852: #}
6853: #$syval.=$1;
6854: #}
1.37 www 6855: } else {
6856: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6857: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6858: &GDBM_READER(),0640)) {
1.37 www 6859: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6860: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6861: unless ($ids) {
6862: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6863: }
6864: unless ($ids) {
6865: # alias?
6866: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6867: }
1.37 www 6868: if ($ids) {
6869: # ------------------------------------------------------------------- Has ID(s)
6870: my @possibilities=split(/\,/,$ids);
1.39 www 6871: if ($#possibilities==0) {
6872: # ----------------------------------------------- There is only one possibility
1.37 www 6873: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6874: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6875: $resid,$thisfn);
1.249 www 6876: } elsif (!$donotrecurse) {
1.39 www 6877: # ------------------------------------------ There is more than one possibility
6878: my $realpossible=0;
1.800 albertel 6879: foreach my $id (@possibilities) {
6880: my $file=$bighash{'src_'.$id};
1.39 www 6881: if (&allowed('bre',$file)) {
1.800 albertel 6882: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6883: if ($bighash{'map_type_'.$mapid} ne 'page') {
6884: $realpossible++;
1.626 albertel 6885: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6886: $resid,$thisfn);
1.39 www 6887: }
6888: }
1.191 harris41 6889: }
1.39 www 6890: if ($realpossible!=1) { $syval=''; }
1.249 www 6891: } else {
6892: $syval='';
1.37 www 6893: }
6894: }
6895: untie(%bighash)
1.481 raeburn 6896: }
1.31 www 6897: }
1.62 www 6898: if ($syval) {
1.620 albertel 6899: return $env{$cache_str}=$syval;
1.62 www 6900: }
1.31 www 6901: }
1.44 www 6902: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6903: return $env{$cache_str}='';
1.31 www 6904: }
6905:
6906: # ---------------------------------------------------------- Return random seed
6907:
1.32 www 6908: sub numval {
6909: my $txt=shift;
6910: $txt=~tr/A-J/0-9/;
6911: $txt=~tr/a-j/0-9/;
6912: $txt=~tr/K-T/0-9/;
6913: $txt=~tr/k-t/0-9/;
6914: $txt=~tr/U-Z/0-5/;
6915: $txt=~tr/u-z/0-5/;
6916: $txt=~s/\D//g;
1.564 albertel 6917: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6918: return int($txt);
1.368 albertel 6919: }
6920:
1.484 albertel 6921: sub numval2 {
6922: my $txt=shift;
6923: $txt=~tr/A-J/0-9/;
6924: $txt=~tr/a-j/0-9/;
6925: $txt=~tr/K-T/0-9/;
6926: $txt=~tr/k-t/0-9/;
6927: $txt=~tr/U-Z/0-5/;
6928: $txt=~tr/u-z/0-5/;
6929: $txt=~s/\D//g;
6930: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6931: my $total;
6932: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6933: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6934: return int($total);
6935: }
6936:
1.575 albertel 6937: sub numval3 {
6938: use integer;
6939: my $txt=shift;
6940: $txt=~tr/A-J/0-9/;
6941: $txt=~tr/a-j/0-9/;
6942: $txt=~tr/K-T/0-9/;
6943: $txt=~tr/k-t/0-9/;
6944: $txt=~tr/U-Z/0-5/;
6945: $txt=~tr/u-z/0-5/;
6946: $txt=~s/\D//g;
6947: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6948: my $total;
6949: foreach my $val (@txts) { $total+=$val; }
6950: if ($_64bit) { $total=(($total<<32)>>32); }
6951: return $total;
6952: }
6953:
1.675 albertel 6954: sub digest {
6955: my ($data)=@_;
6956: my $digest=&Digest::MD5::md5($data);
6957: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6958: my ($e,$f);
6959: {
6960: use integer;
6961: $e=($a+$b);
6962: $f=($c+$d);
6963: if ($_64bit) {
6964: $e=(($e<<32)>>32);
6965: $f=(($f<<32)>>32);
6966: }
6967: }
6968: if (wantarray) {
6969: return ($e,$f);
6970: } else {
6971: my $g;
6972: {
6973: use integer;
6974: $g=($e+$f);
6975: if ($_64bit) {
6976: $g=(($g<<32)>>32);
6977: }
6978: }
6979: return $g;
6980: }
6981: }
6982:
1.368 albertel 6983: sub latest_rnd_algorithm_id {
1.675 albertel 6984: return '64bit5';
1.366 albertel 6985: }
1.32 www 6986:
1.503 albertel 6987: sub get_rand_alg {
6988: my ($courseid)=@_;
1.790 albertel 6989: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 6990: if ($courseid) {
1.620 albertel 6991: return $env{"course.$courseid.rndseed"};
1.503 albertel 6992: }
6993: return &latest_rnd_algorithm_id();
6994: }
6995:
1.562 albertel 6996: sub validCODE {
6997: my ($CODE)=@_;
6998: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6999: return 0;
7000: }
7001:
1.491 albertel 7002: sub getCODE {
1.620 albertel 7003: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7004: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7005: defined($Apache::lonhomework::parsing_a_task) ) &&
7006: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7007: return $Apache::lonhomework::history{'resource.CODE'};
7008: }
7009: return undef;
7010: }
7011:
1.31 www 7012: sub rndseed {
1.155 albertel 7013: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7014: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 7015: if (!$symb) {
1.366 albertel 7016: unless ($symb=$wsymb) { return time; }
7017: }
7018: if (!$courseid) { $courseid=$wcourseid; }
7019: if (!$domain) { $domain=$wdomain; }
7020: if (!$username) { $username=$wusername }
1.503 albertel 7021: my $which=&get_rand_alg();
1.803 albertel 7022:
1.491 albertel 7023: if (defined(&getCODE())) {
1.675 albertel 7024: if ($which eq '64bit5') {
7025: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7026: } elsif ($which eq '64bit4') {
1.575 albertel 7027: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7028: } else {
7029: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7030: }
1.675 albertel 7031: } elsif ($which eq '64bit5') {
7032: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7033: } elsif ($which eq '64bit4') {
7034: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7035: } elsif ($which eq '64bit3') {
7036: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7037: } elsif ($which eq '64bit2') {
7038: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7039: } elsif ($which eq '64bit') {
7040: return &rndseed_64bit($symb,$courseid,$domain,$username);
7041: }
7042: return &rndseed_32bit($symb,$courseid,$domain,$username);
7043: }
7044:
7045: sub rndseed_32bit {
7046: my ($symb,$courseid,$domain,$username)=@_;
7047: {
7048: use integer;
7049: my $symbchck=unpack("%32C*",$symb) << 27;
7050: my $symbseed=numval($symb) << 22;
7051: my $namechck=unpack("%32C*",$username) << 17;
7052: my $nameseed=numval($username) << 12;
7053: my $domainseed=unpack("%32C*",$domain) << 7;
7054: my $courseseed=unpack("%32C*",$courseid);
7055: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7056: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7057: #&logthis("rndseed :$num:$symb");
1.564 albertel 7058: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7059: return $num;
7060: }
7061: }
7062:
7063: sub rndseed_64bit {
7064: my ($symb,$courseid,$domain,$username)=@_;
7065: {
7066: use integer;
7067: my $symbchck=unpack("%32S*",$symb) << 21;
7068: my $symbseed=numval($symb) << 10;
7069: my $namechck=unpack("%32S*",$username);
7070:
7071: my $nameseed=numval($username) << 21;
7072: my $domainseed=unpack("%32S*",$domain) << 10;
7073: my $courseseed=unpack("%32S*",$courseid);
7074:
7075: my $num1=$symbchck+$symbseed+$namechck;
7076: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7077: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7078: #&logthis("rndseed :$num:$symb");
1.564 albertel 7079: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7080: return "$num1,$num2";
1.155 albertel 7081: }
1.366 albertel 7082: }
7083:
1.443 albertel 7084: sub rndseed_64bit2 {
7085: my ($symb,$courseid,$domain,$username)=@_;
7086: {
7087: use integer;
7088: # strings need to be an even # of cahracters long, it it is odd the
7089: # last characters gets thrown away
7090: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7091: my $symbseed=numval($symb) << 10;
7092: my $namechck=unpack("%32S*",$username.' ');
7093:
7094: my $nameseed=numval($username) << 21;
1.501 albertel 7095: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7096: my $courseseed=unpack("%32S*",$courseid.' ');
7097:
7098: my $num1=$symbchck+$symbseed+$namechck;
7099: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7100: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7101: #&logthis("rndseed :$num:$symb");
1.803 albertel 7102: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7103: return "$num1,$num2";
7104: }
7105: }
7106:
7107: sub rndseed_64bit3 {
7108: my ($symb,$courseid,$domain,$username)=@_;
7109: {
7110: use integer;
7111: # strings need to be an even # of cahracters long, it it is odd the
7112: # last characters gets thrown away
7113: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7114: my $symbseed=numval2($symb) << 10;
7115: my $namechck=unpack("%32S*",$username.' ');
7116:
7117: my $nameseed=numval2($username) << 21;
1.443 albertel 7118: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7119: my $courseseed=unpack("%32S*",$courseid.' ');
7120:
7121: my $num1=$symbchck+$symbseed+$namechck;
7122: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7124: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7126:
1.503 albertel 7127: return "$num1:$num2";
1.443 albertel 7128: }
7129: }
7130:
1.575 albertel 7131: sub rndseed_64bit4 {
7132: my ($symb,$courseid,$domain,$username)=@_;
7133: {
7134: use integer;
7135: # strings need to be an even # of cahracters long, it it is odd the
7136: # last characters gets thrown away
7137: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7138: my $symbseed=numval3($symb) << 10;
7139: my $namechck=unpack("%32S*",$username.' ');
7140:
7141: my $nameseed=numval3($username) << 21;
7142: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7143: my $courseseed=unpack("%32S*",$courseid.' ');
7144:
7145: my $num1=$symbchck+$symbseed+$namechck;
7146: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7147: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7148: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7149: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7150:
7151: return "$num1:$num2";
7152: }
7153: }
7154:
1.675 albertel 7155: sub rndseed_64bit5 {
7156: my ($symb,$courseid,$domain,$username)=@_;
7157: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7158: return "$num1:$num2";
7159: }
7160:
1.366 albertel 7161: sub rndseed_CODE_64bit {
7162: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7163: {
1.366 albertel 7164: use integer;
1.443 albertel 7165: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7166: my $symbseed=numval2($symb);
1.491 albertel 7167: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7168: my $CODEseed=numval(&getCODE());
1.443 albertel 7169: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7170: my $num1=$symbseed+$CODEchck;
7171: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7172: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7173: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7174: if ($_64bit) { $num1=(($num1<<32)>>32); }
7175: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7176: return "$num1:$num2";
1.366 albertel 7177: }
7178: }
7179:
1.575 albertel 7180: sub rndseed_CODE_64bit4 {
7181: my ($symb,$courseid,$domain,$username)=@_;
7182: {
7183: use integer;
7184: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7185: my $symbseed=numval3($symb);
7186: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7187: my $CODEseed=numval3(&getCODE());
7188: my $courseseed=unpack("%32S*",$courseid.' ');
7189: my $num1=$symbseed+$CODEchck;
7190: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7191: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7192: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7193: if ($_64bit) { $num1=(($num1<<32)>>32); }
7194: if ($_64bit) { $num2=(($num2<<32)>>32); }
7195: return "$num1:$num2";
7196: }
7197: }
7198:
1.675 albertel 7199: sub rndseed_CODE_64bit5 {
7200: my ($symb,$courseid,$domain,$username)=@_;
7201: my $code = &getCODE();
7202: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7203: return "$num1:$num2";
7204: }
7205:
1.366 albertel 7206: sub setup_random_from_rndseed {
7207: my ($rndseed)=@_;
1.503 albertel 7208: if ($rndseed =~/([,:])/) {
7209: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7210: &Math::Random::random_set_seed(abs($num1),abs($num2));
7211: } else {
7212: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7213: }
1.36 albertel 7214: }
7215:
1.474 albertel 7216: sub latest_receipt_algorithm_id {
1.835 albertel 7217: return 'receipt3';
1.474 albertel 7218: }
7219:
1.480 www 7220: sub recunique {
7221: my $fucourseid=shift;
7222: my $unique;
1.835 albertel 7223: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7224: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7225: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7226: } else {
7227: $unique=$perlvar{'lonReceipt'};
7228: }
7229: return unpack("%32C*",$unique);
7230: }
7231:
7232: sub recprefix {
7233: my $fucourseid=shift;
7234: my $prefix;
1.835 albertel 7235: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7236: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7237: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7238: } else {
7239: $prefix=$perlvar{'lonHostID'};
7240: }
7241: return unpack("%32C*",$prefix);
7242: }
7243:
1.76 www 7244: sub ireceipt {
1.474 albertel 7245: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7246:
7247: my $return =&recprefix($fucourseid).'-';
7248:
7249: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7250: $env{'request.state'} eq 'construct') {
7251: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7252: return $return;
7253: }
7254:
1.76 www 7255: my $cuname=unpack("%32C*",$funame);
7256: my $cudom=unpack("%32C*",$fudom);
7257: my $cucourseid=unpack("%32C*",$fucourseid);
7258: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7259: my $cunique=&recunique($fucourseid);
1.474 albertel 7260: my $cpart=unpack("%32S*",$part);
1.835 albertel 7261: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7262:
1.790 albertel 7263: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7264:
7265: $return.= ($cunique%$cuname+
7266: $cunique%$cudom+
7267: $cusymb%$cuname+
7268: $cusymb%$cudom+
7269: $cucourseid%$cuname+
7270: $cucourseid%$cudom+
7271: $cpart%$cuname+
7272: $cpart%$cudom);
7273: } else {
7274: $return.= ($cunique%$cuname+
7275: $cunique%$cudom+
7276: $cusymb%$cuname+
7277: $cusymb%$cudom+
7278: $cucourseid%$cuname+
7279: $cucourseid%$cudom);
7280: }
7281: return $return;
1.76 www 7282: }
7283:
7284: sub receipt {
1.474 albertel 7285: my ($part)=@_;
1.790 albertel 7286: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7287: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7288: }
1.260 ng 7289:
1.790 albertel 7290: sub whichuser {
7291: my ($passedsymb)=@_;
7292: my ($symb,$courseid,$domain,$name,$publicuser);
7293: if (defined($env{'form.grade_symb'})) {
7294: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7295: my $allowed=&allowed('vgr',$tmp_courseid);
7296: if (!$allowed &&
7297: exists($env{'request.course.sec'}) &&
7298: $env{'request.course.sec'} !~ /^\s*$/) {
7299: $allowed=&allowed('vgr',$tmp_courseid.
7300: '/'.$env{'request.course.sec'});
7301: }
7302: if ($allowed) {
7303: ($symb)=&get_env_multiple('form.grade_symb');
7304: $courseid=$tmp_courseid;
7305: ($domain)=&get_env_multiple('form.grade_domain');
7306: ($name)=&get_env_multiple('form.grade_username');
7307: return ($symb,$courseid,$domain,$name,$publicuser);
7308: }
7309: }
7310: if (!$passedsymb) {
7311: $symb=&symbread();
7312: } else {
7313: $symb=$passedsymb;
7314: }
7315: $courseid=$env{'request.course.id'};
7316: $domain=$env{'user.domain'};
7317: $name=$env{'user.name'};
7318: if ($name eq 'public' && $domain eq 'public') {
7319: if (!defined($env{'form.username'})) {
7320: $env{'form.username'}.=time.rand(10000000);
7321: }
7322: $name.=$env{'form.username'};
7323: }
7324: return ($symb,$courseid,$domain,$name,$publicuser);
7325:
7326: }
7327:
1.36 albertel 7328: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7329: # returns either the contents of the file or
7330: # -1 if the file doesn't exist
1.481 raeburn 7331: #
7332: # if the target is a file that was uploaded via DOCS,
7333: # a check will be made to see if a current copy exists on the local server,
7334: # if it does this will be served, otherwise a copy will be retrieved from
7335: # the home server for the course and stored in /home/httpd/html/userfiles on
7336: # the local server.
1.472 albertel 7337:
1.36 albertel 7338: sub getfile {
1.538 albertel 7339: my ($file) = @_;
1.609 banghart 7340: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7341: &repcopy($file);
7342: return &readfile($file);
7343: }
7344:
7345: sub repcopy_userfile {
7346: my ($file)=@_;
1.609 banghart 7347: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7348: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7349: my ($cdom,$cnum,$filename) =
1.811 albertel 7350: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7351: my $uri="/uploaded/$cdom/$cnum/$filename";
7352: if (-e "$file") {
1.828 www 7353: # we already have a local copy, check it out
1.538 albertel 7354: my @fileinfo = stat($file);
1.828 www 7355: my $rtncode;
7356: my $info;
1.538 albertel 7357: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7358: if ($lwpresp ne 'ok') {
1.828 www 7359: # there is no such file anymore, even though we had a local copy
1.482 albertel 7360: if ($rtncode eq '404') {
1.538 albertel 7361: unlink($file);
1.482 albertel 7362: }
7363: return -1;
7364: }
7365: if ($info < $fileinfo[9]) {
1.828 www 7366: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7367: return 'ok';
1.828 www 7368: } else {
7369: # the file is outdated, get rid of it
7370: unlink($file);
1.482 albertel 7371: }
1.828 www 7372: }
7373: # one way or the other, at this point, we don't have the file
7374: # construct the correct path for the file
7375: my @parts = ($cdom,$cnum);
7376: if ($filename =~ m|^(.+)/[^/]+$|) {
7377: push @parts, split(/\//,$1);
7378: }
7379: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7380: foreach my $part (@parts) {
7381: $path .= '/'.$part;
7382: if (!-e $path) {
7383: mkdir($path,0770);
1.482 albertel 7384: }
7385: }
1.828 www 7386: # now the path exists for sure
7387: # get a user agent
7388: my $ua=new LWP::UserAgent;
7389: my $transferfile=$file.'.in.transfer';
7390: # FIXME: this should flock
7391: if (-e $transferfile) { return 'ok'; }
7392: my $request;
7393: $uri=~s/^\///;
1.838 albertel 7394: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7395: my $response=$ua->request($request,$transferfile);
7396: # did it work?
7397: if ($response->is_error()) {
7398: unlink($transferfile);
7399: &logthis("Userfile repcopy failed for $uri");
7400: return -1;
7401: }
7402: # worked, rename the transfer file
7403: rename($transferfile,$file);
1.607 raeburn 7404: return 'ok';
1.481 raeburn 7405: }
7406:
1.517 albertel 7407: sub tokenwrapper {
7408: my $uri=shift;
1.552 albertel 7409: $uri=~s|^http\://([^/]+)||;
7410: $uri=~s|^/||;
1.620 albertel 7411: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7412: my $token=$1;
1.552 albertel 7413: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7414: if ($udom && $uname && $file) {
7415: $file=~s|(\?\.*)*$||;
1.620 albertel 7416: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7417: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7418: (($uri=~/\?/)?'&':'?').'token='.$token.
7419: '&tokenissued='.$perlvar{'lonHostID'};
7420: } else {
7421: return '/adm/notfound.html';
7422: }
7423: }
7424:
1.828 www 7425: # call with reqtype HEAD: get last modification time
7426: # call with reqtype GET: get the file contents
7427: # Do not call this with reqtype GET for large files! It loads everything into memory
7428: #
1.481 raeburn 7429: sub getuploaded {
7430: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7431: $uri=~s/^\///;
1.838 albertel 7432: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7433: my $ua=new LWP::UserAgent;
7434: my $request=new HTTP::Request($reqtype,$uri);
7435: my $response=$ua->request($request);
7436: $$rtncode = $response->code;
1.482 albertel 7437: if (! $response->is_success()) {
7438: return 'failed';
7439: }
7440: if ($reqtype eq 'HEAD') {
1.486 www 7441: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7442: } elsif ($reqtype eq 'GET') {
7443: $$info = $response->content;
1.472 albertel 7444: }
1.482 albertel 7445: return 'ok';
1.36 albertel 7446: }
7447:
1.481 raeburn 7448: sub readfile {
7449: my $file = shift;
7450: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7451: my $fh;
7452: open($fh,"<$file");
7453: my $a='';
1.800 albertel 7454: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7455: return $a;
7456: }
7457:
1.36 albertel 7458: sub filelocation {
1.590 banghart 7459: my ($dir,$file) = @_;
7460: my $location;
7461: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7462:
7463: if ($file =~ m-^/adm/-) {
7464: $file=~s-^/adm/wrapper/-/-;
7465: $file=~s-^/adm/coursedocs/showdoc/-/-;
7466: }
1.590 banghart 7467: if ($file=~m:^/~:) { # is a contruction space reference
7468: $location = $file;
7469: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7470: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7471: # is a correct contruction space reference
7472: $location = $file;
1.609 banghart 7473: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7474: my ($udom,$uname,$filename)=
1.811 albertel 7475: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7476: my $home=&homeserver($uname,$udom);
7477: my $is_me=0;
7478: my @ids=¤t_machine_ids();
7479: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7480: if ($is_me) {
1.740 www 7481: $location=&propath($udom,$uname).
1.590 banghart 7482: '/userfiles/'.$filename;
7483: } else {
7484: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7485: $udom.'/'.$uname.'/'.$filename;
7486: }
7487: } else {
7488: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7489: $file=~s:^/res/:/:;
7490: if ( !( $file =~ m:^/:) ) {
7491: $location = $dir. '/'.$file;
7492: } else {
7493: $location = '/home/httpd/html/res'.$file;
7494: }
1.59 albertel 7495: }
1.590 banghart 7496: $location=~s://+:/:g; # remove duplicate /
7497: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7498: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7499: return $location;
1.46 www 7500: }
1.36 albertel 7501:
1.46 www 7502: sub hreflocation {
7503: my ($dir,$file)=@_;
1.460 albertel 7504: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7505: $file=filelocation($dir,$file);
1.700 albertel 7506: } elsif ($file=~m-^/adm/-) {
7507: $file=~s-^/adm/wrapper/-/-;
7508: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7509: }
7510: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7511: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7512: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7513: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7514: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7515: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7516: -/uploaded/$1/$2/-x;
1.46 www 7517: }
1.462 albertel 7518: return $file;
1.465 albertel 7519: }
7520:
7521: sub current_machine_domains {
1.853 albertel 7522: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7523: }
7524:
7525: sub machine_domains {
7526: my ($hostname) = @_;
1.465 albertel 7527: my @domains;
1.838 albertel 7528: my %hostname = &all_hostnames();
1.465 albertel 7529: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7530: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7531: if ($hostname eq $name) {
1.844 albertel 7532: push(@domains,&host_domain($id));
1.465 albertel 7533: }
7534: }
7535: return @domains;
7536: }
7537:
7538: sub current_machine_ids {
1.853 albertel 7539: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7540: }
7541:
7542: sub machine_ids {
7543: my ($hostname) = @_;
7544: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7545: my @ids;
1.838 albertel 7546: my %hostname = &all_hostnames();
1.465 albertel 7547: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7548: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7549: if ($hostname eq $name) {
7550: push(@ids,$id);
7551: }
7552: }
7553: return @ids;
1.31 www 7554: }
7555:
1.824 raeburn 7556: sub additional_machine_domains {
7557: my @domains;
7558: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7559: while( my $line = <$fh>) {
7560: $line =~ s/\s//g;
7561: push(@domains,$line);
7562: }
7563: return @domains;
7564: }
7565:
7566: sub default_login_domain {
7567: my $domain = $perlvar{'lonDefDomain'};
7568: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7569: foreach my $posdom (¤t_machine_domains(),
7570: &additional_machine_domains()) {
7571: if (lc($posdom) eq lc($testdomain)) {
7572: $domain=$posdom;
7573: last;
7574: }
7575: }
7576: return $domain;
7577: }
7578:
1.31 www 7579: # ------------------------------------------------------------- Declutters URLs
7580:
7581: sub declutter {
7582: my $thisfn=shift;
1.569 albertel 7583: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7584: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7585: $thisfn=~s/^\///;
1.697 albertel 7586: $thisfn=~s|^adm/wrapper/||;
7587: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7588: $thisfn=~s/^res\///;
1.235 www 7589: $thisfn=~s/\?.+$//;
1.268 www 7590: return $thisfn;
7591: }
7592:
7593: # ------------------------------------------------------------- Clutter up URLs
7594:
7595: sub clutter {
7596: my $thisfn='/'.&declutter(shift);
1.609 banghart 7597: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7598: $thisfn='/res'.$thisfn;
7599: }
1.694 albertel 7600: if ($thisfn !~m|/adm|) {
1.695 albertel 7601: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7602: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7603: } else {
7604: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7605: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7606: if ($embstyle eq 'ssi'
7607: || ($embstyle eq 'hdn')
7608: || ($embstyle eq 'rat')
7609: || ($embstyle eq 'prv')
7610: || ($embstyle eq 'ign')) {
7611: #do nothing with these
7612: } elsif (($embstyle eq 'img')
1.695 albertel 7613: || ($embstyle eq 'emb')
7614: || ($embstyle eq 'wrp')) {
7615: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7616: } elsif ($embstyle eq 'unk'
7617: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7618: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7619: } else {
1.718 www 7620: # &logthis("Got a blank emb style");
1.695 albertel 7621: }
1.694 albertel 7622: }
7623: }
1.31 www 7624: return $thisfn;
1.12 www 7625: }
7626:
1.787 albertel 7627: sub clutter_with_no_wrapper {
7628: my $uri = &clutter(shift);
7629: if ($uri =~ m-^/adm/-) {
7630: $uri =~ s-^/adm/wrapper/-/-;
7631: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7632: }
7633: return $uri;
7634: }
7635:
1.557 albertel 7636: sub freeze_escape {
7637: my ($value)=@_;
7638: if (ref($value)) {
7639: $value=&nfreeze($value);
7640: return '__FROZEN__'.&escape($value);
7641: }
7642: return &escape($value);
7643: }
7644:
1.11 www 7645:
1.557 albertel 7646: sub thaw_unescape {
7647: my ($value)=@_;
7648: if ($value =~ /^__FROZEN__/) {
7649: substr($value,0,10,undef);
7650: $value=&unescape($value);
7651: return &thaw($value);
7652: }
7653: return &unescape($value);
7654: }
7655:
1.436 albertel 7656: sub correct_line_ends {
7657: my ($result)=@_;
7658: $$result =~s/\r\n/\n/mg;
7659: $$result =~s/\r/\n/mg;
1.415 albertel 7660: }
1.1 albertel 7661: # ================================================================ Main Program
7662:
1.184 www 7663: sub goodbye {
1.204 albertel 7664: &logthis("Starting Shut down");
1.443 albertel 7665: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 7666: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 7667: #converted
1.599 albertel 7668: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7669: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7670: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7671: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 7672: #1.1 only
1.599 albertel 7673: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7674: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7675: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7676: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7677: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7678: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7679: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7680: &flushcourselogs();
7681: &logthis("Shutting down");
7682: }
7683:
1.852 albertel 7684: sub get_dns {
7685: my ($url,$func) = @_;
7686: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7687: foreach my $dns (<$config>) {
7688: next if ($dns !~ /^\^(\S*)/x);
7689: $dns = $1;
7690: my $ua=new LWP::UserAgent;
7691: my $request=new HTTP::Request('GET',"http://$dns$url");
7692: my $response=$ua->request($request);
7693: next if ($response->is_error());
7694: my @content = split("\n",$response->content);
7695: &$func(\@content);
7696: }
7697: close($config);
7698: }
1.327 albertel 7699: # ------------------------------------------------------------ Read domain file
7700: {
1.852 albertel 7701: my $loaded;
1.846 albertel 7702: my %domain;
7703:
1.852 albertel 7704: sub parse_domain_tab {
7705: my ($lines) = @_;
7706: foreach my $line (@$lines) {
7707: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 7708:
1.846 albertel 7709: chomp($line);
1.852 albertel 7710: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 7711: my %this_domain;
7712: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7713: 'lang_def', 'city', 'longi', 'lati',
7714: 'primary') {
7715: $this_domain{$field} = shift(@elements);
7716: }
7717: $domain{$name} = \%this_domain;
1.852 albertel 7718: }
7719: }
1.864 albertel 7720:
7721: sub reset_domain_info {
7722: undef($loaded);
7723: undef(%domain);
7724: }
7725:
1.852 albertel 7726: sub load_domain_tab {
7727: &get_dns('/adm/dns/domain',\&parse_domain_tab);
7728: my $fh;
7729: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7730: my @lines = <$fh>;
7731: &parse_domain_tab(\@lines);
1.448 albertel 7732: }
1.852 albertel 7733: close($fh);
7734: $loaded = 1;
1.327 albertel 7735: }
1.846 albertel 7736:
7737: sub domain {
1.852 albertel 7738: &load_domain_tab() if (!$loaded);
7739:
1.846 albertel 7740: my ($name,$what) = @_;
7741: return if ( !exists($domain{$name}) );
7742:
7743: if (!$what) {
7744: return $domain{$name}{'description'};
7745: }
7746: return $domain{$name}{$what};
7747: }
1.327 albertel 7748: }
7749:
7750:
1.1 albertel 7751: # ------------------------------------------------------------- Read hosts file
7752: {
1.838 albertel 7753: my %hostname;
1.844 albertel 7754: my %hostdom;
1.845 albertel 7755: my %libserv;
1.852 albertel 7756: my $loaded;
7757:
7758: sub parse_hosts_tab {
7759: my ($file) = @_;
7760: foreach my $configline (@$file) {
7761: next if ($configline =~ /^(\#|\s*$ )/x);
7762: next if ($configline =~ /^\^/);
7763: chomp($configline);
7764: my ($id,$domain,$role,$name)=split(/:/,$configline);
7765: $name=~s/\s//g;
7766: if ($id && $domain && $role && $name) {
7767: $hostname{$id}=$name;
7768: $hostdom{$id}=$domain;
7769: if ($role eq 'library') { $libserv{$id}=$name; }
7770: }
7771: }
7772: }
1.864 albertel 7773:
7774: sub reset_hosts_info {
7775: &reset_domain_info();
7776: &reset_hosts_ip_info();
7777: undef(%hostname);
7778: undef(%hostdom);
7779: undef(%libserv);
7780: undef($loaded);
7781: }
1.1 albertel 7782:
1.852 albertel 7783: sub load_hosts_tab {
7784: &get_dns('/adm/dns/hosts',\&parse_hosts_tab);
7785: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7786: my @config = <$config>;
7787: &parse_hosts_tab(\@config);
7788: close($config);
7789: $loaded=1;
1.1 albertel 7790: }
1.852 albertel 7791:
1.838 albertel 7792: sub hostname {
1.852 albertel 7793: &load_hosts_tab() if (!$loaded);
7794:
1.838 albertel 7795: my ($lonid) = @_;
7796: return $hostname{$lonid};
7797: }
1.845 albertel 7798:
1.838 albertel 7799: sub all_hostnames {
1.852 albertel 7800: &load_hosts_tab() if (!$loaded);
7801:
1.838 albertel 7802: return %hostname;
7803: }
1.845 albertel 7804:
7805: sub is_library {
1.852 albertel 7806: &load_hosts_tab() if (!$loaded);
7807:
1.845 albertel 7808: return exists($libserv{$_[0]});
7809: }
7810:
7811: sub all_library {
1.852 albertel 7812: &load_hosts_tab() if (!$loaded);
7813:
1.845 albertel 7814: return %libserv;
7815: }
7816:
1.841 albertel 7817: sub get_servers {
1.852 albertel 7818: &load_hosts_tab() if (!$loaded);
7819:
1.841 albertel 7820: my ($domain,$type) = @_;
7821: my %possible_hosts = ($type eq 'library') ? %libserv
7822: : %hostname;
7823: my %result;
1.842 albertel 7824: if (ref($domain) eq 'ARRAY') {
7825: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 7826: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 7827: $result{$host} = $hostname;
7828: }
7829: }
7830: } else {
7831: while ( my ($host,$hostname) = each(%possible_hosts)) {
7832: if ($hostdom{$host} eq $domain) {
7833: $result{$host} = $hostname;
7834: }
1.841 albertel 7835: }
7836: }
7837: return %result;
7838: }
1.845 albertel 7839:
1.844 albertel 7840: sub host_domain {
1.852 albertel 7841: &load_hosts_tab() if (!$loaded);
7842:
1.844 albertel 7843: my ($lonid) = @_;
7844: return $hostdom{$lonid};
7845: }
7846:
1.841 albertel 7847: sub all_domains {
1.852 albertel 7848: &load_hosts_tab() if (!$loaded);
7849:
1.841 albertel 7850: my %seen;
7851: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7852: return @uniq;
7853: }
1.1 albertel 7854: }
7855:
1.847 albertel 7856: {
7857: my %iphost;
1.856 albertel 7858: my %name_to_ip;
7859: my %lonid_to_ip;
1.847 albertel 7860: sub get_hosts_from_ip {
7861: my ($ip) = @_;
7862: my %iphosts = &get_iphost();
7863: if (ref($iphosts{$ip})) {
7864: return @{$iphosts{$ip}};
7865: }
7866: return;
1.839 albertel 7867: }
1.864 albertel 7868:
7869: sub reset_hosts_ip_info {
7870: undef(%iphost);
7871: undef(%name_to_ip);
7872: undef(%lonid_to_ip);
7873: }
1.856 albertel 7874:
7875: sub get_host_ip {
7876: my ($lonid) = @_;
7877: if (exists($lonid_to_ip{$lonid})) {
7878: return $lonid_to_ip{$lonid};
7879: }
7880: my $name=&hostname($lonid);
7881: my $ip = gethostbyname($name);
7882: return if (!$ip || length($ip) ne 4);
7883: $ip=inet_ntoa($ip);
7884: $name_to_ip{$name} = $ip;
7885: $lonid_to_ip{$lonid} = $ip;
7886: return $ip;
7887: }
1.847 albertel 7888:
7889: sub get_iphost {
7890: if (%iphost) { return %iphost; }
7891: my %hostname = &all_hostnames();
7892: foreach my $id (keys(%hostname)) {
1.864 albertel 7893: my $name=&hostname($id);
1.847 albertel 7894: my $ip;
7895: if (!exists($name_to_ip{$name})) {
7896: $ip = gethostbyname($name);
7897: if (!$ip || length($ip) ne 4) {
7898: &logthis("Skipping host $id name $name no IP found");
7899: next;
7900: }
7901: $ip=inet_ntoa($ip);
7902: $name_to_ip{$name} = $ip;
7903: } else {
7904: $ip = $name_to_ip{$name};
1.653 albertel 7905: }
1.856 albertel 7906: $lonid_to_ip{$id} = $ip;
1.847 albertel 7907: push(@{$iphost{$ip}},$id);
1.598 albertel 7908: }
1.847 albertel 7909: return %iphost;
1.598 albertel 7910: }
7911: }
7912:
1.862 albertel 7913: BEGIN {
7914:
7915: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7916: unless ($readit) {
7917: {
7918: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7919: %perlvar = (%perlvar,%{$configvars});
7920: }
7921:
7922:
1.1 albertel 7923: # ------------------------------------------------------ Read spare server file
7924: {
1.448 albertel 7925: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7926:
7927: while (my $configline=<$config>) {
7928: chomp($configline);
1.284 matthew 7929: if ($configline) {
1.784 albertel 7930: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7931: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7932: push(@{ $spareid{$type} }, $host);
1.1 albertel 7933: }
7934: }
1.448 albertel 7935: close($config);
1.1 albertel 7936: }
1.11 www 7937: # ------------------------------------------------------------ Read permissions
7938: {
1.448 albertel 7939: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7940:
7941: while (my $configline=<$config>) {
1.448 albertel 7942: chomp($configline);
7943: if ($configline) {
7944: my ($role,$perm)=split(/ /,$configline);
7945: if ($perm ne '') { $pr{$role}=$perm; }
7946: }
1.11 www 7947: }
1.448 albertel 7948: close($config);
1.11 www 7949: }
7950:
7951: # -------------------------------------------- Read plain texts for permissions
7952: {
1.448 albertel 7953: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 7954:
7955: while (my $configline=<$config>) {
1.448 albertel 7956: chomp($configline);
7957: if ($configline) {
1.742 raeburn 7958: my ($short,@plain)=split(/:/,$configline);
7959: %{$prp{$short}} = ();
7960: if (@plain > 0) {
7961: $prp{$short}{'std'} = $plain[0];
7962: for (my $i=1; $i<@plain; $i++) {
7963: $prp{$short}{'alt'.$i} = $plain[$i];
7964: }
7965: }
1.448 albertel 7966: }
1.135 www 7967: }
1.448 albertel 7968: close($config);
1.135 www 7969: }
7970:
7971: # ---------------------------------------------------------- Read package table
7972: {
1.448 albertel 7973: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 7974:
7975: while (my $configline=<$config>) {
1.483 albertel 7976: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 7977: chomp($configline);
7978: my ($short,$plain)=split(/:/,$configline);
7979: my ($pack,$name)=split(/\&/,$short);
7980: if ($plain ne '') {
7981: $packagetab{$pack.'&'.$name.'&name'}=$name;
7982: $packagetab{$short}=$plain;
7983: }
1.11 www 7984: }
1.448 albertel 7985: close($config);
1.329 matthew 7986: }
7987:
7988: # ------------- set up temporary directory
7989: {
7990: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7991:
1.11 www 7992: }
7993:
1.794 albertel 7994: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7995: 'compress_threshold'=> 20_000,
7996: });
1.185 www 7997:
1.281 www 7998: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 7999: $dumpcount=0;
1.22 www 8000:
1.163 harris41 8001: &logtouch();
1.672 albertel 8002: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8003: $readit=1;
1.564 albertel 8004: {
8005: use integer;
8006: my $test=(2**32)+1;
1.568 albertel 8007: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8008: &logthis(" Detected 64bit platform ($_64bit)");
8009: }
1.195 www 8010: }
1.1 albertel 8011: }
1.179 www 8012:
1.1 albertel 8013: 1;
1.191 harris41 8014: __END__
8015:
1.243 albertel 8016: =pod
8017:
1.191 harris41 8018: =head1 NAME
8019:
1.243 albertel 8020: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8021:
8022: =head1 SYNOPSIS
8023:
1.243 albertel 8024: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8025:
8026: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8027:
1.243 albertel 8028: Common parameters:
8029:
8030: =over 4
8031:
8032: =item *
8033:
8034: $uname : an internal username (if $cname expecting a course Id specifically)
8035:
8036: =item *
8037:
8038: $udom : a domain (if $cdom expecting a course's domain specifically)
8039:
8040: =item *
8041:
8042: $symb : a resource instance identifier
8043:
8044: =item *
8045:
8046: $namespace : the name of a .db file that contains the data needed or
8047: being set.
8048:
8049: =back
8050:
1.394 bowersj2 8051: =head1 OVERVIEW
1.191 harris41 8052:
1.394 bowersj2 8053: lonnet provides subroutines which interact with the
8054: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8055: about classes, users, and resources.
1.243 albertel 8056:
8057: For many of these objects you can also use this to store data about
8058: them or modify them in various ways.
1.191 harris41 8059:
1.394 bowersj2 8060: =head2 Symbs
1.191 harris41 8061:
1.394 bowersj2 8062: To identify a specific instance of a resource, LON-CAPA uses symbols
8063: or "symbs"X<symb>. These identifiers are built from the URL of the
8064: map, the resource number of the resource in the map, and the URL of
8065: the resource itself. The latter is somewhat redundant, but might help
8066: if maps change.
8067:
8068: An example is
8069:
8070: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8071:
8072: The respective map entry is
8073:
8074: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8075: title="Problem 2">
8076: </resource>
8077:
8078: Symbs are used by the random number generator, as well as to store and
8079: restore data specific to a certain instance of for example a problem.
8080:
8081: =head2 Storing And Retrieving Data
8082:
8083: X<store()>X<cstore()>X<restore()>Three of the most important functions
8084: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8085: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8086: is is the non-critical message twin of cstore. These functions are for
8087: handlers to store a perl hash to a user's permanent data space in an
8088: easy manner, and to retrieve it again on another call. It is expected
8089: that a handler would use this once at the beginning to retrieve data,
8090: and then again once at the end to send only the new data back.
8091:
8092: The data is stored in the user's data directory on the user's
8093: homeserver under the ID of the course.
8094:
8095: The hash that is returned by restore will have all of the previous
8096: value for all of the elements of the hash.
8097:
8098: Example:
8099:
8100: #creating a hash
8101: my %hash;
8102: $hash{'foo'}='bar';
8103:
8104: #storing it
8105: &Apache::lonnet::cstore(\%hash);
8106:
8107: #changing a value
8108: $hash{'foo'}='notbar';
8109:
8110: #adding a new value
8111: $hash{'bar'}='foo';
8112: &Apache::lonnet::cstore(\%hash);
8113:
8114: #retrieving the hash
8115: my %history=&Apache::lonnet::restore();
8116:
8117: #print the hash
8118: foreach my $key (sort(keys(%history))) {
8119: print("\%history{$key} = $history{$key}");
8120: }
8121:
8122: Will print out:
1.191 harris41 8123:
1.394 bowersj2 8124: %history{1:foo} = bar
8125: %history{1:keys} = foo:timestamp
8126: %history{1:timestamp} = 990455579
8127: %history{2:bar} = foo
8128: %history{2:foo} = notbar
8129: %history{2:keys} = foo:bar:timestamp
8130: %history{2:timestamp} = 990455580
8131: %history{bar} = foo
8132: %history{foo} = notbar
8133: %history{timestamp} = 990455580
8134: %history{version} = 2
8135:
8136: Note that the special hash entries C<keys>, C<version> and
8137: C<timestamp> were added to the hash. C<version> will be equal to the
8138: total number of versions of the data that have been stored. The
8139: C<timestamp> attribute will be the UNIX time the hash was
8140: stored. C<keys> is available in every historical section to list which
8141: keys were added or changed at a specific historical revision of a
8142: hash.
8143:
8144: B<Warning>: do not store the hash that restore returns directly. This
8145: will cause a mess since it will restore the historical keys as if the
8146: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8147:
1.394 bowersj2 8148: Calling convention:
1.191 harris41 8149:
1.394 bowersj2 8150: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8151: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8152:
1.394 bowersj2 8153: For more detailed information, see lonnet specific documentation.
1.191 harris41 8154:
1.394 bowersj2 8155: =head1 RETURN MESSAGES
1.191 harris41 8156:
1.394 bowersj2 8157: =over 4
1.191 harris41 8158:
1.394 bowersj2 8159: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8160:
1.394 bowersj2 8161: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8162: when the connection is brought back up
1.191 harris41 8163:
1.394 bowersj2 8164: =item * B<con_failed>: unable to contact remote host and unable to save message
8165: for later delivery
1.191 harris41 8166:
1.394 bowersj2 8167: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8168:
1.394 bowersj2 8169: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8170: that was requested
1.191 harris41 8171:
1.243 albertel 8172: =back
1.191 harris41 8173:
1.243 albertel 8174: =head1 PUBLIC SUBROUTINES
1.191 harris41 8175:
1.243 albertel 8176: =head2 Session Environment Functions
1.191 harris41 8177:
1.243 albertel 8178: =over 4
1.191 harris41 8179:
1.394 bowersj2 8180: =item *
8181: X<appenv()>
8182: B<appenv(%hash)>: the value of %hash is written to
8183: the user envirnoment file, and will be restored for each access this
1.620 albertel 8184: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8185: process
1.191 harris41 8186:
8187: =item *
1.394 bowersj2 8188: X<delenv()>
8189: B<delenv($regexp)>: removes all items from the session
8190: environment file that matches the regular expression in $regexp. The
1.620 albertel 8191: values are also delted from the current processes %env.
1.191 harris41 8192:
1.795 albertel 8193: =item * get_env_multiple($name)
8194:
8195: gets $name from the %env hash, it seemlessly handles the cases where multiple
8196: values may be defined and end up as an array ref.
8197:
8198: returns an array of values
8199:
1.243 albertel 8200: =back
8201:
8202: =head2 User Information
1.191 harris41 8203:
1.243 albertel 8204: =over 4
1.191 harris41 8205:
8206: =item *
1.394 bowersj2 8207: X<queryauthenticate()>
8208: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8209: authentication scheme
8210:
8211: =item *
1.394 bowersj2 8212: X<authenticate()>
8213: B<authenticate($uname,$upass,$udom)>: try to
8214: authenticate user from domain's lib servers (first use the current
8215: one). C<$upass> should be the users password.
1.191 harris41 8216:
8217: =item *
1.394 bowersj2 8218: X<homeserver()>
8219: B<homeserver($uname,$udom)>: find the server which has
8220: the user's directory and files (there must be only one), this caches
8221: the answer, and also caches if there is a borken connection.
1.191 harris41 8222:
8223: =item *
1.394 bowersj2 8224: X<idget()>
8225: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8226: (IDs are a unique resource in a domain, there must be only 1 ID per
8227: username, and only 1 username per ID in a specific domain) (returns
8228: hash: id=>name,id=>name)
1.191 harris41 8229:
8230: =item *
1.394 bowersj2 8231: X<idrget()>
8232: B<idrget($udom,@unames)>: find the IDs behind a list of
8233: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8234:
8235: =item *
1.394 bowersj2 8236: X<idput()>
8237: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8238:
8239: =item *
1.394 bowersj2 8240: X<rolesinit()>
8241: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8242:
8243: =item *
1.551 albertel 8244: X<getsection()>
8245: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8246: course $cname, return section name/number or '' for "not in course"
8247: and '-1' for "no section"
8248:
8249: =item *
1.394 bowersj2 8250: X<userenvironment()>
8251: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8252: passed in @what from the requested user's environment, returns a hash
8253:
1.858 raeburn 8254: =item *
8255: X<userlog_query()>
1.859 albertel 8256: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8257: activity.log file. %filters defines filters applied when parsing the
8258: log file. These can be start or end timestamps, or the type of action
8259: - log to look for Login or Logout events, check for Checkin or
8260: Checkout, role for role selection. The response is in the form
8261: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8262: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8263:
1.243 albertel 8264: =back
8265:
8266: =head2 User Roles
8267:
8268: =over 4
8269:
8270: =item *
8271:
1.810 raeburn 8272: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8273: F: full access
8274: U,I,K: authentication modes (cxx only)
8275: '': forbidden
8276: 1: user needs to choose course
8277: 2: browse allowed
1.766 albertel 8278: A: passphrase authentication needed
1.243 albertel 8279:
8280: =item *
8281:
8282: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8283: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8284: and course level
8285:
8286: =item *
8287:
8288: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8289: explanation of a user role term
8290:
1.832 raeburn 8291: =item *
8292:
1.858 raeburn 8293: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8294: All arguments are optional. Returns a hash of a roles, either for
8295: co-author/assistant author roles for a user's Construction Space
8296: (default), or if $context is 'user', roles for the user himself,
8297: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8298: and value is set to colon-separated start and end times for the role.
8299: If no username and domain are specified, will default to current
8300: user/domain. Types, roles, and roledoms are references to arrays,
8301: of role statuses (active, future or previous), roles
8302: (e.g., cc,in, st etc.) and domains of the roles which can be used
8303: to restrict the list of roles reported. If no array ref is
8304: provided for types, will default to return only active roles.
1.834 albertel 8305:
1.243 albertel 8306: =back
8307:
8308: =head2 User Modification
8309:
8310: =over 4
8311:
8312: =item *
8313:
8314: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8315: user for the level given by URL. Optional start and end dates (leave empty
8316: string or zero for "no date")
1.191 harris41 8317:
8318: =item *
8319:
1.243 albertel 8320: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8321: change a users, password, possible return values are: ok,
8322: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8323: refused
1.191 harris41 8324:
8325: =item *
8326:
1.243 albertel 8327: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8328:
8329: =item *
8330:
1.243 albertel 8331: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8332: modify user
1.191 harris41 8333:
8334: =item *
8335:
1.286 matthew 8336: modifystudent
8337:
8338: modify a students enrollment and identification information.
8339: The course id is resolved based on the current users environment.
8340: This means the envoking user must be a course coordinator or otherwise
8341: associated with a course.
8342:
1.297 matthew 8343: This call is essentially a wrapper for lonnet::modifyuser and
8344: lonnet::modify_student_enrollment
1.286 matthew 8345:
8346: Inputs:
8347:
8348: =over 4
8349:
8350: =item B<$udom> Students loncapa domain
8351:
8352: =item B<$uname> Students loncapa login name
8353:
8354: =item B<$uid> Students id/student number
8355:
8356: =item B<$umode> Students authentication mode
8357:
8358: =item B<$upass> Students password
8359:
8360: =item B<$first> Students first name
8361:
8362: =item B<$middle> Students middle name
8363:
8364: =item B<$last> Students last name
8365:
8366: =item B<$gene> Students generation
8367:
8368: =item B<$usec> Students section in course
8369:
8370: =item B<$end> Unix time of the roles expiration
8371:
8372: =item B<$start> Unix time of the roles start date
8373:
8374: =item B<$forceid> If defined, allow $uid to be changed
8375:
8376: =item B<$desiredhome> server to use as home server for student
8377:
8378: =back
1.297 matthew 8379:
8380: =item *
8381:
8382: modify_student_enrollment
8383:
8384: Change a students enrollment status in a class. The environment variable
8385: 'role.request.course' must be defined for this function to proceed.
8386:
8387: Inputs:
8388:
8389: =over 4
8390:
8391: =item $udom, students domain
8392:
8393: =item $uname, students name
8394:
8395: =item $uid, students user id
8396:
8397: =item $first, students first name
8398:
8399: =item $middle
8400:
8401: =item $last
8402:
8403: =item $gene
8404:
8405: =item $usec
8406:
8407: =item $end
8408:
8409: =item $start
8410:
8411: =back
8412:
1.191 harris41 8413:
8414: =item *
8415:
1.243 albertel 8416: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8417: custom role; give a custom role to a user for the level given by URL. Specify
8418: name and domain of role author, and role name
1.191 harris41 8419:
8420: =item *
8421:
1.243 albertel 8422: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8423:
8424: =item *
8425:
1.243 albertel 8426: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8427:
8428: =back
8429:
8430: =head2 Course Infomation
8431:
8432: =over 4
1.191 harris41 8433:
8434: =item *
8435:
1.631 albertel 8436: coursedescription($courseid) : returns a hash of information about the
8437: specified course id, including all environment settings for the
8438: course, the description of the course will be in the hash under the
8439: key 'description'
1.191 harris41 8440:
8441: =item *
8442:
1.624 albertel 8443: resdata($name,$domain,$type,@which) : request for current parameter
8444: setting for a specific $type, where $type is either 'course' or 'user',
8445: @what should be a list of parameters to ask about. This routine caches
8446: answers for 5 minutes.
1.243 albertel 8447:
8448: =back
8449:
8450: =head2 Course Modification
8451:
8452: =over 4
1.191 harris41 8453:
8454: =item *
8455:
1.243 albertel 8456: writecoursepref($courseid,%prefs) : write preferences (environment
8457: database) for a course
1.191 harris41 8458:
8459: =item *
8460:
1.243 albertel 8461: createcourse($udom,$description,$url) : make/modify course
8462:
8463: =back
8464:
8465: =head2 Resource Subroutines
8466:
8467: =over 4
1.191 harris41 8468:
8469: =item *
8470:
1.243 albertel 8471: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8472:
8473: =item *
8474:
1.243 albertel 8475: repcopy($filename) : subscribes to the requested file, and attempts to
8476: replicate from the owning library server, Might return
1.607 raeburn 8477: 'unavailable', 'not_found', 'forbidden', 'ok', or
8478: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8479: resource. Expects the local filesystem pathname
8480: (/home/httpd/html/res/....)
8481:
8482: =back
8483:
8484: =head2 Resource Information
8485:
8486: =over 4
1.191 harris41 8487:
8488: =item *
8489:
1.243 albertel 8490: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8491: a vairety of different possible values, $varname should be a request
8492: string, and the other parameters can be used to specify who and what
8493: one is asking about.
8494:
8495: Possible values for $varname are environment.lastname (or other item
8496: from the envirnment hash), user.name (or someother aspect about the
8497: user), resource.0.maxtries (or some other part and parameter of a
8498: resource)
1.204 albertel 8499:
8500: =item *
8501:
1.243 albertel 8502: directcondval($number) : get current value of a condition; reads from a state
8503: string
1.204 albertel 8504:
8505: =item *
8506:
1.243 albertel 8507: condval($condidx) : value of condition index based on state
1.204 albertel 8508:
8509: =item *
8510:
1.243 albertel 8511: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8512: resource's metadata, $what should be either a specific key, or either
8513: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8514: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8515:
8516: this function automatically caches all requests
1.191 harris41 8517:
8518: =item *
8519:
1.243 albertel 8520: metadata_query($query,$custom,$customshow) : make a metadata query against the
8521: network of library servers; returns file handle of where SQL and regex results
8522: will be stored for query
1.191 harris41 8523:
8524: =item *
8525:
1.243 albertel 8526: symbread($filename) : return symbolic list entry (filename argument optional);
8527: returns the data handle
1.191 harris41 8528:
8529: =item *
8530:
1.243 albertel 8531: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 8532: a possible symb for the URL in $thisfn, and if is an encryypted
8533: resource that the user accessed using /enc/ returns a 1 on success, 0
8534: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 8535: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 8536:
1.191 harris41 8537:
8538: =item *
8539:
1.243 albertel 8540: symbclean($symb) : removes versions numbers from a symb, returns the
8541: cleaned symb
1.191 harris41 8542:
8543: =item *
8544:
1.243 albertel 8545: is_on_map($uri) : checks if the $uri is somewhere on the current
8546: course map, user must be in a course for it to work.
1.191 harris41 8547:
8548: =item *
8549:
1.243 albertel 8550: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 8551:
8552: =item *
8553:
1.243 albertel 8554: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8555: a random seed, all arguments are optional, if they aren't sent it uses the
8556: environment to derive them. Note: if symb isn't sent and it can't get one
8557: from &symbread it will use the current time as its return value
1.191 harris41 8558:
8559: =item *
8560:
1.243 albertel 8561: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8562: unfakeable, receipt
1.191 harris41 8563:
8564: =item *
8565:
1.620 albertel 8566: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 8567:
8568: =item *
8569:
1.243 albertel 8570: countacc($url) : count the number of accesses to a given URL
1.191 harris41 8571:
8572: =item *
8573:
1.243 albertel 8574: 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 8575:
8576: =item *
8577:
1.243 albertel 8578: 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 8579:
8580: =item *
8581:
1.243 albertel 8582: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 8583:
8584: =item *
8585:
1.243 albertel 8586: devalidate($symb) : devalidate temporary spreadsheet calculations,
8587: forcing spreadsheet to reevaluate the resource scores next time.
8588:
8589: =back
8590:
8591: =head2 Storing/Retreiving Data
8592:
8593: =over 4
1.191 harris41 8594:
8595: =item *
8596:
1.243 albertel 8597: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8598: for this url; hashref needs to be given and should be a \%hashname; the
8599: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 8600: be derived from the env
1.191 harris41 8601:
8602: =item *
8603:
1.243 albertel 8604: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8605: uses critical subroutine
1.191 harris41 8606:
8607: =item *
8608:
1.243 albertel 8609: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8610: all args are optional
1.191 harris41 8611:
8612: =item *
8613:
1.717 albertel 8614: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8615: dumps the complete (or key matching regexp) namespace into a hash
8616: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8617: normally &store()ed into
8618:
8619: $range should be either an integer '100' (give me the first 100
8620: matching records)
8621: or be two integers sperated by a - with no spaces
8622: '30-50' (give me the 30th through the 50th matching
8623: records)
8624:
8625:
8626: =item *
8627:
8628: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8629: replaces a &store() version of data with a replacement set of data
8630: for a particular resource in a namespace passed in the $storehash hash
8631: reference
8632:
8633: =item *
8634:
1.243 albertel 8635: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8636: works very similar to store/cstore, but all data is stored in a
8637: temporary location and can be reset using tmpreset, $storehash should
8638: be a hash reference, returns nothing on success
1.191 harris41 8639:
8640: =item *
8641:
1.243 albertel 8642: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8643: similar to restore, but all data is stored in a temporary location and
8644: can be reset using tmpreset. Returns a hash of values on success,
8645: error string otherwise.
1.191 harris41 8646:
8647: =item *
8648:
1.243 albertel 8649: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8650: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8651:
8652: =item *
8653:
1.243 albertel 8654: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8655: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8656:
8657: =item *
8658:
1.243 albertel 8659: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8660: namesp ($udom and $uname are optional)
1.191 harris41 8661:
8662: =item *
8663:
1.702 albertel 8664: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8665: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8666: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8667:
1.702 albertel 8668: $range should be either an integer '100' (give me the first 100
8669: matching records)
8670: or be two integers sperated by a - with no spaces
8671: '30-50' (give me the 30th through the 50th matching
8672: records)
1.449 matthew 8673: =item *
8674:
8675: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8676: $store can be a scalar, an array reference, or if the amount to be
8677: incremented is > 1, a hash reference.
8678:
8679: ($udom and $uname are optional)
1.191 harris41 8680:
8681: =item *
8682:
1.243 albertel 8683: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8684: ($udom and $uname are optional)
1.191 harris41 8685:
8686: =item *
8687:
1.243 albertel 8688: cput($namespace,$storehash,$udom,$uname) : critical put
8689: ($udom and $uname are optional)
1.191 harris41 8690:
8691: =item *
8692:
1.748 albertel 8693: newput($namespace,$storehash,$udom,$uname) :
8694:
8695: Attempts to store the items in the $storehash, but only if they don't
8696: currently exist, if this succeeds you can be certain that you have
8697: successfully created a new key value pair in the $namespace db.
8698:
8699:
8700: Args:
8701: $namespace: name of database to store values to
8702: $storehash: hashref to store to the db
8703: $udom: (optional) domain of user containing the db
8704: $uname: (optional) name of user caontaining the db
8705:
8706: Returns:
8707: 'ok' -> succeeded in storing all keys of $storehash
8708: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8709: least <key> already existed in the db (other
8710: requested keys may also already exist)
8711: 'error: <msg>' -> unable to tie the DB or other erorr occured
8712: 'con_lost' -> unable to contact request server
8713: 'refused' -> action was not allowed by remote machine
8714:
8715:
8716: =item *
8717:
1.243 albertel 8718: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8719: reference filled in from namesp (encrypts the return communication)
8720: ($udom and $uname are optional)
1.191 harris41 8721:
8722: =item *
8723:
1.243 albertel 8724: log($udom,$name,$home,$message) : write to permanent log for user; use
8725: critical subroutine
8726:
1.806 raeburn 8727: =item *
8728:
1.860 raeburn 8729: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
8730: array reference filled in from namespace found in domain level on either
8731: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 8732:
8733: =item *
8734:
1.860 raeburn 8735: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
8736: domain level either on specified domain server ($uhome) or primary domain
8737: server ($udom and $uhome are optional)
1.806 raeburn 8738:
1.243 albertel 8739: =back
8740:
8741: =head2 Network Status Functions
8742:
8743: =over 4
1.191 harris41 8744:
8745: =item *
8746:
8747: dirlist($uri) : return directory list based on URI
8748:
8749: =item *
8750:
1.243 albertel 8751: spareserver() : find server with least workload from spare.tab
8752:
8753: =back
8754:
8755: =head2 Apache Request
8756:
8757: =over 4
1.191 harris41 8758:
8759: =item *
8760:
1.243 albertel 8761: ssi($url,%hash) : server side include, does a complete request cycle on url to
8762: localhost, posts hash
8763:
8764: =back
8765:
8766: =head2 Data to String to Data
8767:
8768: =over 4
1.191 harris41 8769:
8770: =item *
8771:
1.243 albertel 8772: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8773: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8774:
8775: =item *
8776:
1.243 albertel 8777: hashref2str($hashref) : convert a hashref into a string complete with
8778: escaping and '=' and '&' separators, supports elements that are
8779: arrayrefs and hashrefs
1.191 harris41 8780:
8781: =item *
8782:
1.243 albertel 8783: arrayref2str($arrayref) : convert an arrayref into a string complete
8784: with escaping and '&' separators, supports elements that are arrayrefs
8785: and hashrefs
1.191 harris41 8786:
8787: =item *
8788:
1.243 albertel 8789: str2hash($string) : convert string to hash using unescaping and
8790: splitting on '=' and '&', supports elements that are arrayrefs and
8791: hashrefs
1.191 harris41 8792:
8793: =item *
8794:
1.243 albertel 8795: str2array($string) : convert string to hash using unescaping and
8796: splitting on '&', supports elements that are arrayrefs and hashrefs
8797:
8798: =back
8799:
8800: =head2 Logging Routines
8801:
8802: =over 4
8803:
8804: These routines allow one to make log messages in the lonnet.log and
8805: lonnet.perm logfiles.
1.191 harris41 8806:
8807: =item *
8808:
1.243 albertel 8809: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8810:
8811: =item *
8812:
1.243 albertel 8813: logthis() : append message to the normal lonnet.log file, it gets
8814: preiodically rolled over and deleted.
1.191 harris41 8815:
8816: =item *
8817:
1.243 albertel 8818: logperm() : append a permanent message to lonnet.perm.log, this log
8819: file never gets deleted by any automated portion of the system, only
8820: messages of critical importance should go in here.
8821:
8822: =back
8823:
8824: =head2 General File Helper Routines
8825:
8826: =over 4
1.191 harris41 8827:
8828: =item *
8829:
1.481 raeburn 8830: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8831: (a) files in /uploaded
8832: (i) If a local copy of the file exists -
8833: compares modification date of local copy with last-modified date for
8834: definitive version stored on home server for course. If local copy is
8835: stale, requests a new version from the home server and stores it.
8836: If the original has been removed from the home server, then local copy
8837: is unlinked.
8838: (ii) If local copy does not exist -
8839: requests the file from the home server and stores it.
8840:
8841: If $caller is 'uploadrep':
8842: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8843: for request for files originally uploaded via DOCS.
8844: - returns 'ok' if fresh local copy now available, -1 otherwise.
8845:
8846: Otherwise:
8847: This indicates a call from the content generation phase of the request.
8848: - returns the entire contents of the file or -1.
8849:
8850: (b) files in /res
8851: - returns the entire contents of a file or -1;
8852: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8853:
1.712 albertel 8854:
8855: =item *
8856:
8857: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8858: reference
8859:
8860: returns either a stat() list of data about the file or an empty list
8861: if the file doesn't exist or couldn't find out about it (connection
8862: problems or user unknown)
8863:
1.191 harris41 8864: =item *
8865:
1.243 albertel 8866: filelocation($dir,$file) : returns file system location of a file
8867: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8868: directory that relative $file lookups are to looked in ($dir of /a/dir
8869: and a file of ../bob will become /a/bob)
1.191 harris41 8870:
8871: =item *
8872:
8873: hreflocation($dir,$file) : returns file system location or a URL; same as
8874: filelocation except for hrefs
8875:
8876: =item *
8877:
8878: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8879:
1.243 albertel 8880: =back
8881:
1.608 albertel 8882: =head2 Usererfile file routines (/uploaded*)
8883:
8884: =over 4
8885:
8886: =item *
8887:
8888: userfileupload(): main rotine for putting a file in a user or course's
8889: filespace, arguments are,
8890:
1.620 albertel 8891: formname - required - this is the name of the element in $env where the
1.608 albertel 8892: filename, and the contents of the file to create/modifed exist
1.620 albertel 8893: the filename is in $env{'form.'.$formname.'.filename'} and the
8894: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8895: coursedoc - if true, store the file in the course of the active role
8896: of the current user
8897: subdir - required - subdirectory to put the file in under ../userfiles/
8898: if undefined, it will be placed in "unknown"
8899:
8900: (This routine calls clean_filename() to remove any dangerous
8901: characters from the filename, and then calls finuserfileupload() to
8902: complete the transaction)
8903:
8904: returns either the url of the uploaded file (/uploaded/....) if successful
8905: and /adm/notfound.html if unsuccessful
8906:
8907: =item *
8908:
8909: clean_filename(): routine for cleaing a filename up for storage in
8910: userfile space, argument is:
8911:
8912: filename - proposed filename
8913:
8914: returns: the new clean filename
8915:
8916: =item *
8917:
8918: finishuserfileupload(): routine that creaes and sends the file to
8919: userspace, probably shouldn't be called directly
8920:
8921: docuname: username or courseid of destination for the file
8922: docudom: domain of user/course of destination for the file
8923: formname: same as for userfileupload()
8924: fname: filename (inculding subdirectories) for the file
8925:
8926: returns either the url of the uploaded file (/uploaded/....) if successful
8927: and /adm/notfound.html if unsuccessful
8928:
8929: =item *
8930:
8931: renameuserfile(): renames an existing userfile to a new name
8932:
8933: Args:
8934: docuname: username or courseid of destination for the file
8935: docudom: domain of user/course of destination for the file
8936: old: current file name (including any subdirs under userfiles)
8937: new: desired file name (including any subdirs under userfiles)
8938:
8939: =item *
8940:
8941: mkdiruserfile(): creates a directory is a userfiles dir
8942:
8943: Args:
8944: docuname: username or courseid of destination for the file
8945: docudom: domain of user/course of destination for the file
8946: dir: dir to create (including any subdirs under userfiles)
8947:
8948: =item *
8949:
8950: removeuserfile(): removes a file that exists in userfiles
8951:
8952: Args:
8953: docuname: username or courseid of destination for the file
8954: docudom: domain of user/course of destination for the file
8955: fname: filname to delete (including any subdirs under userfiles)
8956:
8957: =item *
8958:
8959: removeuploadedurl(): convience function for removeuserfile()
8960:
8961: Args:
8962: url: a full /uploaded/... url to delete
8963:
1.747 albertel 8964: =item *
8965:
8966: get_portfile_permissions():
8967: Args:
8968: domain: domain of user or course contain the portfolio files
8969: user: name of user or num of course contain the portfolio files
8970: Returns:
8971: hashref of a dump of the proper file_permissions.db
8972:
8973:
8974: =item *
8975:
8976: get_access_controls():
8977:
8978: Args:
8979: current_permissions: the hash ref returned from get_portfile_permissions()
8980: group: (optional) the group you want the files associated with
8981: file: (optional) the file you want access info on
8982:
8983: Returns:
1.749 raeburn 8984: a hash (keys are file names) of hashes containing
8985: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8986: values are XML containing access control settings (see below)
1.747 albertel 8987:
8988: Internal notes:
8989:
1.749 raeburn 8990: access controls are stored in file_permissions.db as key=value pairs.
8991: key -> path to file/file_name\0uniqueID:scope_end_start
8992: where scope -> public,guest,course,group,domains or users.
8993: end -> UNIX time for end of access (0 -> no end date)
8994: start -> UNIX time for start of access
8995:
8996: value -> XML description of access control
8997: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8998: <start></start>
8999: <end></end>
9000:
9001: <password></password> for scope type = guest
9002:
9003: <domain></domain> for scope type = course or group
9004: <number></number>
9005: <roles id="">
9006: <role></role>
9007: <access></access>
9008: <section></section>
9009: <group></group>
9010: </roles>
9011:
9012: <dom></dom> for scope type = domains
9013:
9014: <users> for scope type = users
9015: <user>
9016: <uname></uname>
9017: <udom></udom>
9018: </user>
9019: </users>
9020: </scope>
9021:
9022: Access data is also aggregated for each file in an additional key=value pair:
9023: key -> path to file/file_name\0accesscontrol
9024: value -> reference to hash
9025: hash contains key = value pairs
9026: where key = uniqueID:scope_end_start
9027: value = UNIX time record was last updated
9028:
9029: Used to improve speed of look-ups of access controls for each file.
9030:
9031: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9032:
9033: modify_access_controls():
9034:
9035: Modifies access controls for a portfolio file
9036: Args
9037: 1. file name
9038: 2. reference to hash of required changes,
9039: 3. domain
9040: 4. username
9041: where domain,username are the domain of the portfolio owner
9042: (either a user or a course)
9043:
9044: Returns:
9045: 1. result of additions or updates ('ok' or 'error', with error message).
9046: 2. result of deletions ('ok' or 'error', with error message).
9047: 3. reference to hash of any new or updated access controls.
9048: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9049: key = integer (inbound ID)
9050: value = uniqueID
1.747 albertel 9051:
1.608 albertel 9052: =back
9053:
1.243 albertel 9054: =head2 HTTP Helper Routines
9055:
9056: =over 4
9057:
1.191 harris41 9058: =item *
9059:
9060: escape() : unpack non-word characters into CGI-compatible hex codes
9061:
9062: =item *
9063:
9064: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9065:
1.243 albertel 9066: =back
9067:
9068: =head1 PRIVATE SUBROUTINES
9069:
9070: =head2 Underlying communication routines (Shouldn't call)
9071:
9072: =over 4
9073:
9074: =item *
9075:
9076: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9077:
9078: =item *
9079:
9080: reply() : uses subreply to send a message to remote machine, logs all failures
9081:
9082: =item *
9083:
9084: critical() : passes a critical message to another server; if cannot
9085: get through then place message in connection buffer directory and
9086: returns con_delayed, if incapable of saving message, returns
9087: con_failed
9088:
9089: =item *
9090:
9091: reconlonc() : tries to reconnect lonc client processes.
9092:
9093: =back
9094:
9095: =head2 Resource Access Logging
9096:
9097: =over 4
9098:
9099: =item *
9100:
9101: flushcourselogs() : flush (save) buffer logs and access logs
9102:
9103: =item *
9104:
9105: courselog($what) : save message for course in hash
9106:
9107: =item *
9108:
9109: courseacclog($what) : save message for course using &courselog(). Perform
9110: special processing for specific resource types (problems, exams, quizzes, etc).
9111:
1.191 harris41 9112: =item *
9113:
9114: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9115: as a PerlChildExitHandler
1.243 albertel 9116:
9117: =back
9118:
9119: =head2 Other
9120:
9121: =over 4
9122:
9123: =item *
9124:
9125: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9126:
9127: =back
9128:
9129: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>