File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.868:
download - view:
text,
annotated -
select for diffs
Wed Apr 11 21:37:20 2007 UTC (17 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
Put reg exp check for domain logo in lonnet - &is_domainimage()
checkauthen, publiccheck and lonacc all need this to serve images for log-in page if port 8080 is not in use.
Other possibilities - (1) call once in checkauthen and pass along to publiccheck and lonacc in Apache notes, or (2) modify loncapa_apach.conf.
lonhttpd to use a call to the same routine.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.868 2007/04/11 21:37:20 raeburn Exp $
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: #
28: ###
29:
30: package Apache::lonnet;
31:
32: use strict;
33: use LWP::UserAgent();
34: use HTTP::Headers;
35: use HTTP::Date;
36: # use Date::Parse;
37: use vars
38: qw(%perlvar %badServerCache %spareid
39: %pr %prp $memcache %packagetab
40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
42: $tmpdir $_64bit %env);
43:
44: use IO::Socket;
45: use GDBM_File;
46: use HTML::LCParser;
47: use HTML::Parser;
48: use Fcntl qw(:flock);
49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
50: use Time::HiRes qw( gettimeofday tv_interval );
51: use Cache::Memcached;
52: use Digest::MD5;
53: use Math::Random;
54: use LONCAPA qw(:DEFAULT :match);
55: use LONCAPA::Configuration;
56:
57: my $readit;
58: my $max_connection_retries = 10; # Or some such value.
59:
60: require Exporter;
61:
62: our @ISA = qw (Exporter);
63: our @EXPORT = qw(%env);
64:
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:
88: # --------------------------------------------------------------------- Logging
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,
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: },
107: $env{'course.'.$env{'request.course.id'}.'.domain'},
108: $env{'course.'.$env{'request.course.id'}.'.num'}
109: );
110: }
111: }
112:
113: sub logtouch {
114: my $execdir=$perlvar{'lonDaemons'};
115: unless (-e "$execdir/logs/lonnet.log") {
116: open(my $fh,">>$execdir/logs/lonnet.log");
117: close $fh;
118: }
119: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
120: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
121: }
122:
123: sub logthis {
124: my $message=shift;
125: my $execdir=$perlvar{'lonDaemons'};
126: my $now=time;
127: my $local=localtime($now);
128: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
129: print $fh "$local ($$): $message\n";
130: close($fh);
131: }
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);
140: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
141: print $fh "$now:$message:$local\n";
142: close($fh);
143: }
144: return 1;
145: }
146:
147: sub create_connection {
148: my ($hostname,$lonid) = @_;
149: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
150: Type => SOCK_STREAM,
151: Timeout => 10);
152: return 0 if (!$client);
153: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
154: my $result = <$client>;
155: chomp($result);
156: return 1 if ($result eq 'done');
157: return 0;
158: }
159:
160:
161: # -------------------------------------------------- Non-critical communication
162: sub subreply {
163: my ($cmd,$server)=@_;
164: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
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
175: # or loncnew child is listening so we can connect or everything's dead.
176: #
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!
187: } else {
188: &create_connection(&hostname($server),$server);
189: }
190: sleep(1); # Try again later if failed connection.
191: }
192: my $answer;
193: if ($client) {
194: print $client "sethost:$server:$cmd\n";
195: $answer=<$client>;
196: if (!$answer) { $answer="con_lost"; }
197: chomp($answer);
198: } else {
199: $answer = 'con_lost'; # Failed connection.
200: }
201: return $answer;
202: }
203:
204: sub reply {
205: my ($cmd,$server)=@_;
206: unless (defined(&hostname($server))) { return 'no_such_host'; }
207: my $answer=subreply($cmd,$server);
208: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
209: &logthis("<font color=\"blue\">WARNING:".
210: " $cmd to $server returned $answer</font>");
211: }
212: return $answer;
213: }
214:
215: # ----------------------------------------------------------- Send USR1 to lonc
216:
217: sub reconlonc {
218: &logthis("Trying to reconnect lonc");
219: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
220: if (open(my $fh,"<$loncfile")) {
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;
227: } else {
228: &logthis(
229: "<font color=\"blue\">WARNING:".
230: " lonc at pid $loncpid not responding, giving up</font>");
231: }
232: } else {
233: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
234: }
235: }
236:
237: # ------------------------------------------------------ Critical communication
238:
239: sub critical {
240: my ($cmd,$server)=@_;
241: unless (&hostname($server)) {
242: &logthis("<font color=\"blue\">WARNING:".
243: " Critical message to unknown server ($server)</font>");
244: return 'no_such_host';
245: }
246: my $answer=reply($cmd,$server);
247: if ($answer eq 'con_lost') {
248: &reconlonc("$perlvar{'lonSockDir'}/$server");
249: my $answer=reply($cmd,$server);
250: if ($answer eq 'con_lost') {
251: my $now=time;
252: my $middlename=$cmd;
253: $middlename=substr($middlename,0,16);
254: $middlename=~s/\W//g;
255: my $dfilename=
256: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
257: $dumpcount++;
258: {
259: my $dfh;
260: if (open($dfh,">$dfilename")) {
261: print $dfh "$cmd\n";
262: close($dfh);
263: }
264: }
265: sleep 2;
266: my $wcmd='';
267: {
268: my $dfh;
269: if (open($dfh,"<$dfilename")) {
270: $wcmd=<$dfh>;
271: close($dfh);
272: }
273: }
274: chomp($wcmd);
275: if ($wcmd eq $cmd) {
276: &logthis("<font color=\"blue\">WARNING: ".
277: "Connection buffer $dfilename: $cmd</font>");
278: &logperm("D:$server:$cmd");
279: return 'con_delayed';
280: } else {
281: &logthis("<font color=\"red\">CRITICAL:"
282: ." Critical connection failed: $server $cmd</font>");
283: &logperm("F:$server:$cmd");
284: return 'con_failed';
285: }
286: }
287: }
288: return $answer;
289: }
290:
291: # ------------------------------------------- check if return value is an error
292:
293: sub error {
294: my ($result) = @_;
295: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
296: if ($2 == 2) { return undef; }
297: return $1;
298: }
299: return undef;
300: }
301:
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) {
313: if ($line !~ m/=/) {
314: return 0;
315: }
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: }
327: return 1;
328: }
329:
330: # ------------------------------------------- Transfer profile into environment
331: my $env_loaded;
332: sub transfer_profile_to_env {
333: my ($lonidsdir,$handle,$force_transfer) = @_;
334: if (!$force_transfer && $env_loaded) { return; }
335:
336: if (!defined($lonidsdir)) {
337: $lonidsdir = $perlvar{'lonIDsDir'};
338: }
339: if (!defined($handle)) {
340: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
341: }
342:
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: }
359: }
360:
361: my %remove;
362: while ( my $envname = each(%env) ) {
363: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
364: if ($time < time-300) {
365: $remove{$key}++;
366: }
367: }
368: }
369:
370: $env{'user.environment'} = "$lonidsdir/$handle.id";
371: $env_loaded=1;
372: foreach my $expired_key (keys(%remove)) {
373: &delenv($expired_key);
374: }
375: }
376:
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:
397: # ---------------------------------------------------------- Append Environment
398:
399: sub appenv {
400: my %newenv=@_;
401: foreach my $key (keys(%newenv)) {
402: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
403: &logthis("<font color=\"blue\">WARNING: ".
404: "Attempt to modify environment ".$key." to ".$newenv{$key}
405: .'</font>');
406: delete($newenv{$key});
407: } else {
408: $env{$key}=$newenv{$key};
409: }
410: }
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)) {
416: while (my ($key,$value) = each(%newenv)) {
417: $disk_env{$key} = $value;
418: }
419: untie(%disk_env);
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/)) {
428: &logthis("<font color=\"blue\">WARNING: ".
429: "Attempt to delete from environment ".$delthis);
430: return 'error';
431: }
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)) {
437: foreach my $key (keys(%disk_env)) {
438: if ($key=~/^$delthis/) {
439: delete($env{$key});
440: delete($disk_env{$key});
441: }
442: }
443: untie(%disk_env);
444: }
445: return 'ok';
446: }
447:
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:
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;}
472: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
473: if ($curtime-$mtime < 1800) { $numusers++; }
474: }
475: closedir(LONIDS);
476: }
477: my $userloadpercent=0;
478: my $maxuserload=$perlvar{'lonUserLoadLim'};
479: if ($maxuserload) {
480: $userloadpercent=100*$numusers/$maxuserload;
481: }
482: $userloadpercent=sprintf("%.2f",$userloadpercent);
483: return $userloadpercent;
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'}) {
493: open(my $loadfile,'/proc/loadavg');
494: $loadavg=<$loadfile>;
495: $loadavg =~ s/\s.*//g;
496: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
497: close($loadfile);
498: } else {
499: $loadavg=&reply('load',$checkserver);
500: }
501: my $overload=$loadavg-100;
502: if ($overload>0) {
503: $r->err_headers_out->{'Retry-After'}=$overload;
504: $r->log_error('Overload of '.$overload.' on '.$checkserver);
505: return 413;
506: }
507: return '';
508: }
509:
510: # ------------------------------ Find server with least workload from spare.tab
511:
512: sub spareserver {
513: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
514: my $spare_server;
515: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
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) {
534: $spare_server="http://".&hostname($spare_server);
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;
555: } else {
556: $load = $loadans;
557: }
558: } else {
559: $load = $userloadans;
560: }
561:
562: if (($load =~ /\d/) && ($load < $lowest_load)) {
563: $spare_server = $try_server;
564: $lowest_load = $load;
565: }
566: return ($spare_server,$lowest_load);
567: }
568: # --------------------------------------------- Try to change a user's password
569:
570: sub changepass {
571: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
572: $currentpass = &escape($currentpass);
573: $newpass = &escape($newpass);
574: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
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;
601: }
602:
603: # ----------------------- Try to determine user's current authentication scheme
604:
605: sub queryauthenticate {
606: my ($uname,$udom)=@_;
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");
615: }
616: return $answer;
617: }
618:
619: # --------- Try to authenticate user from domain's lib servers (first this one)
620:
621: sub authenticate {
622: my ($uname,$upass,$udom)=@_;
623: $upass=&escape($upass);
624: $uname= &LONCAPA::clean_username($uname);
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: }
634: return 'no_host';
635: }
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';
644: }
645: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
646: return 'no_host';
647: }
648:
649: # ---------------------- Find the homebase for a user from domain's lib servers
650:
651: my %homecache;
652: sub homeserver {
653: my ($uname,$udom,$ignoreBadCache)=@_;
654: my $index="$uname:$udom";
655:
656: if (exists($homecache{$index})) { return $homecache{$index}; }
657:
658: my %servers = &get_servers($udom,'library');
659: foreach my $tryserver (keys(%servers)) {
660: next if ($ignoreBadCache ne 'true' &&
661: exists($badServerCache{$tryserver}));
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: }
670: }
671: return 'no_host';
672: }
673:
674: # ------------------------------------- Find the usernames behind a list of IDs
675:
676: sub idget {
677: my ($udom,@ids)=@_;
678: my %returnhash=();
679:
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: }
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=();
704: foreach my $uname (@unames) {
705: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
706: }
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=();
715: foreach my $uname (keys(%ids)) {
716: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
717: my $uhom=&homeserver($uname,$udom);
718: if ($uhom ne 'no_host') {
719: my $id=&escape($ids{$uname});
720: $id=~tr/A-Z/a-z/;
721: my $esc_unam=&escape($uname);
722: if ($servers{$uhom}) {
723: $servers{$uhom}.='&'.$id.'='.$esc_unam;
724: } else {
725: $servers{$uhom}=$id.'='.$esc_unam;
726: }
727: }
728: }
729: foreach my $server (keys(%servers)) {
730: &critical('idput:'.$udom.':'.$servers{$server},$server);
731: }
732: }
733:
734: # ------------------------------------------- get items from domain db files
735:
736: sub get_dom {
737: my ($namespace,$storearr,$udom,$uhome)=@_;
738: my $items='';
739: foreach my $item (@$storearr) {
740: $items.=&escape($item).'&';
741: }
742: $items=~s/\&$//;
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')) {
758: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
759: my %returnhash;
760: if ($rep =~ /^error: 2 /) {
761: return %returnhash;
762: }
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 {
775: &logthis("get_dom failed - no homeserver and/or domain");
776: }
777: }
778:
779: # -------------------------------------------- put items in domain db files
780:
781: sub put_dom {
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')) {
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 {
805: &logthis("put_dom failed - no homeserver and/or domain");
806: }
807: }
808:
809: sub retrieve_inst_usertypes {
810: my ($udom) = @_;
811: my (%returnhash,@order);
812: if (defined(&domain($udom,'primary'))) {
813: my $uhome=&domain($udom,'primary');
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:
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:
843: # --------------------------------------------------- Assign a key to a student
844:
845: sub assign_access_key {
846: #
847: # a valid key looks like uname:udom#comments
848: # comments are being appended
849: #
850: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
851: $kdom=
852: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
853: $knum=
854: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
855: $cdom=
856: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
857: $cnum=
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));
861: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
862: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
863: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
864: # assigned to this person
865: # - this should not happen,
866: # unless something went wrong
867: # the first time around
868: # ready to assign
869: $logentry=$1.'; '.$logentry;
870: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
871: $kdom,$knum) eq 'ok') {
872: # key now belongs to user
873: my $envkey='key.'.$cdom.'_'.$cnum;
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: }
884: } elsif (!$existing{$ckey}) {
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: }
891: }
892:
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=
902: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
903: $cnum=
904: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
905: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
906: if ($existing{$ckey}) {
907: $existing{$ckey}.='; '.$logentry;
908: # ready to assign
909: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
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:
921: # ------------------------------------------------------ Generate a set of keys
922:
923: sub generate_access_keys {
924: my ($number,$cdom,$cnum,$logentry)=@_;
925: $cdom=
926: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
927: $cnum=
928: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
929: unless (&allowed('mky',$cdom)) { return 0; }
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 {
945: if (&put('accesskeys',
946: { $newkey => '# generated '.localtime().
947: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
948: '; '.$logentry },
949: $cdom,$cnum) eq 'ok') {
950: $total++;
951: }
952: }
953: }
954: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
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=
964: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
965: $cnum=
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));
969: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
970: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
971: }
972:
973: # ------------------------------------- Find the section of student in a course
974: sub devalidate_getsection_cache {
975: my ($udom,$unam,$courseid)=@_;
976: my $hashid="$udom:$unam:$courseid";
977: &devalidate_cache_new('getsection',$hashid);
978: }
979:
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:
999: sub getsection {
1000: my ($udom,$unam,$courseid)=@_;
1001: my $cachetime=1800;
1002:
1003: my $hashid="$udom:$unam:$courseid";
1004: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1005: if (defined($cached)) { return $result; }
1006:
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: #
1022: $courseid = &courseid_to_courseurl($courseid);
1023: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1024: foreach my $key (keys(%roleshash)) {
1025: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1026: my $section=$1;
1027: if ($key eq $courseid.'_st') { $section=''; }
1028: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1029: my $now=time;
1030: if (defined($end) && $end && ($now > $end)) {
1031: $Expired{$end}=$section;
1032: next;
1033: }
1034: if (defined($start) && $start && ($now < $start)) {
1035: $Pending{$start}=$section;
1036: next;
1037: }
1038: return &do_cache_new('getsection',$hashid,$section,$cachetime);
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);
1045: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1046: }
1047: if (scalar(keys(%Expired))) {
1048: my @sorted = sort {$a <=> $b} keys(%Expired);
1049: my $time = pop(@sorted);
1050: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1051: }
1052: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1053: }
1054:
1055: sub save_cache {
1056: &purge_remembered();
1057: #&Apache::loncommon::validate_page();
1058: undef(%env);
1059: undef($env_loaded);
1060: }
1061:
1062: my $to_remember=-1;
1063: my %remembered;
1064: my %accessed;
1065: my $kicks=0;
1066: my $hits=0;
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:
1073: sub devalidate_cache_new {
1074: my ($name,$id,$debug) = @_;
1075: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1076: $id=&make_key($name,$id);
1077: $memcache->delete($id);
1078: delete($remembered{$id});
1079: delete($accessed{$id});
1080: }
1081:
1082: sub is_cached_new {
1083: my ($name,$id,$debug) = @_;
1084: $id=&make_key($name,$id);
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"); }
1094: return (undef,undef);
1095: }
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) = @_;
1107: $id=&make_key($name,$id);
1108: my $setvalue=$value;
1109: if (!defined($setvalue)) {
1110: $setvalue='__undef__';
1111: }
1112: if (!defined($time) ) {
1113: $time=600;
1114: }
1115: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1116: $memcache->set($id,$setvalue,$time);
1117: # need to make a copy of $value
1118: #&make_room($id,$value,$debug);
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"); }
1140: return;
1141: }
1142:
1143: sub purge_remembered {
1144: #&logthis("Tossing ".scalar(keys(%remembered)));
1145: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1146: undef(%remembered);
1147: undef(%accessed);
1148: }
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;
1162: }
1163:
1164: # ---------------------------------------------------------- Get a studentphoto
1165: sub studentphoto {
1166: my ($udom,$unam,$ext) = @_;
1167: my $home=&Apache::lonnet::homeserver($unam,$udom);
1168: if (defined($env{'request.course.id'})) {
1169: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1170: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1171: return(&retrievestudentphoto($udom,$unam,$ext));
1172: } else {
1173: my ($result,$perm_reqd)=
1174: &Apache::lonnet::auto_photo_permission($unam,$udom);
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) =
1184: &Apache::lonnet::auto_photo_permission($unam,$udom);
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: }
1211: }
1212: }
1213:
1214: # -------------------------------------------------------------------- New chat
1215:
1216: sub chatsend {
1217: my ($newentry,$anon,$group)=@_;
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'};
1221: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1222: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1223: &escape($newentry)).':'.$group,$chome);
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;
1236: my ($result,$cached)=&is_cached_new('resversion',$fname);
1237: if (defined($cached)) { return $result; }
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: }
1249: return &do_cache_new('resversion',$fname,$answer,600);
1250: }
1251:
1252: # ----------------------------- Subscribe to a resource, return URL if possible
1253:
1254: sub subscribe {
1255: my $fname=shift;
1256: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1257: $fname=~s/[\n\r]//g;
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);
1262: if ($home eq 'no_host') {
1263: return 'not_found';
1264: }
1265: my $answer=reply("sub:$fname",$home);
1266: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1267: $answer.=' by '.$home;
1268: }
1269: return $answer;
1270: }
1271:
1272: # -------------------------------------------------------------- Replicate file
1273:
1274: sub repcopy {
1275: my $filename=shift;
1276: $filename=~s/\/+/\//g;
1277: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1278: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1279: if ($filename=~m|^/home/httpd/html/userfiles/| or
1280: $filename=~m -^/*(uploaded|editupload)/-) {
1281: return &repcopy_userfile($filename);
1282: }
1283: $filename=~s/[\n\r]//g;
1284: my $transname="$filename.in.transfer";
1285: # FIXME: this should flock
1286: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1287: my $remoteurl=subscribe($filename);
1288: if ($remoteurl =~ /^con_lost by/) {
1289: &logthis("Subscribe returned $remoteurl: $filename");
1290: return 'unavailable';
1291: } elsif ($remoteurl eq 'not_found') {
1292: #&logthis("Subscribe returned not_found: $filename");
1293: return 'not_found';
1294: } elsif ($remoteurl =~ /^rejected by/) {
1295: &logthis("Subscribe returned $remoteurl: $filename");
1296: return 'forbidden';
1297: } elsif ($remoteurl eq 'directory') {
1298: return 'ok';
1299: } else {
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'}) {
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");
1309: return 'bad_request';
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;
1324: &logthis("<font color=\"blue\">WARNING:"
1325: ." LWP get: $message: $filename</font>");
1326: return 'unavailable';
1327: } else {
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(
1334: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1335: }
1336: }
1337: rename($transname,$filename);
1338: return 'ok';
1339: }
1340: }
1341: }
1342: }
1343:
1344: # ------------------------------------------------ Get server side include body
1345: sub ssi_body {
1346: my ($filelink,%form)=@_;
1347: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1348: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1349: }
1350: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1351: &ssi($filelink,%form));
1352: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1353: $output=~s/^.*?\<body[^\>]*\>//si;
1354: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1355: return $output;
1356: }
1357:
1358: # --------------------------------------------------------- Server Side Include
1359:
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:
1369: sub ssi {
1370:
1371: my ($fn,%form)=@_;
1372:
1373: my $ua=new LWP::UserAgent;
1374:
1375: my $request;
1376:
1377: $form{'no_update_last_known'}=1;
1378:
1379: if (%form) {
1380: $request=new HTTP::Request('POST',&absolute_url().$fn);
1381: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1382: } else {
1383: $request=new HTTP::Request('GET',&absolute_url().$fn);
1384: }
1385:
1386: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1387: my $response=$ua->request($request);
1388:
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);
1397: return $response->content;
1398: }
1399:
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);
1411: }
1412:
1413: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1414: # input: action, courseID, current domain, intended
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: #
1419: # output: url to file (if action was uploaddoc),
1420: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1421: #
1422: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1423: # course.
1424: #
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.
1428: #
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.
1435: #
1436: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1437: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
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.
1441: #
1442:
1443: sub process_coursefile {
1444: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1445: my $fetchresult;
1446: my $home=&homeserver($docuname,$docudom);
1447: if ($action eq 'propagate') {
1448: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1449: $home);
1450: } else {
1451: my $fpath = '';
1452: my $fname = $file;
1453: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1454: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1455: my $filepath = &build_filepath($fpath);
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,
1464: $home);
1465: }
1466: } elsif ($action eq 'uploaddoc') {
1467: open(my $fh,'>'.$filepath.'/'.$fname);
1468: print $fh $env{'form.'.$source};
1469: close($fh);
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: }
1476: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1477: $home);
1478: if ($fetchresult eq 'ok') {
1479: return '/uploaded/'.$fpath.'/'.$fname;
1480: } else {
1481: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1482: ' to host '.$home.': '.$fetchresult);
1483: return '/adm/notfound.html';
1484: }
1485: }
1486: }
1487: unless ( $fetchresult eq 'ok') {
1488: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1489: ' to host '.$home.': '.$fetchresult);
1490: }
1491: return $fetchresult;
1492: }
1493:
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 {
1510: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
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);
1521: my $home=&homeserver($docuname,$docudom);
1522: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1523: $home);
1524: if ($$fetchresult eq 'ok') {
1525: return '/uploaded/'.$fpath.'/'.$fname;
1526: } else {
1527: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1528: ' to host '.$home.': '.$$fetchresult);
1529: return '/adm/notfound.html';
1530: }
1531: }
1532:
1533: sub clean_filename {
1534: my ($fname,$args)=@_;
1535: # Replace Windows backslashes by forward slashes
1536: $fname=~s/\\/\//g;
1537: if (!$args->{'keep_path'}) {
1538: # Get rid of everything but the actual filename
1539: $fname=~s/^.*\/([^\/]+)$/$1/;
1540: }
1541: # Replace spaces by underscores
1542: $fname=~s/\s+/\_/g;
1543: # Replace all other weird characters by nothing
1544: $fname=~s{[^/\w\.\-]}{}g;
1545: # Replace all .\d. sequences with _\d. so they no longer look like version
1546: # numbers
1547: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1548: return $fname;
1549: }
1550:
1551: # --------------- Take an uploaded file and put it into the userfiles directory
1552: # input: $formname - the contents of the file are in $env{"form.$formname"}
1553: # the desired filenam is in $env{"form.$formname.filename"}
1554: # $coursedoc - if true up to the current course
1555: # if false
1556: # $subdir - directory in userfile to store the file into
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
1562: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1563: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1564: #
1565: # output: url of file in userspace, or error: <message>
1566: # or /adm/notfound.html if failure to upload occurse
1567:
1568:
1569: sub userfileupload {
1570: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1571: $destudom,$thumbwidth,$thumbheight)=@_;
1572: if (!defined($subdir)) { $subdir='unknown'; }
1573: my $fname=$env{'form.'.$formname.'.filename'};
1574: $fname=&clean_filename($fname);
1575: # See if there is anything left
1576: unless ($fname) { return 'error: no uploaded file'; }
1577: chop($env{'form.'.$formname});
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);
1590: print $fh $env{'form.'.$formname};
1591: close($fh);
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;
1608: }
1609:
1610: # Create the directory if not present
1611: $fname="$subdir/$fname";
1612: if ($coursedoc) {
1613: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1614: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1615: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1616: return &finishuserfileupload($docuname,$docudom,
1617: $formname,$fname,$parser,$allfiles,
1618: $codebase,$thumbwidth,$thumbheight);
1619: } else {
1620: $fname=$env{'form.folder'}.'/'.$fname;
1621: return &process_coursefile('uploaddoc',$docuname,$docudom,
1622: $fname,$formname,$parser,
1623: $allfiles,$codebase);
1624: }
1625: } elsif (defined($destuname)) {
1626: my $docuname=$destuname;
1627: my $docudom=$destudom;
1628: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1629: $parser,$allfiles,$codebase,
1630: $thumbwidth,$thumbheight);
1631:
1632: } else {
1633: my $docuname=$env{'user.name'};
1634: my $docudom=$env{'user.domain'};
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: }
1639: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1640: $parser,$allfiles,$codebase,
1641: $thumbwidth,$thumbheight);
1642: }
1643: }
1644:
1645: sub finishuserfileupload {
1646: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1647: $thumbwidth,$thumbheight) = @_;
1648: my $path=$docudom.'/'.$docuname.'/';
1649: my $filepath=$perlvar{'lonDocRoot'};
1650: my ($fnamepath,$file,$fetchthumb);
1651: $file=$fname;
1652: if ($fname=~m|/|) {
1653: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1654: $path.=$fnamepath.'/';
1655: }
1656: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
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: {
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: }
1676: close(FH);
1677: }
1678: if ($parser eq 'parse') {
1679: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1680: $codebase);
1681: unless ($parse_result eq 'ok') {
1682: &logthis('Failed to parse '.$filepath.$file.
1683: ' for embedded media: '.$parse_result);
1684: }
1685: }
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: }
1695:
1696: # Notify homeserver to grep it
1697: #
1698: my $docuhome=&homeserver($docuname,$docudom);
1699: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1700: if ($fetchresult eq 'ok') {
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: }
1708: #
1709: # Return the URL to it
1710: return '/uploaded/'.$path.$file;
1711: } else {
1712: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1713: ': '.$fetchresult);
1714: return '/adm/notfound.html';
1715: }
1716: }
1717:
1718: sub extract_embedded_items {
1719: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1720: my @state = ();
1721: my %javafiles = (
1722: codebase => '',
1723: code => '',
1724: archive => ''
1725: );
1726: my %mediafiles = (
1727: src => '',
1728: movie => '',
1729: );
1730: my $p;
1731: if ($content) {
1732: $p = HTML::LCParser->new($content);
1733: } else {
1734: $p = HTML::LCParser->new($filepath.'/'.$file);
1735: }
1736: while (my $t=$p->get_token()) {
1737: if ($t->[0] eq 'S') {
1738: my ($tagname, $attr) = ($t->[1],$t->[2]);
1739: push (@state, $tagname);
1740: if (lc($tagname) eq 'allow') {
1741: &add_filetype($allfiles,$attr->{'src'},'src');
1742: }
1743: if (lc($tagname) eq 'img') {
1744: &add_filetype($allfiles,$attr->{'src'},'src');
1745: }
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: }
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: }
1812: return 'ok';
1813: }
1814:
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));
1823: }
1824: }
1825:
1826: sub removeuploadedurl {
1827: my ($url)=@_;
1828: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1829: return &removeuserfile($uname,$udom,$fname);
1830: }
1831:
1832: sub removeuserfile {
1833: my ($docuname,$docudom,$fname)=@_;
1834: my $home=&homeserver($docuname,$docudom);
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);
1840: my $url = "/uploaded/$docudom/$docuname/$fname";
1841: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1842: my $sqlresult =
1843: &update_portfolio_table($docuname,$docudom,$file,
1844: 'portfolio_metadata',$group,
1845: 'delete');
1846: }
1847: }
1848: return $result;
1849: }
1850:
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:
1857: sub renameuserfile {
1858: my ($docuname,$docudom,$old,$new)=@_;
1859: my $home=&homeserver($docuname,$docudom);
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);
1868: my $url = "/uploaded/$docudom/$docuname/$old";
1869: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1870: my $sqlresult =
1871: &update_portfolio_table($docuname,$docudom,$file,
1872: 'portfolio_metadata',$group,
1873: 'delete');
1874: }
1875: }
1876: return $result;
1877: }
1878:
1879: # ------------------------------------------------------------------------- Log
1880:
1881: sub log {
1882: my ($dom,$nam,$hom,$what)=@_;
1883: return critical("log:$dom:$nam:$what",$hom);
1884: }
1885:
1886: # ------------------------------------------------------------------ Course Log
1887: #
1888: # This routine flushes several buffers of non-mission-critical nature
1889: #
1890:
1891: sub flushcourselogs {
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=();
1902: foreach my $crsid (keys %courselogs) {
1903: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1904: &escape($courselogs{$crsid}),
1905: $coursehombuf{$crsid}) eq 'ok') {
1906: delete $courselogs{$crsid};
1907: } else {
1908: &logthis('Failed to flush log buffer for '.$crsid);
1909: if (length($courselogs{$crsid})>40000) {
1910: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1911: " exceeded maximum size, deleting.</font>");
1912: delete $courselogs{$crsid};
1913: }
1914: }
1915: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1916: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1917: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1918: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1919: } else {
1920: $courseidbuffer{$coursehombuf{$crsid}}=
1921: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1922: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1923: }
1924: }
1925: #
1926: # Write course id database (reverse lookup) to homeserver of courses
1927: # Is used in pickcourse
1928: #
1929: foreach my $crs_home (keys(%courseidbuffer)) {
1930: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1931: $crs_home);
1932: }
1933: #
1934: # File accesses
1935: # Writes to the dynamic metadata of resources to get hit counts, etc.
1936: #
1937: foreach my $entry (keys(%accesshash)) {
1938: if ($entry =~ /___count$/) {
1939: my ($dom,$name);
1940: ($dom,$name,undef)=
1941: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1942: if (! defined($dom) || $dom eq '' ||
1943: ! defined($name) || $name eq '') {
1944: my $cid = $env{'request.course.id'};
1945: $dom = $env{'request.'.$cid.'.domain'};
1946: $name = $env{'request.'.$cid.'.num'};
1947: }
1948: my $value = $accesshash{$entry};
1949: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1950: my %temphash=($url => $value);
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.
1956: my %temphash=($entry => $value);
1957: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1958: delete $accesshash{$entry};
1959: }
1960: }
1961: } else {
1962: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1963: my %temphash=($entry => $accesshash{$entry});
1964: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1965: delete $accesshash{$entry};
1966: }
1967: }
1968: }
1969: #
1970: # Roles
1971: # Reverse lookup of user roles for course faculty/staff and co-authorship
1972: #
1973: foreach my $entry (keys(%userrolehash)) {
1974: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1975: split(/\:/,$entry);
1976: if (&Apache::lonnet::put('nohist_userroles',
1977: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1978: $rudom,$runame) eq 'ok') {
1979: delete $userrolehash{$entry};
1980: }
1981: }
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)) {
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: }
2004: }
2005: }
2006: $dumpcount++;
2007: }
2008:
2009: sub courselog {
2010: my $what=shift;
2011: $what=time.':'.$what;
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'};
2025: $coursetypebuf{$env{'request.course.id'}}=
2026: $env{'course.'.$env{'request.course.id'}.'.type'};
2027: if (defined $courselogs{$env{'request.course.id'}}) {
2028: $courselogs{$env{'request.course.id'}}.='&'.$what;
2029: } else {
2030: $courselogs{$env{'request.course.id'}}.=$what;
2031: }
2032: if (length($courselogs{$env{'request.course.id'}})>4048) {
2033: &flushcourselogs();
2034: }
2035: }
2036:
2037: sub courseacclog {
2038: my $fnsymb=shift;
2039: unless ($env{'request.course.id'}) { return ''; }
2040: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2041: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2042: $what.=':POST';
2043: # FIXME: Probably ought to escape things....
2044: foreach my $key (keys(%env)) {
2045: if ($key=~/^form\.(.*)/) {
2046: $what.=':'.$1.'='.$env{$key};
2047: }
2048: }
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.
2052: if ($env{'form.phase'} eq 'course_search') {
2053: $what.= ':POST';
2054: # FIXME: Probably ought to escape things....
2055: foreach my $element ('courseexp','crsfulltext','crsrelated',
2056: 'crsdiscuss') {
2057: $what.=':'.$element.'='.$env{'form.'.$element};
2058: }
2059: }
2060: }
2061: &courselog($what);
2062: }
2063:
2064: sub countacc {
2065: my $url=&declutter(shift);
2066: return if (! defined($url) || $url eq '');
2067: unless ($env{'request.course.id'}) { return ''; }
2068: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2069: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2070: $accesshash{$key}++;
2071: }
2072:
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:
2081: sub userrolelog {
2082: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2083: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2084: ($trole=~/^in/) || ($trole=~/^cc/) ||
2085: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2086: ($trole=~/^ta/)) {
2087: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2088: $userrolehash
2089: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2090: =$tend.':'.$tstart;
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: }
2101: }
2102:
2103: sub get_course_adv_roles {
2104: my $cid=shift;
2105: $cid=$env{'request.course.id'} unless (defined($cid));
2106: my %coursehash=&coursedescription($cid);
2107: my %nothide=();
2108: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2109: $nothide{join(':',split(/[\@\:]/,$user))}=1;
2110: }
2111: my %returnhash=();
2112: my %dumphash=
2113: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2114: my $now=time;
2115: foreach my $entry (keys %dumphash) {
2116: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2117: if (($tstart) && ($tstart<0)) { next; }
2118: if (($tend) && ($tend<$now)) { next; }
2119: if (($tstart) && ($now<$tstart)) { next; }
2120: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2121: if ($username eq '' || $domain eq '') { next; }
2122: if ((&privileged($username,$domain)) &&
2123: (!$nothide{$username.':'.$domain})) { next; }
2124: if ($role eq 'cr') { next; }
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: }
2132: }
2133: return %returnhash;
2134: }
2135:
2136: sub get_my_roles {
2137: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
2138: unless (defined($uname)) { $uname=$env{'user.name'}; }
2139: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2140: my %dumphash;
2141: if ($context eq 'userroles') {
2142: %dumphash = &dump('roles',$udom,$uname);
2143: } else {
2144: %dumphash=
2145: &dump('nohist_userroles',$udom,$uname);
2146: }
2147: my %returnhash=();
2148: my $now=time;
2149: foreach my $entry (keys(%dumphash)) {
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: }
2156: if (($tstart) && ($tstart<0)) { next; }
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: }
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: }
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: }
2189: }
2190: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2191: }
2192: return %returnhash;
2193: }
2194:
2195: # ----------------------------------------------------- Frontpage Announcements
2196: #
2197: #
2198:
2199: sub postannounce {
2200: my ($server,$text)=@_;
2201: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2202: unless ($text=~/\w/) { $text=''; }
2203: return &reply('setannounce:'.&escape($text),$server);
2204: }
2205:
2206: sub getannounce {
2207:
2208: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2209: my $announcement='';
2210: while (my $line = <$fh>) { $announcement .= $line; }
2211: close($fh);
2212: if ($announcement=~/\w/) {
2213: return
2214: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2215: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2216: } else {
2217: return '';
2218: }
2219: } else {
2220: return '';
2221: }
2222: }
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 {
2234: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
2235: my %returnhash=();
2236: unless ($domfilter) { $domfilter=''; }
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)) {
2245: foreach my $line (
2246: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
2247: $sincefilter.':'.&escape($descfilter).':'.
2248: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
2249: $tryserver))) {
2250: my ($key,$value)=split(/\=/,$line,2);
2251: if (($key) && ($value)) {
2252: $returnhash{&unescape($key)}=$value;
2253: }
2254: }
2255: }
2256: }
2257: }
2258: return %returnhash;
2259: }
2260:
2261: # ---------------------------------------------------------- DC e-mail
2262:
2263: sub dcmailput {
2264: my ($domain,$msgid,$message,$server)=@_;
2265: my $status = &Apache::lonnet::critical(
2266: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2267: &escape($message),$server);
2268: return $status;
2269: }
2270:
2271: sub dcmaildump {
2272: my ($dom,$startdate,$enddate,$senders) = @_;
2273: my %returnhash=();
2274:
2275: if (defined(&domain($dom,'primary'))) {
2276: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2277: &escape($enddate).':';
2278: my @esc_senders=map { &escape($_)} @$senders;
2279: $cmd.=&escape(join('&',@esc_senders));
2280: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
2281: my ($key,$value) = split(/\=/,$line,2);
2282: if (($key) && ($value)) {
2283: $returnhash{&unescape($key)} = &unescape($value);
2284: }
2285: }
2286: }
2287: return %returnhash;
2288: }
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 = ();
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: }
2314: }
2315: return %personnel;
2316: }
2317:
2318: # ----------------------------------------------------------- Check out an item
2319:
2320: sub get_first_access {
2321: my ($type,$argsymb)=@_;
2322: my ($symb,$courseid,$udom,$uname)=&whichuser();
2323: if ($argsymb) { $symb=$argsymb; }
2324: my ($map,$id,$res)=&decode_symb($symb);
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"};
2332: }
2333:
2334: sub set_first_access {
2335: my ($type)=@_;
2336: my ($symb,$courseid,$udom,$uname)=&whichuser();
2337: my ($map,$id,$res)=&decode_symb($symb);
2338: if ($type eq 'map') {
2339: $res=&symbread($map);
2340: } else {
2341: $res=$symb;
2342: }
2343: my $firstaccess=&get_first_access($type,$symb);
2344: if (!$firstaccess) {
2345: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2346: }
2347: return 'already_set';
2348: }
2349:
2350: sub checkout {
2351: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2352: my $now=time;
2353: my $lonhost=$perlvar{'lonHostID'};
2354: my $infostr=&escape(
2355: 'CHECKOUTTOKEN&'.
2356: $tuname.'&'.
2357: $tudom.'&'.
2358: $tcrsid.'&'.
2359: $symb.'&'.
2360: $now.'&'.$ENV{'REMOTE_ADDR'});
2361: my $token=&reply('tmpput:'.$infostr,$lonhost);
2362: if ($token=~/^error\:/) {
2363: &logthis("<font color=\"blue\">WARNING: ".
2364: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2365: "</font>");
2366: return '';
2367: }
2368:
2369: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2370: $token=~tr/a-z/A-Z/;
2371:
2372: my %infohash=('resource.0.outtoken' => $token,
2373: 'resource.0.checkouttime' => $now,
2374: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2375:
2376: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2377: return '';
2378: } else {
2379: &logthis("<font color=\"blue\">WARNING: ".
2380: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2381: "</font>");
2382: }
2383:
2384: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2385: &escape('Checkout '.$infostr.' - '.
2386: $token)) ne 'ok') {
2387: return '';
2388: } else {
2389: &logthis("<font color=\"blue\">WARNING: ".
2390: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2391: "</font>");
2392: }
2393: return $token;
2394: }
2395:
2396: # ------------------------------------------------------------ Check in an item
2397:
2398: sub checkin {
2399: my $token=shift;
2400: my $now=time;
2401: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2402: $lonhost=~tr/A-Z/a-z/;
2403: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
2404: $dtoken=~s/\W/\_/g;
2405: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2406: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2407:
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: '.
2415: $env{'user.name'}.' - '.$env{'user.domain'});
2416: return '';
2417: }
2418:
2419: my %infohash=('resource.0.intoken' => $token,
2420: 'resource.0.checkintime' => $now,
2421: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
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);
2433: }
2434:
2435: # --------------------------------------------- Set Expire Date for Spreadsheet
2436:
2437: sub expirespread {
2438: my ($uname,$udom,$stype,$usymb)=@_;
2439: my $cid=$env{'request.course.id'};
2440: if ($cid) {
2441: my $now=time;
2442: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2443: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2444: $env{'course.'.$cid.'.num'}.
2445: ':nohist_expirationdates:'.
2446: &escape($key).'='.$now,
2447: $env{'course.'.$cid.'.home'})
2448: }
2449: return 'ok';
2450: }
2451:
2452: # ----------------------------------------------------- Devalidate Spreadsheets
2453:
2454: sub devalidate {
2455: my ($symb,$uname,$udom)=@_;
2456: my $cid=$env{'request.course.id'};
2457: if ($cid) {
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
2462: # - current conditional state info
2463: my $key=$uname.':'.$udom.':';
2464: my $status=
2465: &del('nohist_calculatedsheets',
2466: [$key.'studentcalc:'],
2467: $env{'course.'.$cid.'.domain'},
2468: $env{'course.'.$cid.'.num'})
2469: .' '.
2470: &del('nohist_calculatedsheets_'.$cid,
2471: [$key.'assesscalc:'.$symb],$udom,$uname);
2472: unless ($status eq 'ok ok') {
2473: &logthis('Could not devalidate spreadsheet '.
2474: $uname.' at '.$udom.' for '.
2475: $symb.': '.$status);
2476: }
2477: &delenv('user.state.'.$cid);
2478: }
2479: }
2480:
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:
2500: sub arrayref2str {
2501: my ($arrayref) = @_;
2502: my $result='__ARRAY_REF__';
2503: foreach my $elem (@$arrayref) {
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.");
2510: } else {
2511: $result.=&escape($elem).'&';
2512: }
2513: }
2514: $result=~s/\&$//;
2515: $result .= '__END_ARRAY_REF__';
2516: return $result;
2517: }
2518:
2519: sub hash2str {
2520: my (%hash) = @_;
2521: my $result=&hashref2str(\%hash);
2522: $result=~s/^__HASH_REF__//;
2523: $result=~s/__END_HASH_REF__$//;
2524: return $result;
2525: }
2526:
2527: sub hashref2str {
2528: my ($hashref)=@_;
2529: my $result='__HASH_REF__';
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)) {
2536: $result.='=';
2537: #print("Got a ref of ".(ref($key))." skipping.");
2538: } else {
2539: if ($key) {$result.=&escape($key).'=';} else { last; }
2540: }
2541:
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})) {
2547: $result.='&';
2548: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
2549: } else {
2550: $result.=&escape($hashref->{$key}).'&';
2551: }
2552: }
2553: $result=~s/\&$//;
2554: $result .= '__END_HASH_REF__';
2555: return $result;
2556: }
2557:
2558: sub str2hash {
2559: my ($string)=@_;
2560: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2561: return %$hash;
2562: }
2563:
2564: sub str2hashref {
2565: my ($string) = @_;
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/^(.*?)=//;
2595: $key=&unescape($1);
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;
2619: }
2620:
2621: $string =~ s/^__END_HASH_REF__//;
2622:
2623: return (\%hash, $string);
2624: }
2625:
2626: sub str2array {
2627: my ($string)=@_;
2628: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2629: return @$array;
2630: }
2631:
2632: sub str2arrayref {
2633: my ($string) = @_;
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);
2665: }
2666:
2667: $string =~ s/^__END_ARRAY_REF__//;
2668:
2669: return (\@array, $string);
2670: }
2671:
2672: # -------------------------------------------------------------------Temp Store
2673:
2674: sub tmpreset {
2675: my ($symb,$namespace,$domain,$stuname) = @_;
2676: if (!$symb) {
2677: $symb=&symbread();
2678: if (!$symb) { $symb= $env{'request.url'}; }
2679: }
2680: $symb=escape($symb);
2681:
2682: if (!$namespace) { $namespace=$env{'request.state'}; }
2683: $namespace=~s/\//\_/g;
2684: $namespace=~s/\W//g;
2685:
2686: if (!$domain) { $domain=$env{'user.domain'}; }
2687: if (!$stuname) { $stuname=$env{'user.name'}; }
2688: if ($domain eq 'public' && $stuname eq 'public') {
2689: $stuname=$ENV{'REMOTE_ADDR'};
2690: }
2691: my $path=$perlvar{'lonDaemons'}.'/tmp';
2692: my %hash;
2693: if (tie(%hash,'GDBM_File',
2694: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2695: &GDBM_WRCREAT(),0640)) {
2696: foreach my $key (keys %hash) {
2697: if ($key=~ /:$symb/) {
2698: delete($hash{$key});
2699: }
2700: }
2701: }
2702: }
2703:
2704: sub tmpstore {
2705: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2706:
2707: if (!$symb) {
2708: $symb=&symbread();
2709: if (!$symb) { $symb= $env{'request.url'}; }
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.
2716: #$namespace=$env{'request.course.id'};
2717: #if (!$namespace) {
2718: $namespace=$env{'request.state'};
2719: #}
2720: }
2721: $namespace=~s/\//\_/g;
2722: $namespace=~s/\W//g;
2723: if (!$domain) { $domain=$env{'user.domain'}; }
2724: if (!$stuname) { $stuname=$env{'user.name'}; }
2725: if ($domain eq 'public' && $stuname eq 'public') {
2726: $stuname=$ENV{'REMOTE_ADDR'};
2727: }
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',
2733: &GDBM_WRCREAT(),0640)) {
2734: $hash{"version:$symb"}++;
2735: my $version=$hash{"version:$symb"};
2736: my $allkeys='';
2737: foreach my $key (keys(%$storehash)) {
2738: $allkeys.=$key.':';
2739: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
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: }
2753:
2754: # -----------------------------------------------------------------Temp Restore
2755:
2756: sub tmprestore {
2757: my ($symb,$namespace,$domain,$stuname) = @_;
2758:
2759: if (!$symb) {
2760: $symb=&symbread();
2761: if (!$symb) { $symb= $env{'request.url'}; }
2762: }
2763: $symb=escape($symb);
2764:
2765: if (!$namespace) { $namespace=$env{'request.state'}; }
2766:
2767: if (!$domain) { $domain=$env{'user.domain'}; }
2768: if (!$stuname) { $stuname=$env{'user.name'}; }
2769: if ($domain eq 'public' && $stuname eq 'public') {
2770: $stuname=$ENV{'REMOTE_ADDR'};
2771: }
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',
2779: &GDBM_READER(),0640)) {
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) {
2789: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2790: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2791: }
2792: }
2793: if (!(untie(%hash))) {
2794: return "error:$!";
2795: }
2796: } else {
2797: return "error:$!";
2798: }
2799: return %returnhash;
2800: }
2801:
2802: # ----------------------------------------------------------------------- Store
2803:
2804: sub store {
2805: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2806: my $home='';
2807:
2808: if ($stuname) { $home=&homeserver($stuname,$domain); }
2809:
2810: $symb=&symbclean($symb);
2811: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2812:
2813: if (!$domain) { $domain=$env{'user.domain'}; }
2814: if (!$stuname) { $stuname=$env{'user.name'}; }
2815:
2816: &devalidate($symb,$stuname,$domain);
2817:
2818: $symb=escape($symb);
2819: if (!$namespace) {
2820: unless ($namespace=$env{'request.course.id'}) {
2821: return '';
2822: }
2823: }
2824: if (!$home) { $home=$env{'user.home'}; }
2825:
2826: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2827: $$storehash{'host'}=$perlvar{'lonHostID'};
2828:
2829: my $namevalue='';
2830: foreach my $key (keys(%$storehash)) {
2831: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2832: }
2833: $namevalue=~s/\&$//;
2834: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2835: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2836: }
2837:
2838: # -------------------------------------------------------------- Critical Store
2839:
2840: sub cstore {
2841: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2842: my $home='';
2843:
2844: if ($stuname) { $home=&homeserver($stuname,$domain); }
2845:
2846: $symb=&symbclean($symb);
2847: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2848:
2849: if (!$domain) { $domain=$env{'user.domain'}; }
2850: if (!$stuname) { $stuname=$env{'user.name'}; }
2851:
2852: &devalidate($symb,$stuname,$domain);
2853:
2854: $symb=escape($symb);
2855: if (!$namespace) {
2856: unless ($namespace=$env{'request.course.id'}) {
2857: return '';
2858: }
2859: }
2860: if (!$home) { $home=$env{'user.home'}; }
2861:
2862: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2863: $$storehash{'host'}=$perlvar{'lonHostID'};
2864:
2865: my $namevalue='';
2866: foreach my $key (keys(%$storehash)) {
2867: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2868: }
2869: $namevalue=~s/\&$//;
2870: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2871: return critical
2872: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2873: }
2874:
2875: # --------------------------------------------------------------------- Restore
2876:
2877: sub restore {
2878: my ($symb,$namespace,$domain,$stuname) = @_;
2879: my $home='';
2880:
2881: if ($stuname) { $home=&homeserver($stuname,$domain); }
2882:
2883: if (!$symb) {
2884: unless ($symb=escape(&symbread())) { return ''; }
2885: } else {
2886: $symb=&escape(&symbclean($symb));
2887: }
2888: if (!$namespace) {
2889: unless ($namespace=$env{'request.course.id'}) {
2890: return '';
2891: }
2892: }
2893: if (!$domain) { $domain=$env{'user.domain'}; }
2894: if (!$stuname) { $stuname=$env{'user.name'}; }
2895: if (!$home) { $home=$env{'user.home'}; }
2896: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2897:
2898: my %returnhash=();
2899: foreach my $line (split(/\&/,$answer)) {
2900: my ($name,$value)=split(/\=/,$line);
2901: $returnhash{&unescape($name)}=&thaw_unescape($value);
2902: }
2903: my $version;
2904: for ($version=1;$version<=$returnhash{'version'};$version++) {
2905: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2906: $returnhash{$item}=$returnhash{$version.':'.$item};
2907: }
2908: }
2909: return %returnhash;
2910: }
2911:
2912: # ---------------------------------------------------------- Course Description
2913:
2914: sub coursedescription {
2915: my ($courseid,$args)=@_;
2916: $courseid=~s/^\///;
2917: $courseid=~s/\_/\//g;
2918: my ($cdomain,$cnum)=split(/\//,$courseid);
2919: my $chome=&homeserver($cnum,$cdomain);
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=();
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: }
2946:
2947: if ($chome ne 'no_host') {
2948: %returnhash=&dump('environment',$cdomain,$cnum);
2949: if (!exists($returnhash{'con_lost'})) {
2950: $returnhash{'home'}= $chome;
2951: $returnhash{'domain'} = $cdomain;
2952: $returnhash{'num'} = $cnum;
2953: if (!defined($returnhash{'type'})) {
2954: $returnhash{'type'} = 'Course';
2955: }
2956: while (my ($name,$value) = each %returnhash) {
2957: $envhash{'course.'.$normalid.'.'.$name}=$value;
2958: }
2959: $returnhash{'url'}=&clutter($returnhash{'url'});
2960: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2961: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2962: $envhash{'course.'.$normalid.'.home'}=$chome;
2963: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2964: $envhash{'course.'.$normalid.'.num'}=$cnum;
2965: }
2966: }
2967: if (!$args->{'one_time'}) {
2968: &appenv(%envhash);
2969: }
2970: return %returnhash;
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 '') {
2982: foreach my $entry (split(/&/,$rolesdump)) {
2983: if ($entry!~/^rolesdef_/) {
2984: my ($area,$role)=split(/=/,$entry);
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;
3001: }
3002:
3003: # -------------------------------------------------------- Get user privileges
3004:
3005: sub rolesinit {
3006: my ($domain,$username,$authhost)=@_;
3007: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3008: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
3009: my %allroles=();
3010: my %allgroups=();
3011: my $now=time;
3012: my %userroles = ('user.login.time' => $now);
3013: my $group_privs;
3014:
3015: if ($rolesdump ne '') {
3016: foreach my $entry (split(/&/,$rolesdump)) {
3017: if ($entry!~/^rolesdef_/) {
3018: my ($area,$role)=split(/=/,$entry);
3019: $area=~s/\_\w\w$//;
3020: my ($trole,$tend,$tstart,$group_privs);
3021: if ($role=~/^cr/) {
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]+)_(.*)$|);
3024: ($tend,$tstart)=split('_',$trest);
3025: } else {
3026: $trole=$role;
3027: }
3028: } elsif ($role =~ m|^gr/|) {
3029: ($trole,$tend,$tstart) = split(/_/,$role);
3030: ($trole,$group_privs) = split(/\//,$trole);
3031: $group_privs = &unescape($group_privs);
3032: } else {
3033: ($trole,$tend,$tstart)=split(/_/,$role);
3034: }
3035: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3036: $username);
3037: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3038: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3039: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3040: if (($area ne '') && ($trole ne '')) {
3041: my $spec=$trole.'.'.$area;
3042: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3043: if ($trole =~ /^cr\//) {
3044: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3045: } elsif ($trole eq 'gr') {
3046: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3047: } else {
3048: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3049: }
3050: }
3051: }
3052: }
3053: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3054: $userroles{'user.adv'} = $adv;
3055: $userroles{'user.author'} = $author;
3056: $env{'user.adv'}=$adv;
3057: }
3058: return \%userroles;
3059: }
3060:
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);
3065: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
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);
3072: if (&hostname($homsvr) ne '') {
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:
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) {
3102: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3103: $$allgroups{$course}{$group} .=':'.$group_privs;
3104: }
3105: }
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 {
3126: my ($userroles,$allroles,$allgroups) = @_;
3127: my $author=0;
3128: my $adv=0;
3129: my %grouproles = ();
3130: if (keys(%{$allgroups}) > 0) {
3131: foreach my $role (keys %{$allroles}) {
3132: my ($trole,$area,$sec,$extendedarea);
3133: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
3134: $trole = $1;
3135: $area = $2;
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};
3143: }
3144: }
3145: }
3146: }
3147: }
3148: foreach my $group (keys(%grouproles)) {
3149: $$allroles{$group} = $grouproles{$group};
3150: }
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);
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='';
3166: foreach my $priv (keys(%thesepriv)) {
3167: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3168: }
3169: $userroles->{'user.priv.'.$role} = $thesestr;
3170: }
3171: return ($author,$adv);
3172: }
3173:
3174: # --------------------------------------------------------------- get interface
3175:
3176: sub get {
3177: my ($namespace,$storearr,$udomain,$uname)=@_;
3178: my $items='';
3179: foreach my $item (@$storearr) {
3180: $items.=&escape($item).'&';
3181: }
3182: $items=~s/\&$//;
3183: if (!$udomain) { $udomain=$env{'user.domain'}; }
3184: if (!$uname) { $uname=$env{'user.name'}; }
3185: my $uhome=&homeserver($uname,$udomain);
3186:
3187: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
3188: my @pairs=split(/\&/,$rep);
3189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3190: return @pairs;
3191: }
3192: my %returnhash=();
3193: my $i=0;
3194: foreach my $item (@$storearr) {
3195: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3196: $i++;
3197: }
3198: return %returnhash;
3199: }
3200:
3201: # --------------------------------------------------------------- del interface
3202:
3203: sub del {
3204: my ($namespace,$storearr,$udomain,$uname)=@_;
3205: my $items='';
3206: foreach my $item (@$storearr) {
3207: $items.=&escape($item).'&';
3208: }
3209: $items=~s/\&$//;
3210: if (!$udomain) { $udomain=$env{'user.domain'}; }
3211: if (!$uname) { $uname=$env{'user.name'}; }
3212: my $uhome=&homeserver($uname,$udomain);
3213:
3214: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3215: }
3216:
3217: # -------------------------------------------------------------- dump interface
3218:
3219: sub dump {
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;
3239: }
3240:
3241: # --------------------------------------------------------- dumpstore interface
3242:
3243: sub dumpstore {
3244: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
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;
3262: }
3263:
3264: # -------------------------------------------------------------- keys interface
3265:
3266: sub getkeys {
3267: my ($namespace,$udomain,$uname)=@_;
3268: if (!$udomain) { $udomain=$env{'user.domain'}; }
3269: if (!$uname) { $uname=$env{'user.name'}; }
3270: my $uhome=&homeserver($uname,$udomain);
3271: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3272: my @keyarray=();
3273: foreach my $key (split(/\&/,$rep)) {
3274: next if ($key =~ /^error: 2 /);
3275: push(@keyarray,&unescape($key));
3276: }
3277: return @keyarray;
3278: }
3279:
3280: # --------------------------------------------------------------- currentdump
3281: sub currentdump {
3282: my ($courseid,$sdom,$sname)=@_;
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));
3286: my $uhome = &homeserver($sname,$sdom);
3287: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3288: return if ($rep =~ /^(error:|no_such_host)/);
3289: #
3290: my %returnhash=();
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
3295: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
3296: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3297: my %hash = @tmp;
3298: @tmp=();
3299: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3300: } else {
3301: my @pairs=split(/\&/,$rep);
3302: foreach my $pair (@pairs) {
3303: my ($key,$value)=split(/=/,$pair,2);
3304: my ($symb,$param) = split(/:/,$key);
3305: $returnhash{&unescape($symb)}->{&unescape($param)} =
3306: &thaw_unescape($value);
3307: }
3308: }
3309: return %returnhash;
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);
3320: $symb = &unescape($symb);
3321: $param = &unescape($param);
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;
3339: }
3340:
3341: # ------------------------------------------------------ critical inc interface
3342:
3343: sub cinc {
3344: return &inc(@_,'critical');
3345: }
3346:
3347: # --------------------------------------------------------------- inc interface
3348:
3349: sub inc {
3350: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3351: if (!$udomain) { $udomain=$env{'user.domain'}; }
3352: if (!$uname) { $uname=$env{'user.name'}; }
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/\&$//;
3368: if ($critical) {
3369: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3370: } else {
3371: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3372: }
3373: }
3374:
3375: # --------------------------------------------------------------- put interface
3376:
3377: sub put {
3378: my ($namespace,$storehash,$udomain,$uname)=@_;
3379: if (!$udomain) { $udomain=$env{'user.domain'}; }
3380: if (!$uname) { $uname=$env{'user.name'}; }
3381: my $uhome=&homeserver($uname,$udomain);
3382: my $items='';
3383: foreach my $item (keys(%$storehash)) {
3384: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3385: }
3386: $items=~s/\&$//;
3387: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3388: }
3389:
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:
3407: sub putstore {
3408: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3409: if (!$udomain) { $udomain=$env{'user.domain'}; }
3410: if (!$uname) { $uname=$env{'user.name'}; }
3411: my $uhome=&homeserver($uname,$udomain);
3412: my $items='';
3413: foreach my $key (keys(%$storehash)) {
3414: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3415: }
3416: $items=~s/\&$//;
3417: my $esc_symb=&escape($symb);
3418: my $esc_v=&escape($version);
3419: my $reply =
3420: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3421: $uhome);
3422: if ($reply eq 'unknown_cmd') {
3423: # gfall back to way things use to be done
3424: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3425: $uname);
3426: }
3427: return $reply;
3428: }
3429:
3430: sub old_putstore {
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;
3436: foreach my $item (keys(%$storehash)) {
3437: my $key = $version.':'.&escape($symb).':'.$item;
3438: $newstorehash{$key} = $storehash->{$item};
3439: }
3440: my $items='';
3441: my %allitems = ();
3442: foreach my $item (keys(%newstorehash)) {
3443: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3444: my $key = $1.':keys:'.$2;
3445: $allitems{$key} .= $3.':';
3446: }
3447: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
3448: }
3449: foreach my $item (keys(%allitems)) {
3450: $allitems{$item} =~ s/\:$//;
3451: $items.= $item.'='.$allitems{$item}.'&';
3452: }
3453: $items=~s/\&$//;
3454: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3455: }
3456:
3457: # ------------------------------------------------------ critical put interface
3458:
3459: sub cput {
3460: my ($namespace,$storehash,$udomain,$uname)=@_;
3461: if (!$udomain) { $udomain=$env{'user.domain'}; }
3462: if (!$uname) { $uname=$env{'user.name'}; }
3463: my $uhome=&homeserver($uname,$udomain);
3464: my $items='';
3465: foreach my $item (keys(%$storehash)) {
3466: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3467: }
3468: $items=~s/\&$//;
3469: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3470: }
3471:
3472: # -------------------------------------------------------------- eget interface
3473:
3474: sub eget {
3475: my ($namespace,$storearr,$udomain,$uname)=@_;
3476: my $items='';
3477: foreach my $item (@$storearr) {
3478: $items.=&escape($item).'&';
3479: }
3480: $items=~s/\&$//;
3481: if (!$udomain) { $udomain=$env{'user.domain'}; }
3482: if (!$uname) { $uname=$env{'user.name'}; }
3483: my $uhome=&homeserver($uname,$udomain);
3484: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3485: my @pairs=split(/\&/,$rep);
3486: my %returnhash=();
3487: my $i=0;
3488: foreach my $item (@$storearr) {
3489: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3490: $i++;
3491: }
3492: return %returnhash;
3493: }
3494:
3495: # ------------------------------------------------------------ tmpput interface
3496: sub tmpput {
3497: my ($storehash,$server,$context)=@_;
3498: my $items='';
3499: foreach my $item (keys(%$storehash)) {
3500: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3501: }
3502: $items=~s/\&$//;
3503: if (defined($context)) {
3504: $items .= ':'.&escape($context);
3505: }
3506: return &reply("tmpput:$items",$server);
3507: }
3508:
3509: # ------------------------------------------------------------ tmpget interface
3510: sub tmpget {
3511: my ($token,$server)=@_;
3512: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3513: my $rep=&reply("tmpget:$token",$server);
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:
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:
3529: # -------------------------------------------------- portfolio access checking
3530:
3531: sub portfolio_access {
3532: my ($requrl) = @_;
3533: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3534: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
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: }
3551: if ($result eq 'ok') {
3552: return 'F';
3553: } elsif ($result =~ /^[^:]+:guest_/) {
3554: return 'A';
3555: }
3556: return '';
3557: }
3558:
3559: sub get_portfolio_access {
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:
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) {
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: }
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) {
3633: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
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: }
3646: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
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:
3741: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
3742: $type = 1;
3743: $udom = $1;
3744: $unum = $2;
3745: $file_name = $3;
3746: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
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:
3764: sub is_portfolio_file {
3765: my ($file) = @_;
3766: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
3767: return 1;
3768: }
3769: return;
3770: }
3771:
3772:
3773: # ---------------------------------------------- Custom access rule evaluation
3774:
3775: sub customaccess {
3776: my ($priv,$uri)=@_;
3777: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
3778: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
3779: $udom = &LONCAPA::clean_domain($udom);
3780: $ucrs = &LONCAPA::clean_username($ucrs);
3781: my $access=0;
3782: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3783: my ($effect,$realm,$role)=split(/\:/,$right);
3784: if ($role) {
3785: if ($role ne $urole) { next; }
3786: }
3787: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3788: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
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;
3800: }
3801: if ($realm eq '' && $role eq '') {
3802: $access=($effect eq 'allow');
3803: }
3804: }
3805: return $access;
3806: }
3807:
3808: # ------------------------------------------------- Check for a user privilege
3809:
3810: sub allowed {
3811: my ($priv,$uri,$symb,$role)=@_;
3812: my $ver_orguri=$uri;
3813: $uri=&deversion($uri);
3814: my $orguri=$uri;
3815: $uri=&declutter($uri);
3816:
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:
3826: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3827: # Free bre access to adm and meta resources
3828: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
3829: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3830: && ($priv eq 'bre')) {
3831: return 'F';
3832: }
3833:
3834: # Free bre access to user's own portfolio contents
3835: my ($space,$domain,$name,@dir)=split('/',$uri);
3836: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3837: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
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: }
3846: }
3847:
3848: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
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;
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: }
3868: }
3869: }
3870: }
3871: }
3872:
3873: # Free bre to public access
3874:
3875: if ($priv eq 'bre') {
3876: my $copyright=&metadata($uri,'copyright');
3877: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3878: return 'F';
3879: }
3880: if ($copyright eq 'priv') {
3881: $uri=~/([^\/]+)\/([^\/]+)\//;
3882: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3883: return '';
3884: }
3885: }
3886: if ($copyright eq 'domain') {
3887: $uri=~/([^\/]+)\/([^\/]+)\//;
3888: unless (($env{'user.domain'} eq $1) ||
3889: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3890: return '';
3891: }
3892: }
3893: if ($env{'request.role'}=~ /li\.\//) {
3894: # Library role, so allow browsing of resources in this domain.
3895: return 'F';
3896: }
3897: if ($copyright eq 'custom') {
3898: unless (&customaccess($priv,$uri)) { return ''; }
3899: }
3900: }
3901: # Domain coordinator is trying to create a course
3902: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3903: # uri is the requested domain in this case.
3904: # comparison to 'request.role.domain' shows if the user has selected
3905: # a role of dc for the domain in question.
3906: return 'F' if ($uri eq $env{'request.role.domain'});
3907: }
3908:
3909: my $thisallowed='';
3910: my $statecond=0;
3911: my $courseprivid='';
3912:
3913: # Course
3914:
3915: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3916: $thisallowed.=$1;
3917: }
3918:
3919: # Domain
3920:
3921: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3922: =~/\Q$priv\E\&([^\:]*)/) {
3923: $thisallowed.=$1;
3924: }
3925:
3926: # Course: uri itself is a course
3927: my $courseuri=$uri;
3928: $courseuri=~s/\_(\d)/\/$1/;
3929: $courseuri=~s/^([^\/])/\/$1/;
3930:
3931: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3932: =~/\Q$priv\E\&([^\:]*)/) {
3933: $thisallowed.=$1;
3934: }
3935:
3936: # URI is an uploaded document for this course, default permissions don't matter
3937: # not allowing 'edit' access (editupload) to uploaded course docs
3938: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3939: $thisallowed='';
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 {
3947: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3948: if ($refuri) {
3949: if ($refuri =~ m|^/adm/|) {
3950: $thisallowed='F';
3951: } else {
3952: $refuri=&declutter($refuri);
3953: my ($match) = &is_on_map($refuri);
3954: if ($match) {
3955: $thisallowed='F';
3956: }
3957: }
3958: }
3959: }
3960: }
3961:
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:
3969: # Full access at system, domain or course-wide level? Exit.
3970:
3971: if ($thisallowed=~/F/) {
3972: return 'F';
3973: }
3974:
3975: # If this is generating or modifying users, exit with special codes
3976:
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')) {
3979: my ($audom,$auname)=split('/',$uri);
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
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: }
3987: return $thisallowed;
3988: }
3989: #
3990: # Gathered so far: system, domain and course wide privileges
3991: #
3992: # Course: See if uri or referer is an individual resource that is part of
3993: # the course
3994:
3995: if ($env{'request.course.id'}) {
3996:
3997: $courseprivid=$env{'request.course.id'};
3998: if ($env{'request.course.sec'}) {
3999: $courseprivid.='/'.$env{'request.course.sec'};
4000: }
4001: $courseprivid=~s/\_/\//;
4002: my $checkreferer=1;
4003: my ($match,$cond)=&is_on_map($uri);
4004: if ($match) {
4005: $statecond=$cond;
4006: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
4007: =~/\Q$priv\E\&([^\:]*)/) {
4008: $thisallowed.=$1;
4009: $checkreferer=0;
4010: }
4011: }
4012:
4013: if ($checkreferer) {
4014: my $refuri=$env{'httpref.'.$orguri};
4015: unless ($refuri) {
4016: foreach my $key (keys(%env)) {
4017: if ($key=~/^httpref\..*\*/) {
4018: my $pattern=$key;
4019: $pattern=~s/^httpref\.\/res\///;
4020: $pattern=~s/\*/\[\^\/\]\+/g;
4021: $pattern=~s/\//\\\//g;
4022: if ($orguri=~/$pattern/) {
4023: $refuri=$env{$key};
4024: }
4025: }
4026: }
4027: }
4028:
4029: if ($refuri) {
4030: $refuri=&declutter($refuri);
4031: my ($match,$cond)=&is_on_map($refuri);
4032: if ($match) {
4033: my $refstatecond=$cond;
4034: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
4035: =~/\Q$priv\E\&([^\:]*)/) {
4036: $thisallowed.=$1;
4037: $uri=$refuri;
4038: $statecond=$refstatecond;
4039: }
4040: }
4041: }
4042: }
4043: }
4044:
4045: #
4046: # Gathered now: all privileges that could apply, and condition number
4047: #
4048: #
4049: # Full or no access?
4050: #
4051:
4052: if ($thisallowed=~/F/) {
4053: return 'F';
4054: }
4055:
4056: unless ($thisallowed) {
4057: return '';
4058: }
4059:
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
4069: # Locks might take effect only after 10 minutes cache expiration for other
4070: # courses, and 2 minutes for current course
4071:
4072: my $envkey;
4073: if ($thisallowed=~/L/) {
4074: foreach $envkey (keys %env) {
4075: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4076: my $courseid=$2;
4077: my $roleid=$1.'.'.$2;
4078: $courseid=~s/^\///;
4079: my $expiretime=600;
4080: if ($env{'request.role'} eq $roleid) {
4081: $expiretime=120;
4082: }
4083: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4084: my $prefix='course.'.$cdom.'_'.$cnum.'.';
4085: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
4086: &coursedescription($courseid,{'freshen_cache' => 1});
4087: }
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'},
4093: 'Locked by res: '.$priv.' for '.$uri.' due to '.
4094: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4095: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4096: return '';
4097: }
4098: }
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'},
4104: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
4105: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4106: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4107: return '';
4108: }
4109: }
4110: }
4111: }
4112: }
4113:
4114: #
4115: # Rest of the restrictions depend on selected course
4116: #
4117:
4118: unless ($env{'request.course.id'}) {
4119: if ($thisallowed eq 'A') {
4120: return 'A';
4121: } elsif ($thisallowed eq 'B') {
4122: return 'B';
4123: } else {
4124: return '1';
4125: }
4126: }
4127:
4128: #
4129: # Now user is definitely in a course
4130: #
4131:
4132:
4133: # Course preferences
4134:
4135: if ($thisallowed=~/C/) {
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'}
4139: =~/\Q$rolecode\E/) {
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: }
4145: return '';
4146: }
4147:
4148: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
4149: =~/\Q$unamedom\E/) {
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: }
4155: return '';
4156: }
4157: }
4158:
4159: # Resource preferences
4160:
4161: if ($thisallowed=~/R/) {
4162: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4163: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
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 '';
4169: }
4170: }
4171:
4172: # Restricted by state or randomout?
4173:
4174: if ($thisallowed=~/X/) {
4175: if ($env{'acc.randomout'}) {
4176: if (!$symb) { $symb=&symbread($uri,1); }
4177: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
4178: return '';
4179: }
4180: }
4181: if (&condval($statecond)) {
4182: return '2';
4183: } else {
4184: return '';
4185: }
4186: }
4187:
4188: if ($thisallowed eq 'A') {
4189: return 'A';
4190: } elsif ($thisallowed eq 'B') {
4191: return 'B';
4192: }
4193: return 'F';
4194: }
4195:
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: }
4203: # --------------------------------------------------- Is a resource on the map?
4204:
4205: sub is_on_map {
4206: my ($pathname,$filename) = &split_uri_for_cond(shift);
4207: #Trying to find the conditional for the file
4208: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
4209: /\&\Q$filename\E\:([\d\|]+)\&/);
4210: if ($match) {
4211: return (1,$1);
4212: } else {
4213: return (0,0);
4214: }
4215: }
4216:
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;
4227: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
4228: &GDBM_READER(),0640)) {
4229: my $rid=$bighash{'mapalias_'.$symb};
4230: if ($rid) {
4231: my ($mapid,$resid)=split(/\./,$rid);
4232: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4233: $resid,$bighash{'src_'.$rid});
4234: }
4235: untie %bighash;
4236: }
4237: return $aliassymb;
4238: }
4239:
4240: # ----------------------------------------------------------------- Define Role
4241:
4242: sub definerole {
4243: if (allowed('mcr','/')) {
4244: my ($rolename,$sysrole,$domrole,$courole)=@_;
4245: foreach my $role (split(':',$sysrole)) {
4246: my ($crole,$cqual)=split(/\&/,$role);
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/) {
4250: return "refused:s:$crole&$cqual";
4251: }
4252: }
4253: }
4254: foreach my $role (split(':',$domrole)) {
4255: my ($crole,$cqual)=split(/\&/,$role);
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/) {
4259: return "refused:d:$crole&$cqual";
4260: }
4261: }
4262: }
4263: foreach my $role (split(':',$courole)) {
4264: my ($crole,$cqual)=split(/\&/,$role);
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/) {
4268: return "refused:c:$crole&$cqual";
4269: }
4270: }
4271: }
4272: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4273: "$env{'user.domain'}:$env{'user.name'}:".
4274: "rolesdef_$rolename=".
4275: escape($sysrole.'_'.$domrole.'_'.$courole);
4276: return reply($command,$env{'user.home'});
4277: } else {
4278: return 'refused';
4279: }
4280: }
4281:
4282: # ---------------- Make a metadata query against the network of library servers
4283:
4284: sub metadata_query {
4285: my ($query,$custom,$customshow,$server_array)=@_;
4286: my %rhash;
4287: my %libserv = &all_library();
4288: my @server_list = (defined($server_array) ? @$server_array
4289: : keys(%libserv) );
4290: for my $server (@server_list) {
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: }
4301: }
4302: return \%rhash;
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'; }
4311: my $uhost=&hostname($uhome);
4312: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
4313: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4314: $uhome);
4315: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
4316: return get_query_reply($queryid);
4317: }
4318:
4319: # -------------------------- Update MySQL table for portfolio file
4320:
4321: sub update_portfolio_table {
4322: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
4323: my $homeserver = &homeserver($uname,$udom);
4324: my $queryid=
4325: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4326: ':'.&escape($file_name).':'.$action,$homeserver);
4327: my $reply = &get_query_reply($queryid);
4328: return $reply;
4329: }
4330:
4331: # ------- Request retrieval of institutional classlists for course(s)
4332:
4333: sub fetch_enrollment_query {
4334: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
4335: my $homeserver;
4336: my $maxtries = 1;
4337: if ($context eq 'automated') {
4338: $homeserver = $perlvar{'lonHostID'};
4339: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
4340: } else {
4341: $homeserver = &homeserver($cnum,$dom);
4342: }
4343: my $host=&hostname($homeserver);
4344: my $cmd = '';
4345: foreach my $affiliate (keys %{$affiliatesref}) {
4346: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4347: }
4348: $cmd =~ s/%%$//;
4349: $cmd = &escape($cmd);
4350: my $query = 'fetchenrollment';
4351: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
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: }
4356: my $reply = &get_query_reply($queryid);
4357: my $tries = 1;
4358: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4359: $reply = &get_query_reply($queryid);
4360: $tries ++;
4361: }
4362: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4363: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4364: } else {
4365: my @responses = split/:/,$reply;
4366: if ($homeserver eq $perlvar{'lonHostID'}) {
4367: foreach my $line (@responses) {
4368: my ($key,$value) = split(/=/,$line,2);
4369: $$replyref{$key} = $value;
4370: }
4371: } else {
4372: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
4373: foreach my $line (@responses) {
4374: my ($key,$value) = split(/=/,$line);
4375: $$replyref{$key} = $value;
4376: if ($value > 0) {
4377: foreach my $item (@{$$affiliatesref{$key}}) {
4378: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
4379: my $destname = $pathname.'/'.$filename;
4380: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
4381: if ($xml_classlist =~ /^error/) {
4382: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4383: } else {
4384: if ( open(FILE,">$destname") ) {
4385: print FILE &unescape($xml_classlist);
4386: close(FILE);
4387: } else {
4388: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
4389: }
4390: }
4391: }
4392: }
4393: }
4394: }
4395: return 'ok';
4396: }
4397: return 'error';
4398: }
4399:
4400: sub get_query_reply {
4401: my $queryid=shift;
4402: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4403: my $reply='';
4404: for (1..100) {
4405: sleep 2;
4406: if (-e $replyfile.'.end') {
4407: if (open(my $fh,$replyfile)) {
4408: $reply.=<$fh>;
4409: close($fh);
4410: } else { return 'error: reply_file_error'; }
4411: return &unescape($reply);
4412: }
4413: }
4414: return 'timeout:'.$queryid;
4415: }
4416:
4417: sub courselog_query {
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: #
4427: my (%filters)=@_;
4428: unless ($env{'request.course.id'}) { return 'no_course'; }
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: }
4434: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4435: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4436: return &log_query($cname,$cdom,'courselog',%filters);
4437: }
4438:
4439: sub userlog_query {
4440: #
4441: # possible filters:
4442: # action: log check role
4443: # start: timestamp
4444: # end: timestamp
4445: #
4446: my ($uname,$udom,%filters)=@_;
4447: return &log_query($uname,$udom,'userlog',%filters);
4448: }
4449:
4450: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4451:
4452: sub auto_run {
4453: my ($cnum,$cdom) = @_;
4454: my $homeserver = &homeserver($cnum,$cdom);
4455: my $response = &reply('autorun:'.$cdom,$homeserver);
4456: return $response;
4457: }
4458:
4459: sub auto_get_sections {
4460: my ($cnum,$cdom,$inst_coursecode) = @_;
4461: my $homeserver = &homeserver($cnum,$cdom);
4462: my @secs = ();
4463: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
4464: unless ($response eq 'refused') {
4465: @secs = split/:/,$response;
4466: }
4467: return @secs;
4468: }
4469:
4470: sub auto_new_course {
4471: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4472: my $homeserver = &homeserver($cnum,$cdom);
4473: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
4474: return $response;
4475: }
4476:
4477: sub auto_validate_courseID {
4478: my ($cnum,$cdom,$inst_course_id) = @_;
4479: my $homeserver = &homeserver($cnum,$cdom);
4480: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
4481: return $response;
4482: }
4483:
4484: sub auto_create_password {
4485: my ($cnum,$cdom,$authparam) = @_;
4486: my $homeserver = &homeserver($cnum,$cdom);
4487: my $create_passwd = 0;
4488: my $authchk = '';
4489: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
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:
4498: sub auto_photo_permission {
4499: my ($cnum,$cdom,$students) = @_;
4500: my $homeserver = &homeserver($cnum,$cdom);
4501: my ($outcome,$perm_reqd,$conditions) =
4502: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
4503: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4504: return (undef,undef);
4505: }
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).':'.
4514: &escape($uname).':'.&escape($pid),
4515: $homeserver));
4516: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4517: return (undef,undef);
4518: }
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:'.
4529: &escape($cdom),
4530: $homeserver)));
4531: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4532: return (undef,undef);
4533: }
4534: return ($update,$comment);
4535: }
4536:
4537: sub auto_photoupdate {
4538: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4539: my $homeserver = &homeserver($cnum,$dom);
4540: my $host=&hostname($homeserver);
4541: my $cmd = '';
4542: my $maxtries = 1;
4543: foreach my $affiliate (keys(%{$affiliatesref})) {
4544: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
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:
4574: sub auto_instcode_format {
4575: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4576: $cat_order) = @_;
4577: my $courses = '';
4578: my @homeservers;
4579: if ($caller eq 'global') {
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: }
4585: }
4586: } else {
4587: push(@homeservers,&homeserver($caller,$codedom));
4588: }
4589: foreach my $code (keys(%{$instcodes})) {
4590: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
4591: }
4592: chop($courses);
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) =
4600: split/:/,$response;
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) {
4609: return 'ok';
4610: } else {
4611: return $response;
4612: }
4613: }
4614:
4615: sub auto_instcode_defaults {
4616: my ($domain,$returnhash,$code_order) = @_;
4617: my @homeservers;
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: }
4624: }
4625:
4626: my $response;
4627: foreach my $server (@homeservers) {
4628: $response=&reply('autoinstcodedefaults:'.$domain,$server);
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';
4640: }
4641:
4642: return $response;
4643: }
4644:
4645: sub auto_validate_class_sec {
4646: my ($cdom,$cnum,$owner,$inst_class) = @_;
4647: my $homeserver = &homeserver($cnum,$cdom);
4648: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
4649: &escape($owner).':'.$cdom,$homeserver);
4650: return $response;
4651: }
4652:
4653: # ------------------------------------------------------- Course Group routines
4654:
4655: sub get_coursegroups {
4656: my ($cdom,$cnum,$group,$namespace) = @_;
4657: return(&dump($namespace,$cdom,$cnum,$group));
4658: }
4659:
4660: sub modify_coursegroup {
4661: my ($cdom,$cnum,$groupsettings) = @_;
4662: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4663: }
4664:
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);
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;
4681: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
4682: my $deloutcome;
4683: if ($result eq 'ok') {
4684: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
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:
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);
4702: if ($result eq 'ok') {
4703: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4704: }
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:
4714: sub get_active_groups {
4715: my ($udom,$uname,$cdom,$cnum) = @_;
4716: my $now = time;
4717: my %groups = ();
4718: foreach my $key (keys(%env)) {
4719: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
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:
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) = @_;
4738: my @usersgroups;
4739: my $cachetime=1800;
4740:
4741: my $hashid="$udom:$uname:$courseid";
4742: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4743: if (defined($cached)) {
4744: @usersgroups = split(/:/,$grouplist);
4745: } else {
4746: $grouplist = '';
4747: my $courseurl = &courseid_to_courseurl($courseid);
4748: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
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);
4764: }
4765: }
4766: next;
4767: }
4768: push(@usersgroups,$group);
4769: }
4770: }
4771: }
4772: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4773: $grouplist = join(':',@usersgroups);
4774: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4775: }
4776: return @usersgroups;
4777: }
4778:
4779: sub devalidate_getgroups_cache {
4780: my ($udom,$uname,$cdom,$cnum)=@_;
4781: my $courseid = $cdom.'_'.$cnum;
4782:
4783: my $hashid="$udom:$uname:$courseid";
4784: &devalidate_cache_new('getgroups',$hashid);
4785: }
4786:
4787: # ------------------------------------------------------------------ Plain Text
4788:
4789: sub plaintext {
4790: my ($short,$type,$cid) = @_;
4791: if ($short =~ /^cr/) {
4792: return (split('/',$short))[-1];
4793: }
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: }
4812: }
4813:
4814: # ----------------------------------------------------------------- Assign Role
4815:
4816: sub assignrole {
4817: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4818: my $mrole;
4819: if ($role =~ /^cr\//) {
4820: my $cwosec=$url;
4821: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4822: unless (&allowed('ccr',$cwosec)) {
4823: &logthis('Refused custom assignrole: '.
4824: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4825: $env{'user.name'}.' at '.$env{'user.domain'});
4826: return 'refused';
4827: }
4828: $mrole='cr';
4829: } elsif ($role =~ /^gr\//) {
4830: my $cwogrp=$url;
4831: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
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';
4839: } else {
4840: my $cwosec=$url;
4841: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4842: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4843: &logthis('Refused assignrole: '.
4844: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4845: $env{'user.name'}.' at '.$env{'user.domain'});
4846: return 'refused';
4847: }
4848: $mrole=$role;
4849: }
4850: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4851: "$udom:$uname:$url".'_'."$mrole=$role";
4852: if ($end) { $command.='_'.$end; }
4853: if ($start) {
4854: if ($end) {
4855: $command.='_'.$start;
4856: } else {
4857: $command.='_0_'.$start;
4858: }
4859: }
4860: my $origstart = $start;
4861: my $origend = $end;
4862: # actually delete
4863: if ($deleteflag) {
4864: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4865: # modify command to delete the role
4866: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4867: "$udom:$uname:$url".'_'."$mrole";
4868: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4869: # set start and finish to negative values for userrolelog
4870: $start=-1;
4871: $end=-1;
4872: }
4873: }
4874: # send command
4875: my $answer=&reply($command,&homeserver($uname,$udom));
4876: # log new user role if status is ok
4877: if ($answer eq 'ok') {
4878: &userrolelog($role,$uname,$udom,$url,$start,$end);
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: }
4884: }
4885: return $answer;
4886: }
4887:
4888: # -------------------------------------------------- Modify user authentication
4889: # Overrides without validation
4890:
4891: sub modifyuserauth {
4892: my ($udom,$uname,$umode,$upass)=@_;
4893: my $uhome=&homeserver($uname,$udom);
4894: unless (&allowed('mau',$udom)) { return 'refused'; }
4895: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4896: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4897: ' in domain '.$env{'request.role.domain'});
4898: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4899: &escape($upass),$uhome);
4900: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4901: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4902: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4903: &log($udom,,$uname,$uhome,
4904: 'Authentication changed by '.$env{'user.domain'}.', '.
4905: $env{'user.name'}.', '.$umode.
4906: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4907: unless ($reply eq 'ok') {
4908: &logthis('Authentication mode error: '.$reply);
4909: return 'error: '.$reply;
4910: }
4911: return 'ok';
4912: }
4913:
4914: # --------------------------------------------------------------- Modify a user
4915:
4916: sub modifyuser {
4917: my ($udom, $uname, $uid,
4918: $umode, $upass, $first,
4919: $middle, $last, $gene,
4920: $forceid, $desiredhome, $email)=@_;
4921: $udom= &LONCAPA::clean_domain($udom);
4922: $uname=&LONCAPA::clean_username($uname);
4923: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4924: $umode.', '.$first.', '.$middle.', '.
4925: $last.', '.$gene.'(forceid: '.$forceid.')'.
4926: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4927: ' desiredhome not specified').
4928: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4929: ' in domain '.$env{'request.role.domain'});
4930: my $uhome=&homeserver($uname,$udom,'true');
4931: # ----------------------------------------------------------------- Create User
4932: if (($uhome eq 'no_host') &&
4933: (($umode && $upass) || ($umode eq 'localauth'))) {
4934: my $unhome='';
4935: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
4936: $unhome = $desiredhome;
4937: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4938: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4939: } else { # load balancing routine for determining $unhome
4940: my $loadm=10000000;
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: }
4948: }
4949: }
4950: if (($unhome eq '') || ($unhome eq 'no_host')) {
4951: return 'error: unable to find a home server for '.$uname.
4952: ' in domain '.$udom;
4953: }
4954: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4955: &escape($upass),$unhome);
4956: unless ($reply eq 'ok') {
4957: return 'error: '.$reply;
4958: }
4959: $uhome=&homeserver($uname,$udom,'true');
4960: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4961: return 'error: unable verify users home machine.';
4962: }
4963: } # End of creation of new user
4964: # ---------------------------------------------------------------------- Add ID
4965: if ($uid) {
4966: $uid=~tr/A-Z/a-z/;
4967: my %uidhash=&idrget($udom,$uname);
4968: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4969: && (!$forceid)) {
4970: unless ($uid eq $uidhash{$uname}) {
4971: return 'error: user id "'.$uid.'" does not match '.
4972: 'current user id "'.$uidhash{$uname}.'".';
4973: }
4974: } else {
4975: &idput($udom,($uname => $uid));
4976: }
4977: }
4978: # -------------------------------------------------------------- Add names, etc
4979: my @tmp=&get('environment',
4980: ['firstname','middlename','lastname','generation'],
4981: $udom,$uname);
4982: my %names;
4983: if ($tmp[0] =~ m/^error:.*/) {
4984: %names=();
4985: } else {
4986: %names = @tmp;
4987: }
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; }
4993: if (defined($middle)) { $names{'middlename'} = $middle; }
4994: if ($last) { $names{'lastname'} = $last; }
4995: if (defined($gene)) { $names{'generation'} = $gene; }
4996: if ($email) {
4997: $email=~s/[^\w\@\.\-\,]//gs;
4998: if ($email=~/\@/) { $names{'notification'} = $email;
4999: $names{'critnotification'} = $email;
5000: $names{'permanentemail'} = $email; }
5001: }
5002: my $reply = &put('environment', \%names, $udom,$uname);
5003: if ($reply ne 'ok') { return 'error: '.$reply; }
5004: &devalidate_cache_new('namescache',$uname.':'.$udom);
5005: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5006: $umode.', '.$first.', '.$middle.', '.
5007: $last.', '.$gene.' by '.
5008: $env{'user.name'}.' at '.$env{'user.domain'});
5009: return 'ok';
5010: }
5011:
5012: # -------------------------------------------------------------- Modify student
5013:
5014: sub modifystudent {
5015: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
5016: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
5017: if (!$cid) {
5018: unless ($cid=$env{'request.course.id'}) {
5019: return 'not_in_class';
5020: }
5021: }
5022: # --------------------------------------------------------------- Make the user
5023: my $reply=&modifyuser
5024: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
5025: $desiredhome,$email);
5026: unless ($reply eq 'ok') { return $reply; }
5027: # This will cause &modify_student_enrollment to get the uid from the
5028: # students environment
5029: $uid = undef if (!$forceid);
5030: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
5031: $gene,$usec,$end,$start,$type,$locktype,$cid);
5032: return $reply;
5033: }
5034:
5035: sub modify_student_enrollment {
5036: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
5037: my ($cdom,$cnum,$chome);
5038: if (!$cid) {
5039: unless ($cid=$env{'request.course.id'}) {
5040: return 'not_in_class';
5041: }
5042: $cdom=$env{'course.'.$cid.'.domain'};
5043: $cnum=$env{'course.'.$cid.'.num'};
5044: } else {
5045: ($cdom,$cnum)=split(/_/,$cid);
5046: }
5047: $chome=$env{'course.'.$cid.'.home'};
5048: if (!$chome) {
5049: $chome=&homeserver($cnum,$cdom);
5050: }
5051: if (!$chome) { return 'unknown_course'; }
5052: # Make sure the user exists
5053: my $uhome=&homeserver($uname,$udom);
5054: if (($uhome eq '') || ($uhome eq 'no_host')) {
5055: return 'error: no such user';
5056: }
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 '') {
5063: # They did not supply us with enough data to enroll the student, so
5064: # we need to pick up more information.
5065: my %tmp = &get('environment',
5066: ['firstname','middlename','lastname', 'generation','id']
5067: ,$udom,$uname);
5068:
5069: #foreach my $key (keys(%tmp)) {
5070: # &logthis("key $key = ".$tmp{$key});
5071: #}
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 '');
5075: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
5076: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5077: }
5078: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
5079: my $reply=cput('classlist',
5080: {"$uname:$udom" =>
5081: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
5082: $cdom,$cnum);
5083: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5084: return 'error: '.$reply;
5085: } else {
5086: &devalidate_getsection_cache($udom,$uname,$cid);
5087: }
5088: # Add student role to user
5089: my $uurl='/'.$cid;
5090: $uurl=~s/\_/\//g;
5091: if ($usec) {
5092: $uurl.='/'.$usec;
5093: }
5094: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
5095: }
5096:
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:
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='';
5128: foreach my $pref (keys(%prefs)) {
5129: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
5130: }
5131: $cstring=~s/\&$//;
5132: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5133: }
5134:
5135: # ---------------------------------------------------------- Make/modify course
5136:
5137: sub createcourse {
5138: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5139: $course_owner,$crstype)=@_;
5140: $url=&declutter($url);
5141: my $cid='';
5142: unless (&allowed('ccc',$udom)) {
5143: return 'refused';
5144: }
5145: # ------------------------------------------------------------------- Create ID
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)).
5149: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5150: # ----------------------------------------------- Make sure that does not exist
5151: my $uhome=&homeserver($uname,$udom,'true');
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'};
5155: $uhome=&homeserver($uname,$udom,'true');
5156: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5157: return 'error: unable to generate unique course-ID';
5158: }
5159: }
5160: # ------------------------------------------------ Check supplied server name
5161: $course_server = $env{'user.homeserver'} if (! defined($course_server));
5162: if (! &is_library($course_server)) {
5163: return 'error:bad server name '.$course_server;
5164: }
5165: # ------------------------------------------------------------- Make the course
5166: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
5167: $course_server);
5168: unless ($reply eq 'ok') { return 'error: '.$reply; }
5169: $uhome=&homeserver($uname,$udom,'true');
5170: if (($uhome eq '') || ($uhome eq 'no_host')) {
5171: return 'error: no such course';
5172: }
5173: # ----------------------------------------------------------------- Course made
5174: # log existence
5175: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
5176: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5177: &escape($crstype),$uhome);
5178: &flushcourselogs();
5179: # set toplevel url
5180: my $topurl=$url;
5181: unless ($nonstandard) {
5182: # ------------------------------------------ For standard courses, make top url
5183: my $mapurl=&clutter($url);
5184: if ($mapurl eq '/res/') { $mapurl=''; }
5185: $env{'form.initmap'}=(<<ENDINITMAP);
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(
5195: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
5196: );
5197: }
5198: # ----------------------------------------------------------- Write preferences
5199: &writecoursepref($udom.'_'.$uname,
5200: ('description' => $description,
5201: 'url' => $topurl));
5202: return '/'.$udom.'/'.$uname;
5203: }
5204:
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:
5215: # ---------------------------------------------------------- Assign Custom Role
5216:
5217: sub assigncustomrole {
5218: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
5219: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
5220: $end,$start,$deleteflag);
5221: }
5222:
5223: # ----------------------------------------------------------------- Revoke Role
5224:
5225: sub revokerole {
5226: my ($udom,$uname,$url,$role,$deleteflag)=@_;
5227: my $now=time;
5228: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
5229: }
5230:
5231: # ---------------------------------------------------------- Revoke Custom Role
5232:
5233: sub revokecustomrole {
5234: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
5235: my $now=time;
5236: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5237: $deleteflag);
5238: }
5239:
5240: # ------------------------------------------------------------ Disk usage
5241: sub diskusage {
5242: my ($udom,$uname,$directoryRoot)=@_;
5243: $directoryRoot =~ s/\/$//;
5244: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
5245: return $listing;
5246: }
5247:
5248: sub is_locked {
5249: my ($file_name, $domain, $user) = @_;
5250: my @check;
5251: my $is_locked;
5252: push @check, $file_name;
5253: my %locked = &get('file_permissions',\@check,
5254: $env{'user.domain'},$env{'user.name'});
5255: my ($tmp)=keys(%locked);
5256: if ($tmp=~/^error:/) { undef(%locked); }
5257:
5258: if (ref($locked{$file_name}) eq 'ARRAY') {
5259: $is_locked = 'false';
5260: foreach my $entry (@{$locked{$file_name}}) {
5261: if (ref($entry) eq 'ARRAY') {
5262: $is_locked = 'true';
5263: last;
5264: }
5265: }
5266: } else {
5267: $is_locked = 'false';
5268: }
5269: }
5270:
5271: sub declutter_portfile {
5272: my ($file) = @_;
5273: $file =~ s{^(/portfolio/|portfolio/)}{/};
5274: return $file;
5275: }
5276:
5277: # ------------------------------------------------------------- Mark as Read Only
5278:
5279: sub mark_as_readonly {
5280: my ($domain,$user,$files,$what) = @_;
5281: my %current_permissions = &dump('file_permissions',$domain,$user);
5282: my ($tmp)=keys(%current_permissions);
5283: if ($tmp=~/^error:/) { undef(%current_permissions); }
5284: foreach my $file (@{$files}) {
5285: $file = &declutter_portfile($file);
5286: push(@{$current_permissions{$file}},$what);
5287: }
5288: &put('file_permissions',\%current_permissions,$domain,$user);
5289: return;
5290: }
5291:
5292: # ------------------------------------------------------------Save Selected Files
5293:
5294: sub save_selected_files {
5295: my ($user, $path, @files) = @_;
5296: my $filename = $user."savedfiles";
5297: my @other_files = &files_not_in_path($user, $path);
5298: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5299: foreach my $file (@files) {
5300: print (OUT $env{'form.currentpath'}.$file."\n");
5301: }
5302: foreach my $file (@other_files) {
5303: print (OUT $file."\n");
5304: }
5305: close (OUT);
5306: return 'ok';
5307: }
5308:
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:
5318: sub files_in_path {
5319: my ($user, $path) = @_;
5320: my $filename = $user."savedfiles";
5321: my %return_files;
5322: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5323: while (my $line_in = <IN>) {
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);
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: }
5334: close (IN);
5335: return (\%return_files);
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;
5344: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5345: while (my $line = <IN>) {
5346: #ok, I know it's clunky, but I want it to work
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);
5351: $path_part .= '/';
5352: my $path_and_file = $path_part.$file_part;
5353: if ($path_part ne $path) {
5354: push(@return_files, ($path_and_file));
5355: }
5356: }
5357: close(OUT);
5358: return (@return_files);
5359: }
5360:
5361: #----------------------------------------------Get portfolio file permissions
5362:
5363: sub get_portfile_permissions {
5364: my ($domain,$user) = @_;
5365: my %current_permissions = &dump('file_permissions',$domain,$user);
5366: my ($tmp)=keys(%current_permissions);
5367: if ($tmp=~/^error:/) { undef(%current_permissions); }
5368: return \%current_permissions;
5369: }
5370:
5371: #---------------------------------------------Get portfolio file access controls
5372:
5373: sub get_access_controls {
5374: my ($current_permissions,$group,$file) = @_;
5375: my %access;
5376: my $real_file = $file;
5377: $file =~ s/\.meta$//;
5378: if (defined($file)) {
5379: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5380: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
5381: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
5382: }
5383: }
5384: } else {
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();
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: }
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: }
5446: }
5447: }
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: }
5482: }
5483: }
5484: }
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);
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);
5500: } else {
5501: $outcome = "error: could not obtain lockfile\n";
5502: }
5503: return ($outcome,$deloutcome,\%new_values,\%translation);
5504: }
5505:
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:
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);
5558: my @readonly_files;
5559: my $cmp1=$what;
5560: if (ref($what)) { $cmp1=join('',@{$what}) };
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: }
5567: if (ref($value) eq "ARRAY"){
5568: foreach my $stored_what (@{$value}) {
5569: my $cmp2=$stored_what;
5570: if (ref($stored_what) eq 'ARRAY') {
5571: $cmp2=join('',@{$stored_what});
5572: }
5573: if ($cmp1 eq $cmp2) {
5574: push(@readonly_files, $file_name);
5575: last;
5576: } elsif (!defined($what)) {
5577: push(@readonly_files, $file_name);
5578: last;
5579: }
5580: }
5581: }
5582: }
5583: return @readonly_files;
5584: }
5585: #-----------------------------------------------------------Get Marked as Read Only Hash
5586:
5587: sub get_marked_as_readonly_hash {
5588: my ($current_permissions,$group,$what) = @_;
5589: my %readonly_files;
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: }
5596: if (ref($value) eq "ARRAY"){
5597: foreach my $stored_what (@{$value}) {
5598: if (ref($stored_what) eq 'ARRAY') {
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: }
5609: }
5610: }
5611: }
5612: }
5613: }
5614: return %readonly_files;
5615: }
5616: # ------------------------------------------------------------ Unmark as Read Only
5617:
5618: sub unmark_as_readonly {
5619: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5620: # for portfolio submissions, $what contains [$symb,$crsid]
5621: my ($domain,$user,$what,$file_name,$group) = @_;
5622: $file_name = &declutter_portfile($file_name);
5623: my $symb_crs = $what;
5624: if (ref($what)) { $symb_crs=join('',@$what); }
5625: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
5626: my ($tmp)=keys(%current_permissions);
5627: if ($tmp=~/^error:/) { undef(%current_permissions); }
5628: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
5629: foreach my $file (@readonly_files) {
5630: my $clean_file = &declutter_portfile($file);
5631: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
5632: my $current_locks = $current_permissions{$file};
5633: my @new_locks;
5634: my @del_keys;
5635: if (ref($current_locks) eq "ARRAY"){
5636: foreach my $locker (@{$current_locks}) {
5637: my $compare=$locker;
5638: if (ref($locker) eq 'ARRAY') {
5639: $compare=join('',@{$locker});
5640: if ($compare ne $symb_crs) {
5641: push(@new_locks, $locker);
5642: }
5643: }
5644: }
5645: if (scalar(@new_locks) > 0) {
5646: $current_permissions{$file} = \@new_locks;
5647: } else {
5648: push(@del_keys, $file);
5649: &del('file_permissions',\@del_keys, $domain, $user);
5650: delete($current_permissions{$file});
5651: }
5652: }
5653: }
5654: &put('file_permissions',\%current_permissions,$domain,$user);
5655: return;
5656: }
5657:
5658: # ------------------------------------------------------------ Directory lister
5659:
5660: sub dirlist {
5661: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5662:
5663: $uri=~s/^\///;
5664: $uri=~s/\/$//;
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/\/$//;
5678: }
5679:
5680: if($udom) {
5681: if($uname) {
5682: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5683: &homeserver($uname,$udom));
5684: my @listing_results;
5685: if ($listing eq 'unknown_cmd') {
5686: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5687: &homeserver($uname,$udom));
5688: @listing_results = split(/:/,$listing);
5689: } else {
5690: @listing_results = map { &unescape($_); } split(/:/,$listing);
5691: }
5692: return @listing_results;
5693: } elsif(!defined($alternateDirectoryRoot)) {
5694: my %allusers;
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: }
5716: }
5717: my $alluserstr='';
5718: foreach my $user (sort(keys(%allusers))) {
5719: $alluserstr.=$user.'&user:';
5720: }
5721: $alluserstr=~s/:$//;
5722: return split(/:/,$alluserstr);
5723: } else {
5724: return ('missing user name');
5725: }
5726: } elsif(!defined($alternateDirectoryRoot)) {
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 {
5733: return ('missing domain');
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:
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: ##
5749: sub GetFileTimestamp {
5750: my ($studentDomain,$studentName,$filename,$root)=@_;
5751: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5752: $studentName = &LONCAPA::clean_username($studentName);
5753: my $subdir=$studentName.'__';
5754: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5755: my $proname="$studentDomain/$subdir/$studentName";
5756: $proname .= '/'.$filename;
5757: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5758: $studentName, $root);
5759: my @stats = split('&', $fileStat);
5760: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5761: # @stats contains first the filename, then the stat output
5762: return $stats[10]; # so this is 10 instead of 9.
5763: } else {
5764: return -1;
5765: }
5766: }
5767:
5768: sub stat_file {
5769: my ($uri) = @_;
5770: $uri = &clutter_with_no_wrapper($uri);
5771:
5772: my ($udom,$uname,$file,$dir);
5773: if ($uri =~ m-^/(uploaded|editupload)/-) {
5774: ($udom,$uname,$file) =
5775: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
5776: $file = 'userfiles/'.$file;
5777: $dir = &propath($udom,$uname);
5778: }
5779: if ($uri =~ m-^/res/-) {
5780: ($udom,$uname) =
5781: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
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);
5792:
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:
5800: # -------------------------------------------------------- Value of a Condition
5801:
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>}
5808: sub directcondval {
5809: my $number=shift;
5810: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5811: &Apache::lonuserstate::evalstate();
5812: }
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: }
5826: if ($env{'user.state.'.$env{'request.course.id'}}) {
5827: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5828: } else {
5829: return 2;
5830: }
5831: }
5832:
5833: # get the collection of conditions for this resource
5834: sub condval {
5835: my $condidx=shift;
5836: my $allpathcond='';
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: }
5842: }
5843: $allpathcond=~s/\|$//;
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: }
5876: }
5877: return $result;
5878: }
5879:
5880: # ---------------------------------------------------- Devalidate courseresdata
5881:
5882: sub devalidatecourseresdata {
5883: my ($coursenum,$coursedomain)=@_;
5884: my $hashid=$coursenum.':'.$coursedomain;
5885: &devalidate_cache_new('courseres',$hashid);
5886: }
5887:
5888:
5889: # --------------------------------------------------- Course Resourcedata Query
5890:
5891: sub get_courseresdata {
5892: my ($coursenum,$coursedomain)=@_;
5893: my $coursehom=&homeserver($coursenum,$coursedomain);
5894: my $hashid=$coursenum.':'.$coursedomain;
5895: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5896: my %dumpreply;
5897: unless (defined($cached)) {
5898: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5899: $result=\%dumpreply;
5900: my ($tmp) = keys(%dumpreply);
5901: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5902: &do_cache_new('courseres',$hashid,$result,600);
5903: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5904: return $tmp;
5905: } elsif ($tmp =~ /^(error)/) {
5906: $result=undef;
5907: &do_cache_new('courseres',$hashid,$result,600);
5908: }
5909: }
5910: return $result;
5911: }
5912:
5913: sub devalidateuserresdata {
5914: my ($uname,$udom)=@_;
5915: my $hashid="$udom:$uname";
5916: &devalidate_cache_new('userres',$hashid);
5917: }
5918:
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 /) {
5937: &logthis("<font color=\"blue\">WARNING:".
5938: " Trying to get resource data for ".
5939: $uname." at ".$udom.": ".
5940: $tmp."</font>");
5941: } elsif ($tmp=~/error: 2 /) {
5942: #&EXT_cache_set($udom,$uname);
5943: &do_cache_new('userres',$hashid,undef,600);
5944: undef($tmp); # not really an error so don't send it back
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; }
5958: foreach my $item (@which) {
5959: if (defined($result->{$item})) {
5960: return $result->{$item};
5961: }
5962: }
5963: return undef;
5964: }
5965:
5966: #
5967: # EXT resource caching routines
5968: #
5969:
5970: sub clear_EXT_cache_status {
5971: &delenv('cache.EXT.');
5972: }
5973:
5974: sub EXT_cache_status {
5975: my ($target_domain,$target_user) = @_;
5976: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5977: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
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) = @_;
5987: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5988: #&appenv($cachename => time);
5989: }
5990:
5991: # --------------------------------------------------------- Value of a Variable
5992: sub EXT {
5993:
5994: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5995: unless ($varname) { return ''; }
5996: #get real user name/domain, courseid and symb
5997: my $courseid;
5998: my $publicuser;
5999: if ($symbparm) {
6000: $symbparm=&get_symb_from_alias($symbparm);
6001: }
6002: if (!($uname && $udom)) {
6003: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
6004: if (!$symbparm) { $symbparm=$cursymb; }
6005: } else {
6006: $courseid=$env{'request.course.id'};
6007: }
6008: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6009: my $rest;
6010: if (defined($therest[0])) {
6011: $rest=join('.',@therest);
6012: } else {
6013: $rest='';
6014: }
6015:
6016: my $qualifierrest=$qualifier;
6017: if ($rest) { $qualifierrest.='.'.$rest; }
6018: my $spacequalifierrest=$space;
6019: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
6020: if ($realm eq 'user') {
6021: # --------------------------------------------------------------- user.resource
6022: if ($space eq 'resource') {
6023: if ( (defined($Apache::lonhomework::parsing_a_problem)
6024: || defined($Apache::lonhomework::parsing_a_task))
6025: &&
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: }
6034: } else {
6035: my %restored;
6036: if ($publicuser || $env{'request.state'} eq 'construct') {
6037: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6038: } else {
6039: %restored=&restore($symbparm,$courseid,$udom,$uname);
6040: }
6041: return $restored{$qualifierrest};
6042: }
6043: # ----------------------------------------------------------------- user.access
6044: } elsif ($space eq 'access') {
6045: # FIXME - not supporting calls for a specific user
6046: return &allowed($qualifier,$rest);
6047: # ------------------------------------------ user.preferences, user.environment
6048: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
6049: if (($uname eq $env{'user.name'}) &&
6050: ($udom eq $env{'user.domain'})) {
6051: return $env{join('.',('environment',$qualifierrest))};
6052: } else {
6053: my %returnhash;
6054: if (!$publicuser) {
6055: %returnhash=&userenvironment($udom,$uname,
6056: $qualifierrest);
6057: }
6058: return $returnhash{$qualifierrest};
6059: }
6060: # ----------------------------------------------------------------- user.course
6061: } elsif ($space eq 'course') {
6062: # FIXME - not supporting calls for a specific user
6063: return $env{join('.',('request.course',$qualifier))};
6064: # ------------------------------------------------------------------- user.role
6065: } elsif ($space eq 'role') {
6066: # FIXME - not supporting calls for a specific user
6067: my ($role,$where)=split(/\./,$env{'request.role'});
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') {
6075: return $udom;
6076: # ------------------------------------------------------------------- user.name
6077: } elsif ($space eq 'name') {
6078: return $uname;
6079: # ---------------------------------------------------- Any other user namespace
6080: } else {
6081: my %reply;
6082: if (!$publicuser) {
6083: %reply=&get($space,[$qualifierrest],$udom,$uname);
6084: }
6085: return $reply{$qualifierrest};
6086: }
6087: } elsif ($realm eq 'query') {
6088: # ---------------------------------------------- pull stuff out of query string
6089: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6090: [$spacequalifierrest]);
6091: return $env{'form.'.$spacequalifierrest};
6092: } elsif ($realm eq 'request') {
6093: # ------------------------------------------------------------- request.browser
6094: if ($space eq 'browser') {
6095: if ($qualifier eq 'textremote') {
6096: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
6097: return 1;
6098: } else {
6099: return 0;
6100: }
6101: } else {
6102: return $env{'browser.'.$qualifier};
6103: }
6104: # ------------------------------------------------------------ request.filename
6105: } else {
6106: return $env{'request.'.$spacequalifierrest};
6107: }
6108: } elsif ($realm eq 'course') {
6109: # ---------------------------------------------------------- course.description
6110: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
6111: } elsif ($realm eq 'resource') {
6112:
6113: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
6114: if (!$symbparm) { $symbparm=&symbread(); }
6115: }
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);
6128: my ($courselevelm,$courselevel);
6129: if ($symbparm && defined($courseid) &&
6130: $courseid eq $env{'request.course.id'}) {
6131:
6132: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
6133:
6134: # ----------------------------------------------------- Cascading lookup scheme
6135: my $symbp=$symbparm;
6136: my $mapp=&deversion((&decode_symb($symbp))[0]);
6137:
6138: my $symbparm=$symbp.'.'.$spacequalifierrest;
6139: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6140:
6141: if (($env{'user.name'} eq $uname) &&
6142: ($env{'user.domain'} eq $udom)) {
6143: $section=$env{'request.course.sec'};
6144: @groups = split(/:/,$env{'request.course.groups'});
6145: @groups=&sort_course_groups($courseid,@groups);
6146: } else {
6147: if (! defined($usection)) {
6148: $section=&getsection($udom,$uname,$courseid);
6149: } else {
6150: $section = $usection;
6151: }
6152: @groups = &get_users_groups($udom,$uname,$courseid);
6153: }
6154:
6155: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6156: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6157: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6158:
6159: $courselevel=$courseid.'.'.$spacequalifierrest;
6160: my $courselevelr=$courseid.'.'.$symbparm;
6161: $courselevelm=$courseid.'.'.$mapparm;
6162:
6163: # ----------------------------------------------------------- first, check user
6164:
6165: my $userreply=&resdata($uname,$udom,'user',
6166: ($courselevelr,$courselevelm,
6167: $courselevel));
6168: if (defined($userreply)) { return $userreply; }
6169:
6170: # ------------------------------------------------ second, check some of course
6171: my $coursereply;
6172: if (@groups > 0) {
6173: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6174: $mapparm,$spacequalifierrest);
6175: if (defined($coursereply)) { return $coursereply; }
6176: }
6177:
6178: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6179: $env{'course.'.$courseid.'.domain'},
6180: 'course',
6181: ($seclevelr,$seclevelm,$seclevel,
6182: $courselevelr));
6183: if (defined($coursereply)) { return $coursereply; }
6184:
6185: # ------------------------------------------------------ third, check map parms
6186: my %parmhash=();
6187: my $thisparm='';
6188: if (tie(%parmhash,'GDBM_File',
6189: $env{'request.course.fn'}.'_parms.db',
6190: &GDBM_READER(),0640)) {
6191: $thisparm=$parmhash{$symbparm};
6192: untie(%parmhash);
6193: }
6194: if ($thisparm) { return $thisparm; }
6195: }
6196: # ------------------------------------------ fourth, look in resource metadata
6197:
6198: $spacequalifierrest=~s/\./\_/;
6199: my $filename;
6200: if (!$symbparm) { $symbparm=&symbread(); }
6201: if ($symbparm) {
6202: $filename=(&decode_symb($symbparm))[2];
6203: } else {
6204: $filename=$env{'request.filename'};
6205: }
6206: my $metadata=&metadata($filename,$spacequalifierrest);
6207: if (defined($metadata)) { return $metadata; }
6208: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
6209: if (defined($metadata)) { return $metadata; }
6210:
6211: # ---------------------------------------------- fourth, look in rest pf course
6212: if ($symbparm && defined($courseid) &&
6213: $courseid eq $env{'request.course.id'}) {
6214: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6215: $env{'course.'.$courseid.'.domain'},
6216: 'course',
6217: ($courselevelm,$courselevel));
6218: if (defined($coursereply)) { return $coursereply; }
6219: }
6220: # ------------------------------------------------------------------ Cascade up
6221: unless ($space eq '0') {
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,
6227: $symbparm,$udom,$uname,$section,1);
6228: if (defined($partgeneral)) { return $partgeneral; }
6229: }
6230: if ($recurse) { return undef; }
6231: my $pack_def=&packages_tab_default($filename,$varname);
6232: if (defined($pack_def)) { return $pack_def; }
6233:
6234: # ---------------------------------------------------- Any other user namespace
6235: } elsif ($realm eq 'environment') {
6236: # ----------------------------------------------------------------- environment
6237: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6238: return $env{'environment.'.$spacequalifierrest};
6239: } else {
6240: if ($uname eq 'anonymous' && $udom eq '') {
6241: return '';
6242: }
6243: my %returnhash=&userenvironment($udom,$uname,
6244: $spacequalifierrest);
6245: return $returnhash{$spacequalifierrest};
6246: }
6247: } elsif ($realm eq 'system') {
6248: # ----------------------------------------------------------------- system.time
6249: if ($space eq 'time') {
6250: return time;
6251: }
6252: } elsif ($realm eq 'server') {
6253: # ----------------------------------------------------------------- system.time
6254: if ($space eq 'name') {
6255: return $ENV{'SERVER_NAME'};
6256: }
6257: }
6258: return '';
6259: }
6260:
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().
6279: my ($courseid,@groups) = @_;
6280: @groups = sort(@groups);
6281: return @groups;
6282: }
6283:
6284: sub packages_tab_default {
6285: my ($uri,$varname)=@_;
6286: my (undef,$part,$name)=split(/\./,$varname);
6287:
6288: my (@extension,@specifics,$do_default);
6289: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
6290: my ($pack_type,$pack_part)=split(/_/,$package,2);
6291: if ($pack_type eq 'default') {
6292: $do_default=1;
6293: } elsif ($pack_type eq 'extension') {
6294: push(@extension,[$package,$pack_type,$pack_part]);
6295: } elsif ($pack_part eq $part) {
6296: # only look at packages defaults for packages that this id is
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};
6311: if (defined($packagetab{"$pack_type&$name&default"})) {
6312: return $packagetab{"$pack_type&$name&default"};
6313: }
6314: if ($pack_type eq 'part') { $pack_part='0'; }
6315: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6316: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
6317: }
6318: }
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: }
6333: return undef;
6334: }
6335:
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:
6352: # ---------------------------------------------------------------- Get metadata
6353:
6354: my %metaentry;
6355: sub metadata {
6356: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
6357: $uri=&declutter($uri);
6358: # if it is a non metadata possible uri return quickly
6359: if (($uri eq '') ||
6360: (($uri =~ m|^/*adm/|) &&
6361: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
6362: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
6363: ($uri =~ m|home/$match_username/public_html/|)) {
6364: return undef;
6365: }
6366: my $filename=$uri;
6367: $uri=~s/\.meta$//;
6368: #
6369: # Is the metadata already cached?
6370: # Look at timestamp of caching
6371: # Everything is cached by the main uri, libraries are never directly cached
6372: #
6373: if (!defined($liburi)) {
6374: my ($result,$cached)=&is_cached_new('meta',$uri);
6375: if (defined($cached)) { return $result->{':'.$what}; }
6376: }
6377: {
6378: #
6379: # Is this a recursive call for a library?
6380: #
6381: # if (! exists($metacache{$uri})) {
6382: # $metacache{$uri}={};
6383: # }
6384: if ($liburi) {
6385: $liburi=&declutter($liburi);
6386: $filename=$liburi;
6387: } else {
6388: &devalidate_cache_new('meta',$uri);
6389: undef(%metaentry);
6390: }
6391: my %metathesekeys=();
6392: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
6393: my $metastring;
6394: if ($uri !~ m -^(editupload)/-) {
6395: my $file=&filelocation('',&clutter($filename));
6396: #push(@{$metaentry{$uri.'.file'}},$file);
6397: $metastring=&getfile($file);
6398: }
6399: my $parser=HTML::LCParser->new(\$metastring);
6400: my $token;
6401: undef %metathesekeys;
6402: while ($token=$parser->get_token) {
6403: if ($token->[0] eq 'S') {
6404: if (defined($token->[2]->{'package'})) {
6405: #
6406: # This is a package - get package info
6407: #
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: }
6413: if ($metaentry{':packages'}) {
6414: $metaentry{':packages'}.=','.$package.$keyroot;
6415: } else {
6416: $metaentry{':packages'}=$package.$keyroot;
6417: }
6418: foreach my $pack_entry (keys(%packagetab)) {
6419: my $part=$keyroot;
6420: $part=~s/^\_//;
6421: if ($pack_entry=~/^\Q$package\E\&/ ||
6422: $pack_entry=~/^\Q$package\E_0\&/) {
6423: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
6424: # ignore package.tab specified default values
6425: # here &package_tab_default() will fetch those
6426: if ($subp eq 'default') { next; }
6427: my $value=$packagetab{$pack_entry};
6428: my $unikey;
6429: if ($pack =~ /_0$/) {
6430: $unikey='parameter_0_'.$name;
6431: $part=0;
6432: } else {
6433: $unikey='parameter'.$keyroot.'_'.$name;
6434: }
6435: if ($subp eq 'display') {
6436: $value.=' [Part: '.$part.']';
6437: }
6438: $metaentry{':'.$unikey.'.part'}=$part;
6439: $metathesekeys{$unikey}=1;
6440: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6441: $metaentry{':'.$unikey.'.'.$subp}=$value;
6442: }
6443: if (defined($metaentry{':'.$unikey.'.default'})) {
6444: $metaentry{':'.$unikey}=
6445: $metaentry{':'.$unikey.'.default'};
6446: }
6447: }
6448: }
6449: } else {
6450: #
6451: # This is not a package - some other kind of start tag
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: }
6465:
6466: if ($entry eq 'import') {
6467: #
6468: # Importing a library here
6469: #
6470: if ($depthcount<20) {
6471: my $location=$parser->get_text('/import');
6472: my $dir=$filename;
6473: $dir=~s|[^/]*$||;
6474: $location=&filelocation($dir,$location);
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;
6481: }
6482: }
6483: } else {
6484:
6485: if (defined($token->[2]->{'name'})) {
6486: $unikey.='_'.$token->[2]->{'name'};
6487: }
6488: $metathesekeys{$unikey}=1;
6489: foreach my $param (@{$token->[3]}) {
6490: $metaentry{':'.$unikey.'.'.$param} =
6491: $token->[2]->{$param};
6492: }
6493: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
6494: my $default=$metaentry{':'.$unikey.'.default'};
6495: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6496: # only ws inside the tag, and not in default, so use default
6497: # as value
6498: $metaentry{':'.$unikey}=$default;
6499: } else {
6500: # either something interesting inside the tag or default
6501: # uninteresting
6502: $metaentry{':'.$unikey}=$internaltext;
6503: }
6504: # end of not-a-package not-a-library import
6505: }
6506: # end of not-a-package start tag
6507: }
6508: # the next is the end of "start tag"
6509: }
6510: }
6511: my ($extension) = ($uri =~ /\.(\w+)$/);
6512: foreach my $key (keys(%packagetab)) {
6513: #no specific packages #how's our extension
6514: if ($key!~/^extension_\Q$extension\E&/) { next; }
6515: &metadata_create_package_def($uri,$key,'extension_'.$extension,
6516: \%metathesekeys);
6517: }
6518: if (!exists($metaentry{':packages'})) {
6519: foreach my $key (keys(%packagetab)) {
6520: #no specific packages well let's get default then
6521: if ($key!~/^default&/) { next; }
6522: &metadata_create_package_def($uri,$key,'default',
6523: \%metathesekeys);
6524: }
6525: }
6526: # are there custom rights to evaluate
6527: if ($metaentry{':copyright'} eq 'custom') {
6528:
6529: #
6530: # Importing a rights file here
6531: #
6532: unless ($depthcount) {
6533: my $location=$metaentry{':customdistributionfile'};
6534: my $dir=$filename;
6535: $dir=~s|[^/]*$||;
6536: $location=&filelocation($dir,$location);
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;
6543: }
6544: }
6545: }
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));
6553: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6554: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
6555: &do_cache_new('meta',$uri,\%metaentry,60*60);
6556: # this is the end of "was not already recently cached
6557: }
6558: return $metaentry{':'.$what};
6559: }
6560:
6561: sub metadata_create_package_def {
6562: my ($uri,$key,$package,$metathesekeys)=@_;
6563: my ($pack,$name,$subp)=split(/\&/,$key);
6564: if ($subp eq 'default') { next; }
6565:
6566: if (defined($metaentry{':packages'})) {
6567: $metaentry{':packages'}.=','.$package;
6568: } else {
6569: $metaentry{':packages'}=$package;
6570: }
6571: my $value=$packagetab{$key};
6572: my $unikey;
6573: $unikey='parameter_0_'.$name;
6574: $metaentry{':'.$unikey.'.part'}=0;
6575: $$metathesekeys{$unikey}=1;
6576: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6577: $metaentry{':'.$unikey.'.'.$subp}=$value;
6578: }
6579: if (defined($metaentry{':'.$unikey.'.default'})) {
6580: $metaentry{':'.$unikey}=
6581: $metaentry{':'.$unikey.'.default'};
6582: }
6583: }
6584:
6585: sub metadata_generate_part0 {
6586: my ($metadata,$metacache,$uri) = @_;
6587: my %allnames;
6588: foreach my $metakey (keys(%$metadata)) {
6589: if ($metakey=~/^parameter\_(.*)/) {
6590: my $part=$$metacache{':'.$metakey.'.part'};
6591: my $name=$$metacache{':'.$metakey.'.name'};
6592: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
6593: $allnames{$name}=$part;
6594: }
6595: }
6596: }
6597: foreach my $name (keys(%allnames)) {
6598: $$metadata{"parameter_0_$name"}=1;
6599: my $key=":parameter_0_$name";
6600: $$metacache{"$key.part"}='0';
6601: $$metacache{"$key.name"}=$name;
6602: $$metacache{"$key.type"}=$$metacache{':parameter_'.
6603: $allnames{$name}.'_'.$name.
6604: '.type'};
6605: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
6606: '.display'};
6607: my $expr='[Part: '.$allnames{$name}.']';
6608: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
6609: $$metacache{"$key.display"}=$olddis;
6610: }
6611: }
6612:
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:
6624: # ------------------------------------------------- Get the title of a resource
6625:
6626: sub gettitle {
6627: my $urlsymb=shift;
6628: my $symb=&symbread($urlsymb);
6629: if ($symb) {
6630: my $key=$env{'request.course.id'}."\0".$symb;
6631: my ($result,$cached)=&is_cached_new('title',$key);
6632: if (defined($cached)) {
6633: return $result;
6634: }
6635: my ($map,$resid,$url)=&decode_symb($symb);
6636: my $title='';
6637: my %bighash;
6638: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
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) {
6646: return &do_cache_new('title',$key,$title,600);
6647: }
6648: $urlsymb=$url;
6649: }
6650: my $title=&metadata($urlsymb,'title');
6651: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6652: return $title;
6653: }
6654:
6655: sub get_slot {
6656: my ($which,$cnum,$cdom)=@_;
6657: if (!$cnum || !$cdom) {
6658: (undef,my $courseid)=&whichuser();
6659: $cdom=$env{'course.'.$courseid.'.domain'};
6660: $cnum=$env{'course.'.$courseid.'.num'};
6661: }
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: }
6673: if (ref($slotinfo{$which}) eq 'HASH') {
6674: return %{$slotinfo{$which}};
6675: }
6676: return $slotinfo{$which};
6677: }
6678: # ------------------------------------------------- Update symbolic store links
6679:
6680: sub symblist {
6681: my ($mapname,%newhash)=@_;
6682: $mapname=&deversion(&declutter($mapname));
6683: my %hash;
6684: if (($env{'request.course.fn'}) && (%newhash)) {
6685: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6686: &GDBM_WRCREAT(),0640)) {
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]);
6693: }
6694: if (untie(%hash)) {
6695: return 'ok';
6696: }
6697: }
6698: }
6699: return 'error';
6700: }
6701:
6702: # --------------------------------------------------------------- Verify a symb
6703:
6704: sub symbverify {
6705: my ($symb,$thisurl)=@_;
6706: my $thisfn=$thisurl;
6707: $thisfn=&declutter($thisfn);
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
6711: my ($map,$resid,$url)=&decode_symb($symb);
6712:
6713: unless ($url eq $thisfn) { return 0; }
6714:
6715: $symb=&symbclean($symb);
6716: $thisurl=&deversion($thisurl);
6717: $thisfn=&deversion($thisfn);
6718:
6719: my %bighash;
6720: my $okay=0;
6721:
6722: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6723: &GDBM_READER(),0640)) {
6724: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6725: unless ($ids) {
6726: $ids=$bighash{'ids_/'.$thisurl};
6727: }
6728: if ($ids) {
6729: # ------------------------------------------------------------------- Has ID(s)
6730: foreach my $id (split(/\,/,$ids)) {
6731: my ($mapid,$resid)=split(/\./,$id);
6732: if (
6733: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6734: eq $symb) {
6735: if (($env{'request.role.adv'}) ||
6736: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
6737: $okay=1;
6738: }
6739: }
6740: }
6741: }
6742: untie(%bighash);
6743: }
6744: return $okay;
6745: }
6746:
6747: # --------------------------------------------------------------- Clean-up symb
6748:
6749: sub symbclean {
6750: my $symb=shift;
6751: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6752: # remove version from map
6753: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6754:
6755: # remove version from URL
6756: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6757:
6758: # remove wrapper
6759:
6760: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6761: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6762: return $symb;
6763: }
6764:
6765: # ---------------------------------------------- Split symb to find map and url
6766:
6767: sub encode_symb {
6768: my ($map,$resid,$url)=@_;
6769: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6770: }
6771:
6772: sub decode_symb {
6773: my $symb=shift;
6774: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6775: my ($map,$resid,$url)=split(/___/,$symb);
6776: return (&fixversion($map),$resid,&fixversion($url));
6777: }
6778:
6779: sub fixversion {
6780: my $fn=shift;
6781: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6782: my %bighash;
6783: my $uri=&clutter($fn);
6784: my $key=$env{'request.course.id'}.'_'.$uri;
6785: # is this cached?
6786: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6787: if (defined($cached)) { return $result; }
6788: # unfortunately not cached, or expired
6789: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6790: &GDBM_READER(),0640)) {
6791: if ($bighash{'version_'.$uri}) {
6792: my $version=$bighash{'version_'.$uri};
6793: unless (($version eq 'mostrecent') ||
6794: ($version==&getversion($uri))) {
6795: $uri=~s/\.(\w+)$/\.$version\.$1/;
6796: }
6797: }
6798: untie %bighash;
6799: }
6800: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6801: }
6802:
6803: sub deversion {
6804: my $url=shift;
6805: $url=~s/\.\d+\.(\w+)$/\.$1/;
6806: return $url;
6807: }
6808:
6809: # ------------------------------------------------------ Return symb list entry
6810:
6811: sub symbread {
6812: my ($thisfn,$donotrecurse)=@_;
6813: my $cache_str='request.symbread.cached.'.$thisfn;
6814: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6815: # no filename provided? try from environment
6816: unless ($thisfn) {
6817: if ($env{'request.symb'}) {
6818: return $env{$cache_str}=&symbclean($env{'request.symb'});
6819: }
6820: $thisfn=$env{'request.filename'};
6821: }
6822: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6823: # is that filename actually a symb? Verify, clean, and return
6824: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6825: if (&symbverify($thisfn,$1)) {
6826: return $env{$cache_str}=&symbclean($thisfn);
6827: }
6828: }
6829: $thisfn=declutter($thisfn);
6830: my %hash;
6831: my %bighash;
6832: my $syval='';
6833: if (($env{'request.course.fn'}) && ($thisfn)) {
6834: my $targetfn = $thisfn;
6835: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6836: $targetfn = 'adm/wrapper/'.$thisfn;
6837: }
6838: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6839: $targetfn=$1;
6840: }
6841: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6842: &GDBM_READER(),0640)) {
6843: $syval=$hash{$targetfn};
6844: untie(%hash);
6845: }
6846: # ---------------------------------------------------------- There was an entry
6847: if ($syval) {
6848: #unless ($syval=~/\_\d+$/) {
6849: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6850: #&appenv('request.ambiguous' => $thisfn);
6851: #return $env{$cache_str}='';
6852: #}
6853: #$syval.=$1;
6854: #}
6855: } else {
6856: # ------------------------------------------------------- Was not in symb table
6857: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6858: &GDBM_READER(),0640)) {
6859: # ---------------------------------------------- Get ID(s) for current resource
6860: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6861: unless ($ids) {
6862: $ids=$bighash{'ids_/'.$thisfn};
6863: }
6864: unless ($ids) {
6865: # alias?
6866: $ids=$bighash{'mapalias_'.$thisfn};
6867: }
6868: if ($ids) {
6869: # ------------------------------------------------------------------- Has ID(s)
6870: my @possibilities=split(/\,/,$ids);
6871: if ($#possibilities==0) {
6872: # ----------------------------------------------- There is only one possibility
6873: my ($mapid,$resid)=split(/\./,$ids);
6874: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6875: $resid,$thisfn);
6876: } elsif (!$donotrecurse) {
6877: # ------------------------------------------ There is more than one possibility
6878: my $realpossible=0;
6879: foreach my $id (@possibilities) {
6880: my $file=$bighash{'src_'.$id};
6881: if (&allowed('bre',$file)) {
6882: my ($mapid,$resid)=split(/\./,$id);
6883: if ($bighash{'map_type_'.$mapid} ne 'page') {
6884: $realpossible++;
6885: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6886: $resid,$thisfn);
6887: }
6888: }
6889: }
6890: if ($realpossible!=1) { $syval=''; }
6891: } else {
6892: $syval='';
6893: }
6894: }
6895: untie(%bighash)
6896: }
6897: }
6898: if ($syval) {
6899: return $env{$cache_str}=$syval;
6900: }
6901: }
6902: &appenv('request.ambiguous' => $thisfn);
6903: return $env{$cache_str}='';
6904: }
6905:
6906: # ---------------------------------------------------------- Return random seed
6907:
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;
6917: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6918: return int($txt);
6919: }
6920:
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; }
6933: if ($_64bit) { if ($total > 2**32) { return -1; } }
6934: return int($total);
6935: }
6936:
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:
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:
6983: sub latest_rnd_algorithm_id {
6984: return '64bit5';
6985: }
6986:
6987: sub get_rand_alg {
6988: my ($courseid)=@_;
6989: if (!$courseid) { $courseid=(&whichuser())[1]; }
6990: if ($courseid) {
6991: return $env{"course.$courseid.rndseed"};
6992: }
6993: return &latest_rnd_algorithm_id();
6994: }
6995:
6996: sub validCODE {
6997: my ($CODE)=@_;
6998: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6999: return 0;
7000: }
7001:
7002: sub getCODE {
7003: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
7004: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7005: defined($Apache::lonhomework::parsing_a_task) ) &&
7006: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
7007: return $Apache::lonhomework::history{'resource.CODE'};
7008: }
7009: return undef;
7010: }
7011:
7012: sub rndseed {
7013: my ($symb,$courseid,$domain,$username)=@_;
7014: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
7015: if (!$symb) {
7016: unless ($symb=$wsymb) { return time; }
7017: }
7018: if (!$courseid) { $courseid=$wcourseid; }
7019: if (!$domain) { $domain=$wdomain; }
7020: if (!$username) { $username=$wusername }
7021: my $which=&get_rand_alg();
7022:
7023: if (defined(&getCODE())) {
7024: if ($which eq '64bit5') {
7025: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7026: } elsif ($which eq '64bit4') {
7027: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7028: } else {
7029: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7030: }
7031: } elsif ($which eq '64bit5') {
7032: return &rndseed_64bit5($symb,$courseid,$domain,$username);
7033: } elsif ($which eq '64bit4') {
7034: return &rndseed_64bit4($symb,$courseid,$domain,$username);
7035: } elsif ($which eq '64bit3') {
7036: return &rndseed_64bit3($symb,$courseid,$domain,$username);
7037: } elsif ($which eq '64bit2') {
7038: return &rndseed_64bit2($symb,$courseid,$domain,$username);
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;
7056: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7057: #&logthis("rndseed :$num:$symb");
7058: if ($_64bit) { $num=(($num<<32)>>32); }
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;
7077: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7078: #&logthis("rndseed :$num:$symb");
7079: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7080: return "$num1,$num2";
7081: }
7082: }
7083:
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;
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;
7100: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7101: #&logthis("rndseed :$num:$symb");
7102: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
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;
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;
7123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7124: #&logthis("rndseed :$num1:$num2:$_64bit");
7125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7126:
7127: return "$num1:$num2";
7128: }
7129: }
7130:
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;
7147: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7148: #&logthis("rndseed :$num1:$num2:$_64bit");
7149: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7150:
7151: return "$num1:$num2";
7152: }
7153: }
7154:
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:
7161: sub rndseed_CODE_64bit {
7162: my ($symb,$courseid,$domain,$username)=@_;
7163: {
7164: use integer;
7165: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7166: my $symbseed=numval2($symb);
7167: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7168: my $CODEseed=numval(&getCODE());
7169: my $courseseed=unpack("%32S*",$courseid.' ');
7170: my $num1=$symbseed+$CODEchck;
7171: my $num2=$CODEseed+$courseseed+$symbchck;
7172: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7173: #&logthis("rndseed :$num1:$num2:$symb");
7174: if ($_64bit) { $num1=(($num1<<32)>>32); }
7175: if ($_64bit) { $num2=(($num2<<32)>>32); }
7176: return "$num1:$num2";
7177: }
7178: }
7179:
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;
7191: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7192: #&logthis("rndseed :$num1:$num2:$symb");
7193: if ($_64bit) { $num1=(($num1<<32)>>32); }
7194: if ($_64bit) { $num2=(($num2<<32)>>32); }
7195: return "$num1:$num2";
7196: }
7197: }
7198:
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:
7206: sub setup_random_from_rndseed {
7207: my ($rndseed)=@_;
7208: if ($rndseed =~/([,:])/) {
7209: my ($num1,$num2)=split(/[,:]/,$rndseed);
7210: &Math::Random::random_set_seed(abs($num1),abs($num2));
7211: } else {
7212: &Math::Random::random_set_seed_from_phrase($rndseed);
7213: }
7214: }
7215:
7216: sub latest_receipt_algorithm_id {
7217: return 'receipt3';
7218: }
7219:
7220: sub recunique {
7221: my $fucourseid=shift;
7222: my $unique;
7223: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7224: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7225: $unique=$env{"course.$fucourseid.internal.encseed"};
7226: } else {
7227: $unique=$perlvar{'lonReceipt'};
7228: }
7229: return unpack("%32C*",$unique);
7230: }
7231:
7232: sub recprefix {
7233: my $fucourseid=shift;
7234: my $prefix;
7235: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7236: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7237: $prefix=$env{"course.$fucourseid.internal.encpref"};
7238: } else {
7239: $prefix=$perlvar{'lonHostID'};
7240: }
7241: return unpack("%32C*",$prefix);
7242: }
7243:
7244: sub ireceipt {
7245: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
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:
7255: my $cuname=unpack("%32C*",$funame);
7256: my $cudom=unpack("%32C*",$fudom);
7257: my $cucourseid=unpack("%32C*",$fucourseid);
7258: my $cusymb=unpack("%32C*",$fusymb);
7259: my $cunique=&recunique($fucourseid);
7260: my $cpart=unpack("%32S*",$part);
7261: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7262:
7263: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
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;
7282: }
7283:
7284: sub receipt {
7285: my ($part)=@_;
7286: my ($symb,$courseid,$domain,$name) = &whichuser();
7287: return &ireceipt($name,$domain,$courseid,$symb,$part);
7288: }
7289:
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:
7328: # ------------------------------------------------------------ Serves up a file
7329: # returns either the contents of the file or
7330: # -1 if the file doesn't exist
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.
7337:
7338: sub getfile {
7339: my ($file) = @_;
7340: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7341: &repcopy($file);
7342: return &readfile($file);
7343: }
7344:
7345: sub repcopy_userfile {
7346: my ($file)=@_;
7347: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7348: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
7349: my ($cdom,$cnum,$filename) =
7350: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
7351: my $uri="/uploaded/$cdom/$cnum/$filename";
7352: if (-e "$file") {
7353: # we already have a local copy, check it out
7354: my @fileinfo = stat($file);
7355: my $rtncode;
7356: my $info;
7357: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
7358: if ($lwpresp ne 'ok') {
7359: # there is no such file anymore, even though we had a local copy
7360: if ($rtncode eq '404') {
7361: unlink($file);
7362: }
7363: return -1;
7364: }
7365: if ($info < $fileinfo[9]) {
7366: # nice, the file we have is up-to-date, just say okay
7367: return 'ok';
7368: } else {
7369: # the file is outdated, get rid of it
7370: unlink($file);
7371: }
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);
7384: }
7385: }
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/^\///;
7394: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
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);
7404: return 'ok';
7405: }
7406:
7407: sub tokenwrapper {
7408: my $uri=shift;
7409: $uri=~s|^http\://([^/]+)||;
7410: $uri=~s|^/||;
7411: $env{'user.environment'}=~/\/([^\/]+)\.id/;
7412: my $token=$1;
7413: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7414: if ($udom && $uname && $file) {
7415: $file=~s|(\?\.*)*$||;
7416: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
7417: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
7418: (($uri=~/\?/)?'&':'?').'token='.$token.
7419: '&tokenissued='.$perlvar{'lonHostID'};
7420: } else {
7421: return '/adm/notfound.html';
7422: }
7423: }
7424:
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: #
7429: sub getuploaded {
7430: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7431: $uri=~s/^\///;
7432: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
7433: my $ua=new LWP::UserAgent;
7434: my $request=new HTTP::Request($reqtype,$uri);
7435: my $response=$ua->request($request);
7436: $$rtncode = $response->code;
7437: if (! $response->is_success()) {
7438: return 'failed';
7439: }
7440: if ($reqtype eq 'HEAD') {
7441: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
7442: } elsif ($reqtype eq 'GET') {
7443: $$info = $response->content;
7444: }
7445: return 'ok';
7446: }
7447:
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='';
7454: while (my $line = <$fh>) { $a .= $line; }
7455: return $a;
7456: }
7457:
7458: sub filelocation {
7459: my ($dir,$file) = @_;
7460: my $location;
7461: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
7462:
7463: if ($file =~ m-^/adm/-) {
7464: $file=~s-^/adm/wrapper/-/-;
7465: $file=~s-^/adm/coursedocs/showdoc/-/-;
7466: }
7467: if ($file=~m:^/~:) { # is a contruction space reference
7468: $location = $file;
7469: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
7470: } elsif ($file=~m{^/home/$match_username/public_html/}) {
7471: # is a correct contruction space reference
7472: $location = $file;
7473: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
7474: my ($udom,$uname,$filename)=
7475: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
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) {
7481: $location=&propath($udom,$uname).
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: }
7495: }
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;
7500: }
7501:
7502: sub hreflocation {
7503: my ($dir,$file)=@_;
7504: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
7505: $file=filelocation($dir,$file);
7506: } elsif ($file=~m-^/adm/-) {
7507: $file=~s-^/adm/wrapper/-/-;
7508: $file=~s-^/adm/coursedocs/showdoc/-/-;
7509: }
7510: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7511: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7512: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7513: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
7514: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7515: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
7516: -/uploaded/$1/$2/-x;
7517: }
7518: return $file;
7519: }
7520:
7521: sub current_machine_domains {
7522: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7523: }
7524:
7525: sub machine_domains {
7526: my ($hostname) = @_;
7527: my @domains;
7528: my %hostname = &all_hostnames();
7529: while( my($id, $name) = each(%hostname)) {
7530: # &logthis("-$id-$name-$hostname-");
7531: if ($hostname eq $name) {
7532: push(@domains,&host_domain($id));
7533: }
7534: }
7535: return @domains;
7536: }
7537:
7538: sub current_machine_ids {
7539: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7540: }
7541:
7542: sub machine_ids {
7543: my ($hostname) = @_;
7544: $hostname ||= &hostname($perlvar{'lonHostID'});
7545: my @ids;
7546: my %hostname = &all_hostnames();
7547: while( my($id, $name) = each(%hostname)) {
7548: # &logthis("-$id-$name-$hostname-");
7549: if ($hostname eq $name) {
7550: push(@ids,$id);
7551: }
7552: }
7553: return @ids;
7554: }
7555:
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:
7579: # ------------------------------------------------------------- Declutters URLs
7580:
7581: sub declutter {
7582: my $thisfn=shift;
7583: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7584: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7585: $thisfn=~s/^\///;
7586: $thisfn=~s|^adm/wrapper/||;
7587: $thisfn=~s|^adm/coursedocs/showdoc/||;
7588: $thisfn=~s/^res\///;
7589: $thisfn=~s/\?.+$//;
7590: return $thisfn;
7591: }
7592:
7593: # ------------------------------------------------------------- Clutter up URLs
7594:
7595: sub clutter {
7596: my $thisfn='/'.&declutter(shift);
7597: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
7598: $thisfn='/res'.$thisfn;
7599: }
7600: if ($thisfn !~m|/adm|) {
7601: if ($thisfn =~ m|/ext/|) {
7602: $thisfn='/adm/wrapper'.$thisfn;
7603: } else {
7604: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7605: my $embstyle=&Apache::loncommon::fileembstyle($ext);
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')
7613: || ($embstyle eq 'emb')
7614: || ($embstyle eq 'wrp')) {
7615: $thisfn='/adm/wrapper'.$thisfn;
7616: } elsif ($embstyle eq 'unk'
7617: && $thisfn!~/\.(sequence|page)$/) {
7618: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
7619: } else {
7620: # &logthis("Got a blank emb style");
7621: }
7622: }
7623: }
7624: return $thisfn;
7625: }
7626:
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:
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:
7645:
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:
7656: sub correct_line_ends {
7657: my ($result)=@_;
7658: $$result =~s/\r\n/\n/mg;
7659: $$result =~s/\r/\n/mg;
7660: }
7661: # ================================================================ Main Program
7662:
7663: sub goodbye {
7664: &logthis("Starting Shut down");
7665: #not converted to using infrastruture and probably shouldn't be
7666: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
7667: #converted
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))));
7672: #1.1 only
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));
7680: &flushcourselogs();
7681: &logthis("Shutting down");
7682: }
7683:
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: }
7699: # ------------------------------------------------------------ Read domain file
7700: {
7701: my $loaded;
7702: my %domain;
7703:
7704: sub parse_domain_tab {
7705: my ($lines) = @_;
7706: foreach my $line (@$lines) {
7707: next if ($line =~ /^(\#|\s*$ )/x);
7708:
7709: chomp($line);
7710: my ($name,@elements) = split(/:/,$line,9);
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;
7718: }
7719: }
7720:
7721: sub reset_domain_info {
7722: undef($loaded);
7723: undef(%domain);
7724: }
7725:
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);
7732: }
7733: close($fh);
7734: $loaded = 1;
7735: }
7736:
7737: sub domain {
7738: &load_domain_tab() if (!$loaded);
7739:
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: }
7748: }
7749:
7750:
7751: # ------------------------------------------------------------- Read hosts file
7752: {
7753: my %hostname;
7754: my %hostdom;
7755: my %libserv;
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: }
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: }
7782:
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;
7790: }
7791:
7792: sub hostname {
7793: &load_hosts_tab() if (!$loaded);
7794:
7795: my ($lonid) = @_;
7796: return $hostname{$lonid};
7797: }
7798:
7799: sub all_hostnames {
7800: &load_hosts_tab() if (!$loaded);
7801:
7802: return %hostname;
7803: }
7804:
7805: sub is_library {
7806: &load_hosts_tab() if (!$loaded);
7807:
7808: return exists($libserv{$_[0]});
7809: }
7810:
7811: sub all_library {
7812: &load_hosts_tab() if (!$loaded);
7813:
7814: return %libserv;
7815: }
7816:
7817: sub get_servers {
7818: &load_hosts_tab() if (!$loaded);
7819:
7820: my ($domain,$type) = @_;
7821: my %possible_hosts = ($type eq 'library') ? %libserv
7822: : %hostname;
7823: my %result;
7824: if (ref($domain) eq 'ARRAY') {
7825: while ( my ($host,$hostname) = each(%possible_hosts)) {
7826: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
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: }
7835: }
7836: }
7837: return %result;
7838: }
7839:
7840: sub host_domain {
7841: &load_hosts_tab() if (!$loaded);
7842:
7843: my ($lonid) = @_;
7844: return $hostdom{$lonid};
7845: }
7846:
7847: sub all_domains {
7848: &load_hosts_tab() if (!$loaded);
7849:
7850: my %seen;
7851: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7852: return @uniq;
7853: }
7854: }
7855:
7856: {
7857: my %iphost;
7858: my %name_to_ip;
7859: my %lonid_to_ip;
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;
7867: }
7868:
7869: sub reset_hosts_ip_info {
7870: undef(%iphost);
7871: undef(%name_to_ip);
7872: undef(%lonid_to_ip);
7873: }
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: }
7888:
7889: sub get_iphost {
7890: if (%iphost) { return %iphost; }
7891: my %hostname = &all_hostnames();
7892: foreach my $id (keys(%hostname)) {
7893: my $name=&hostname($id);
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};
7905: }
7906: $lonid_to_ip{$id} = $ip;
7907: push(@{$iphost{$ip}},$id);
7908: }
7909: return %iphost;
7910: }
7911: }
7912:
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:
7923: # ------------------------------------------------------ Read spare server file
7924: {
7925: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7926:
7927: while (my $configline=<$config>) {
7928: chomp($configline);
7929: if ($configline) {
7930: my ($host,$type) = split(':',$configline,2);
7931: if (!defined($type) || $type eq '') { $type = 'default' };
7932: push(@{ $spareid{$type} }, $host);
7933: }
7934: }
7935: close($config);
7936: }
7937: # ------------------------------------------------------------ Read permissions
7938: {
7939: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7940:
7941: while (my $configline=<$config>) {
7942: chomp($configline);
7943: if ($configline) {
7944: my ($role,$perm)=split(/ /,$configline);
7945: if ($perm ne '') { $pr{$role}=$perm; }
7946: }
7947: }
7948: close($config);
7949: }
7950:
7951: # -------------------------------------------- Read plain texts for permissions
7952: {
7953: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7954:
7955: while (my $configline=<$config>) {
7956: chomp($configline);
7957: if ($configline) {
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: }
7966: }
7967: }
7968: close($config);
7969: }
7970:
7971: # ---------------------------------------------------------- Read package table
7972: {
7973: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7974:
7975: while (my $configline=<$config>) {
7976: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
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: }
7984: }
7985: close($config);
7986: }
7987:
7988: # ------------- set up temporary directory
7989: {
7990: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7991:
7992: }
7993:
7994: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7995: 'compress_threshold'=> 20_000,
7996: });
7997:
7998: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7999: $dumpcount=0;
8000:
8001: &logtouch();
8002: &logthis('<font color="yellow">INFO: Read configuration</font>');
8003: $readit=1;
8004: {
8005: use integer;
8006: my $test=(2**32)+1;
8007: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
8008: &logthis(" Detected 64bit platform ($_64bit)");
8009: }
8010: }
8011: }
8012:
8013: 1;
8014: __END__
8015:
8016: =pod
8017:
8018: =head1 NAME
8019:
8020: Apache::lonnet - Subroutines to ask questions about things in the network.
8021:
8022: =head1 SYNOPSIS
8023:
8024: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
8025:
8026: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8027:
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:
8051: =head1 OVERVIEW
8052:
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.
8056:
8057: For many of these objects you can also use this to store data about
8058: them or modify them in various ways.
8059:
8060: =head2 Symbs
8061:
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:
8123:
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.
8147:
8148: Calling convention:
8149:
8150: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8151: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
8152:
8153: For more detailed information, see lonnet specific documentation.
8154:
8155: =head1 RETURN MESSAGES
8156:
8157: =over 4
8158:
8159: =item * B<con_lost>: unable to contact remote host
8160:
8161: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8162: when the connection is brought back up
8163:
8164: =item * B<con_failed>: unable to contact remote host and unable to save message
8165: for later delivery
8166:
8167: =item * B<error:>: an error a occured, a description of the error follows the :
8168:
8169: =item * B<no_such_host>: unable to fund a host associated with the user/domain
8170: that was requested
8171:
8172: =back
8173:
8174: =head1 PUBLIC SUBROUTINES
8175:
8176: =head2 Session Environment Functions
8177:
8178: =over 4
8179:
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
8184: user makes during this session, also modifies the %env for the current
8185: process
8186:
8187: =item *
8188: X<delenv()>
8189: B<delenv($regexp)>: removes all items from the session
8190: environment file that matches the regular expression in $regexp. The
8191: values are also delted from the current processes %env.
8192:
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:
8200: =back
8201:
8202: =head2 User Information
8203:
8204: =over 4
8205:
8206: =item *
8207: X<queryauthenticate()>
8208: B<queryauthenticate($uname,$udom)>: try to determine user's current
8209: authentication scheme
8210:
8211: =item *
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.
8216:
8217: =item *
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.
8222:
8223: =item *
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)
8229:
8230: =item *
8231: X<idrget()>
8232: B<idrget($udom,@unames)>: find the IDs behind a list of
8233: usernames (returns hash: name=>id,name=>id)
8234:
8235: =item *
8236: X<idput()>
8237: B<idput($udom,%ids)>: store away a list of names and associated IDs
8238:
8239: =item *
8240: X<rolesinit()>
8241: B<rolesinit($udom,$username,$authhost)>: get user privileges
8242:
8243: =item *
8244: X<getsection()>
8245: B<getsection($udom,$uname,$cname)>: finds the section of student in the
8246: course $cname, return section name/number or '' for "not in course"
8247: and '-1' for "no section"
8248:
8249: =item *
8250: X<userenvironment()>
8251: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
8252: passed in @what from the requested user's environment, returns a hash
8253:
8254: =item *
8255: X<userlog_query()>
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.
8263:
8264: =back
8265:
8266: =head2 User Roles
8267:
8268: =over 4
8269:
8270: =item *
8271:
8272: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
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
8278: A: passphrase authentication needed
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:
8291: =item *
8292:
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.
8305:
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")
8317:
8318: =item *
8319:
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
8324:
8325: =item *
8326:
8327: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
8328:
8329: =item *
8330:
8331: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8332: modify user
8333:
8334: =item *
8335:
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:
8343: This call is essentially a wrapper for lonnet::modifyuser and
8344: lonnet::modify_student_enrollment
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
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:
8413:
8414: =item *
8415:
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
8419:
8420: =item *
8421:
8422: revokerole($udom,$uname,$url,$role) : revoke a role for url
8423:
8424: =item *
8425:
8426: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8427:
8428: =back
8429:
8430: =head2 Course Infomation
8431:
8432: =over 4
8433:
8434: =item *
8435:
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'
8440:
8441: =item *
8442:
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.
8447:
8448: =back
8449:
8450: =head2 Course Modification
8451:
8452: =over 4
8453:
8454: =item *
8455:
8456: writecoursepref($courseid,%prefs) : write preferences (environment
8457: database) for a course
8458:
8459: =item *
8460:
8461: createcourse($udom,$description,$url) : make/modify course
8462:
8463: =back
8464:
8465: =head2 Resource Subroutines
8466:
8467: =over 4
8468:
8469: =item *
8470:
8471: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
8472:
8473: =item *
8474:
8475: repcopy($filename) : subscribes to the requested file, and attempts to
8476: replicate from the owning library server, Might return
8477: 'unavailable', 'not_found', 'forbidden', 'ok', or
8478: 'bad_request', also attempts to grab the metadata for the
8479: resource. Expects the local filesystem pathname
8480: (/home/httpd/html/res/....)
8481:
8482: =back
8483:
8484: =head2 Resource Information
8485:
8486: =over 4
8487:
8488: =item *
8489:
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)
8499:
8500: =item *
8501:
8502: directcondval($number) : get current value of a condition; reads from a state
8503: string
8504:
8505: =item *
8506:
8507: condval($condidx) : value of condition index based on state
8508:
8509: =item *
8510:
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
8517:
8518: =item *
8519:
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
8523:
8524: =item *
8525:
8526: symbread($filename) : return symbolic list entry (filename argument optional);
8527: returns the data handle
8528:
8529: =item *
8530:
8531: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
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
8535: the course initial hash, and uses $env('request.course.id'}
8536:
8537:
8538: =item *
8539:
8540: symbclean($symb) : removes versions numbers from a symb, returns the
8541: cleaned symb
8542:
8543: =item *
8544:
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.
8547:
8548: =item *
8549:
8550: numval($salt) : return random seed value (addend for rndseed)
8551:
8552: =item *
8553:
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
8558:
8559: =item *
8560:
8561: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8562: unfakeable, receipt
8563:
8564: =item *
8565:
8566: receipt() : API to ireceipt working off of env values; given out to users
8567:
8568: =item *
8569:
8570: countacc($url) : count the number of accesses to a given URL
8571:
8572: =item *
8573:
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
8575:
8576: =item *
8577:
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)
8579:
8580: =item *
8581:
8582: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
8583:
8584: =item *
8585:
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
8594:
8595: =item *
8596:
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
8600: be derived from the env
8601:
8602: =item *
8603:
8604: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8605: uses critical subroutine
8606:
8607: =item *
8608:
8609: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8610: all args are optional
8611:
8612: =item *
8613:
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:
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
8639:
8640: =item *
8641:
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.
8646:
8647: =item *
8648:
8649: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8650: deltes all keys for $symb form the temporary storage hash.
8651:
8652: =item *
8653:
8654: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8655: reference filled in from namesp ($udom and $uname are optional)
8656:
8657: =item *
8658:
8659: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8660: namesp ($udom and $uname are optional)
8661:
8662: =item *
8663:
8664: dump($namespace,$udom,$uname,$regexp,$range) :
8665: dumps the complete (or key matching regexp) namespace into a hash
8666: ($udom, $uname, $regexp, $range are optional)
8667:
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)
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)
8680:
8681: =item *
8682:
8683: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8684: ($udom and $uname are optional)
8685:
8686: =item *
8687:
8688: cput($namespace,$storehash,$udom,$uname) : critical put
8689: ($udom and $uname are optional)
8690:
8691: =item *
8692:
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:
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)
8721:
8722: =item *
8723:
8724: log($udom,$name,$home,$message) : write to permanent log for user; use
8725: critical subroutine
8726:
8727: =item *
8728:
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).
8732:
8733: =item *
8734:
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)
8738:
8739: =back
8740:
8741: =head2 Network Status Functions
8742:
8743: =over 4
8744:
8745: =item *
8746:
8747: dirlist($uri) : return directory list based on URI
8748:
8749: =item *
8750:
8751: spareserver() : find server with least workload from spare.tab
8752:
8753: =back
8754:
8755: =head2 Apache Request
8756:
8757: =over 4
8758:
8759: =item *
8760:
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
8769:
8770: =item *
8771:
8772: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8773: and '&' separators, supports elements that are arrayrefs and hashrefs
8774:
8775: =item *
8776:
8777: hashref2str($hashref) : convert a hashref into a string complete with
8778: escaping and '=' and '&' separators, supports elements that are
8779: arrayrefs and hashrefs
8780:
8781: =item *
8782:
8783: arrayref2str($arrayref) : convert an arrayref into a string complete
8784: with escaping and '&' separators, supports elements that are arrayrefs
8785: and hashrefs
8786:
8787: =item *
8788:
8789: str2hash($string) : convert string to hash using unescaping and
8790: splitting on '=' and '&', supports elements that are arrayrefs and
8791: hashrefs
8792:
8793: =item *
8794:
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.
8806:
8807: =item *
8808:
8809: logtouch() : make sure the logfile, lonnet.log, exists
8810:
8811: =item *
8812:
8813: logthis() : append message to the normal lonnet.log file, it gets
8814: preiodically rolled over and deleted.
8815:
8816: =item *
8817:
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
8827:
8828: =item *
8829:
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.
8853:
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:
8864: =item *
8865:
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)
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:
8880: =back
8881:
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:
8891: formname - required - this is the name of the element in $env where the
8892: filename, and the contents of the file to create/modifed exist
8893: the filename is in $env{'form.'.$formname.'.filename'} and the
8894: contents of the file is located in $env{'form.'.$formname}
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:
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:
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)
8987:
8988: Internal notes:
8989:
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
9051:
9052: =back
9053:
9054: =head2 HTTP Helper Routines
9055:
9056: =over 4
9057:
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:
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:
9112: =item *
9113:
9114: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9115: as a PerlChildExitHandler
9116:
9117: =back
9118:
9119: =head2 Other
9120:
9121: =over 4
9122:
9123: =item *
9124:
9125: symblist($mapname,%newhash) : update symbolic storage links
9126:
9127: =back
9128:
9129: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>