File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.858:
download - view:
text,
annotated -
select for diffs
Tue Apr 3 17:51:50 2007 UTC (17 years, 5 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- lonsql
- Need to escape results from userlog queries (escaping of all results from lonsql eliminated in 1.50).
- Allow filtering of user's activity.log for 'Role'
- Include host in information returned for userlog query
- Autoupdate.pl
- &lonnet::get_my_roles() by default gets roles from nohist_userroles. Use in Autoupdate wants information about a user's own roles (from roles.db) - use context as argument
- warning messagea when username changed (assumes fixed student ID). prints to screen
for now (log to file would be preferred)
- lonnet.pm
- documentation for &userfileupload
- get_my_roles() now includes optional context which determines which db file is target for dump (default is nohist_userroles, context of 'userroles' sets target to roles.db
- documentation for &userlog_query() - now includes hostID
- documentation updated for &get_my_roles().
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.858 2007/04/03 17:51:50 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)=@_;
738: my $items='';
739: foreach my $item (@$storearr) {
740: $items.=&escape($item).'&';
741: }
742: $items=~s/\&$//;
743: if (!$udom) { $udom=$env{'user.domain'}; }
744: if (defined(&domain($udom,'primary'))) {
745: my $uhome=&domain($udom,'primary');
746: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
747: my @pairs=split(/\&/,$rep);
748: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
749: return @pairs;
750: }
751: my %returnhash=();
752: my $i=0;
753: foreach my $item (@$storearr) {
754: $returnhash{$item}=&thaw_unescape($pairs[$i]);
755: $i++;
756: }
757: return %returnhash;
758: } else {
759: &logthis("get_dom failed - no primary domain server for $udom");
760: }
761: }
762:
763: # -------------------------------------------- put items in domain db files
764:
765: sub put_dom {
766: my ($namespace,$storehash,$udom)=@_;
767: if (!$udom) { $udom=$env{'user.domain'}; }
768: if (defined(&domain($udom,'primary'))) {
769: my $uhome=&domain($udom,'primary');
770: my $items='';
771: foreach my $item (keys(%$storehash)) {
772: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
773: }
774: $items=~s/\&$//;
775: return &reply("putdom:$udom:$namespace:$items",$uhome);
776: } else {
777: &logthis("put_dom failed - no primary domain server for $udom");
778: }
779: }
780:
781: sub retrieve_inst_usertypes {
782: my ($udom) = @_;
783: my (%returnhash,@order);
784: if (defined(&domain($udom,'primary'))) {
785: my $uhome=&domain($udom,'primary');
786: my $rep=&reply("inst_usertypes:$udom",$uhome);
787: my ($hashitems,$orderitems) = split(/:/,$rep);
788: my @pairs=split(/\&/,$hashitems);
789: foreach my $item (@pairs) {
790: my ($key,$value)=split(/=/,$item,2);
791: $key = &unescape($key);
792: next if ($key =~ /^error: 2 /);
793: $returnhash{$key}=&thaw_unescape($value);
794: }
795: my @esc_order = split(/\&/,$orderitems);
796: foreach my $item (@esc_order) {
797: push(@order,&unescape($item));
798: }
799: } else {
800: &logthis("get_dom failed - no primary domain server for $udom");
801: }
802: return (\%returnhash,\@order);
803: }
804:
805: # --------------------------------------------------- Assign a key to a student
806:
807: sub assign_access_key {
808: #
809: # a valid key looks like uname:udom#comments
810: # comments are being appended
811: #
812: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
813: $kdom=
814: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
815: $knum=
816: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
817: $cdom=
818: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
819: $cnum=
820: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
821: $udom=$env{'user.name'} unless (defined($udom));
822: $uname=$env{'user.domain'} unless (defined($uname));
823: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
824: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
825: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
826: # assigned to this person
827: # - this should not happen,
828: # unless something went wrong
829: # the first time around
830: # ready to assign
831: $logentry=$1.'; '.$logentry;
832: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
833: $kdom,$knum) eq 'ok') {
834: # key now belongs to user
835: my $envkey='key.'.$cdom.'_'.$cnum;
836: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
837: &appenv('environment.'.$envkey => $ckey);
838: return 'ok';
839: } else {
840: return
841: 'error: Count not permanently assign key, will need to be re-entered later.';
842: }
843: } else {
844: return 'error: Could not assign key, try again later.';
845: }
846: } elsif (!$existing{$ckey}) {
847: # the key does not exist
848: return 'error: The key does not exist';
849: } else {
850: # the key is somebody else's
851: return 'error: The key is already in use';
852: }
853: }
854:
855: # ------------------------------------------ put an additional comment on a key
856:
857: sub comment_access_key {
858: #
859: # a valid key looks like uname:udom#comments
860: # comments are being appended
861: #
862: my ($ckey,$cdom,$cnum,$logentry)=@_;
863: $cdom=
864: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
865: $cnum=
866: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
867: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
868: if ($existing{$ckey}) {
869: $existing{$ckey}.='; '.$logentry;
870: # ready to assign
871: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
872: $cdom,$cnum) eq 'ok') {
873: return 'ok';
874: } else {
875: return 'error: Count not store comment.';
876: }
877: } else {
878: # the key does not exist
879: return 'error: The key does not exist';
880: }
881: }
882:
883: # ------------------------------------------------------ Generate a set of keys
884:
885: sub generate_access_keys {
886: my ($number,$cdom,$cnum,$logentry)=@_;
887: $cdom=
888: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
889: $cnum=
890: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
891: unless (&allowed('mky',$cdom)) { return 0; }
892: unless (($cdom) && ($cnum)) { return 0; }
893: if ($number>10000) { return 0; }
894: sleep(2); # make sure don't get same seed twice
895: srand(time()^($$+($$<<15))); # from "Programming Perl"
896: my $total=0;
897: for (my $i=1;$i<=$number;$i++) {
898: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
899: sprintf("%lx",int(100000*rand)).'-'.
900: sprintf("%lx",int(100000*rand));
901: $newkey=~s/1/g/g; # folks mix up 1 and l
902: $newkey=~s/0/h/g; # and also 0 and O
903: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
904: if ($existing{$newkey}) {
905: $i--;
906: } else {
907: if (&put('accesskeys',
908: { $newkey => '# generated '.localtime().
909: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
910: '; '.$logentry },
911: $cdom,$cnum) eq 'ok') {
912: $total++;
913: }
914: }
915: }
916: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
917: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
918: return $total;
919: }
920:
921: # ------------------------------------------------------- Validate an accesskey
922:
923: sub validate_access_key {
924: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
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: $udom=$env{'user.domain'} unless (defined($udom));
930: $uname=$env{'user.name'} unless (defined($uname));
931: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
932: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
933: }
934:
935: # ------------------------------------- Find the section of student in a course
936: sub devalidate_getsection_cache {
937: my ($udom,$unam,$courseid)=@_;
938: my $hashid="$udom:$unam:$courseid";
939: &devalidate_cache_new('getsection',$hashid);
940: }
941:
942: sub courseid_to_courseurl {
943: my ($courseid) = @_;
944: #already url style courseid
945: return $courseid if ($courseid =~ m{^/});
946:
947: if (exists($env{'course.'.$courseid.'.num'})) {
948: my $cnum = $env{'course.'.$courseid.'.num'};
949: my $cdom = $env{'course.'.$courseid.'.domain'};
950: return "/$cdom/$cnum";
951: }
952:
953: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
954: if (exists($courseinfo{'num'})) {
955: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
956: }
957:
958: return undef;
959: }
960:
961: sub getsection {
962: my ($udom,$unam,$courseid)=@_;
963: my $cachetime=1800;
964:
965: my $hashid="$udom:$unam:$courseid";
966: my ($result,$cached)=&is_cached_new('getsection',$hashid);
967: if (defined($cached)) { return $result; }
968:
969: my %Pending;
970: my %Expired;
971: #
972: # Each role can either have not started yet (pending), be active,
973: # or have expired.
974: #
975: # If there is an active role, we are done.
976: #
977: # If there is more than one role which has not started yet,
978: # choose the one which will start sooner
979: # If there is one role which has not started yet, return it.
980: #
981: # If there is more than one expired role, choose the one which ended last.
982: # If there is a role which has expired, return it.
983: #
984: $courseid = &courseid_to_courseurl($courseid);
985: my %roleshash = &dump('roles',$udom,$unam,$courseid);
986: foreach my $key (keys(%roleshash)) {
987: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
988: my $section=$1;
989: if ($key eq $courseid.'_st') { $section=''; }
990: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
991: my $now=time;
992: if (defined($end) && $end && ($now > $end)) {
993: $Expired{$end}=$section;
994: next;
995: }
996: if (defined($start) && $start && ($now < $start)) {
997: $Pending{$start}=$section;
998: next;
999: }
1000: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1001: }
1002: #
1003: # Presumedly there will be few matching roles from the above
1004: # loop and the sorting time will be negligible.
1005: if (scalar(keys(%Pending))) {
1006: my ($time) = sort {$a <=> $b} keys(%Pending);
1007: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1008: }
1009: if (scalar(keys(%Expired))) {
1010: my @sorted = sort {$a <=> $b} keys(%Expired);
1011: my $time = pop(@sorted);
1012: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1013: }
1014: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1015: }
1016:
1017: sub save_cache {
1018: &purge_remembered();
1019: #&Apache::loncommon::validate_page();
1020: undef(%env);
1021: undef($env_loaded);
1022: }
1023:
1024: my $to_remember=-1;
1025: my %remembered;
1026: my %accessed;
1027: my $kicks=0;
1028: my $hits=0;
1029: sub make_key {
1030: my ($name,$id) = @_;
1031: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1032: return &escape($name.':'.$id);
1033: }
1034:
1035: sub devalidate_cache_new {
1036: my ($name,$id,$debug) = @_;
1037: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1038: $id=&make_key($name,$id);
1039: $memcache->delete($id);
1040: delete($remembered{$id});
1041: delete($accessed{$id});
1042: }
1043:
1044: sub is_cached_new {
1045: my ($name,$id,$debug) = @_;
1046: $id=&make_key($name,$id);
1047: if (exists($remembered{$id})) {
1048: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1049: $accessed{$id}=[&gettimeofday()];
1050: $hits++;
1051: return ($remembered{$id},1);
1052: }
1053: my $value = $memcache->get($id);
1054: if (!(defined($value))) {
1055: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1056: return (undef,undef);
1057: }
1058: if ($value eq '__undef__') {
1059: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1060: $value=undef;
1061: }
1062: &make_room($id,$value,$debug);
1063: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1064: return ($value,1);
1065: }
1066:
1067: sub do_cache_new {
1068: my ($name,$id,$value,$time,$debug) = @_;
1069: $id=&make_key($name,$id);
1070: my $setvalue=$value;
1071: if (!defined($setvalue)) {
1072: $setvalue='__undef__';
1073: }
1074: if (!defined($time) ) {
1075: $time=600;
1076: }
1077: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1078: $memcache->set($id,$setvalue,$time);
1079: # need to make a copy of $value
1080: #&make_room($id,$value,$debug);
1081: return $value;
1082: }
1083:
1084: sub make_room {
1085: my ($id,$value,$debug)=@_;
1086: $remembered{$id}=$value;
1087: if ($to_remember<0) { return; }
1088: $accessed{$id}=[&gettimeofday()];
1089: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1090: my $to_kick;
1091: my $max_time=0;
1092: foreach my $other (keys(%accessed)) {
1093: if (&tv_interval($accessed{$other}) > $max_time) {
1094: $to_kick=$other;
1095: $max_time=&tv_interval($accessed{$other});
1096: }
1097: }
1098: delete($remembered{$to_kick});
1099: delete($accessed{$to_kick});
1100: $kicks++;
1101: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1102: return;
1103: }
1104:
1105: sub purge_remembered {
1106: #&logthis("Tossing ".scalar(keys(%remembered)));
1107: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1108: undef(%remembered);
1109: undef(%accessed);
1110: }
1111: # ------------------------------------- Read an entry from a user's environment
1112:
1113: sub userenvironment {
1114: my ($udom,$unam,@what)=@_;
1115: my %returnhash=();
1116: my @answer=split(/\&/,
1117: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1118: &homeserver($unam,$udom)));
1119: my $i;
1120: for ($i=0;$i<=$#what;$i++) {
1121: $returnhash{$what[$i]}=&unescape($answer[$i]);
1122: }
1123: return %returnhash;
1124: }
1125:
1126: # ---------------------------------------------------------- Get a studentphoto
1127: sub studentphoto {
1128: my ($udom,$unam,$ext) = @_;
1129: my $home=&Apache::lonnet::homeserver($unam,$udom);
1130: if (defined($env{'request.course.id'})) {
1131: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1132: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1133: return(&retrievestudentphoto($udom,$unam,$ext));
1134: } else {
1135: my ($result,$perm_reqd)=
1136: &Apache::lonnet::auto_photo_permission($unam,$udom);
1137: if ($result eq 'ok') {
1138: if (!($perm_reqd eq 'yes')) {
1139: return(&retrievestudentphoto($udom,$unam,$ext));
1140: }
1141: }
1142: }
1143: }
1144: } else {
1145: my ($result,$perm_reqd) =
1146: &Apache::lonnet::auto_photo_permission($unam,$udom);
1147: if ($result eq 'ok') {
1148: if (!($perm_reqd eq 'yes')) {
1149: return(&retrievestudentphoto($udom,$unam,$ext));
1150: }
1151: }
1152: }
1153: return '/adm/lonKaputt/lonlogo_broken.gif';
1154: }
1155:
1156: sub retrievestudentphoto {
1157: my ($udom,$unam,$ext,$type) = @_;
1158: my $home=&Apache::lonnet::homeserver($unam,$udom);
1159: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1160: if ($ret eq 'ok') {
1161: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1162: if ($type eq 'thumbnail') {
1163: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1164: }
1165: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1166: return $tokenurl;
1167: } else {
1168: if ($type eq 'thumbnail') {
1169: return '/adm/lonKaputt/genericstudent_tn.gif';
1170: } else {
1171: return '/adm/lonKaputt/lonlogo_broken.gif';
1172: }
1173: }
1174: }
1175:
1176: # -------------------------------------------------------------------- New chat
1177:
1178: sub chatsend {
1179: my ($newentry,$anon,$group)=@_;
1180: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1181: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1182: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1183: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1184: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1185: &escape($newentry)).':'.$group,$chome);
1186: }
1187:
1188: # ------------------------------------------ Find current version of a resource
1189:
1190: sub getversion {
1191: my $fname=&clutter(shift);
1192: unless ($fname=~/^\/res\//) { return -1; }
1193: return ¤tversion(&filelocation('',$fname));
1194: }
1195:
1196: sub currentversion {
1197: my $fname=shift;
1198: my ($result,$cached)=&is_cached_new('resversion',$fname);
1199: if (defined($cached)) { return $result; }
1200: my $author=$fname;
1201: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1202: my ($udom,$uname)=split(/\//,$author);
1203: my $home=homeserver($uname,$udom);
1204: if ($home eq 'no_host') {
1205: return -1;
1206: }
1207: my $answer=reply("currentversion:$fname",$home);
1208: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1209: return -1;
1210: }
1211: return &do_cache_new('resversion',$fname,$answer,600);
1212: }
1213:
1214: # ----------------------------- Subscribe to a resource, return URL if possible
1215:
1216: sub subscribe {
1217: my $fname=shift;
1218: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1219: $fname=~s/[\n\r]//g;
1220: my $author=$fname;
1221: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1222: my ($udom,$uname)=split(/\//,$author);
1223: my $home=homeserver($uname,$udom);
1224: if ($home eq 'no_host') {
1225: return 'not_found';
1226: }
1227: my $answer=reply("sub:$fname",$home);
1228: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1229: $answer.=' by '.$home;
1230: }
1231: return $answer;
1232: }
1233:
1234: # -------------------------------------------------------------- Replicate file
1235:
1236: sub repcopy {
1237: my $filename=shift;
1238: $filename=~s/\/+/\//g;
1239: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1240: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1241: if ($filename=~m|^/home/httpd/html/userfiles/| or
1242: $filename=~m -^/*(uploaded|editupload)/-) {
1243: return &repcopy_userfile($filename);
1244: }
1245: $filename=~s/[\n\r]//g;
1246: my $transname="$filename.in.transfer";
1247: # FIXME: this should flock
1248: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1249: my $remoteurl=subscribe($filename);
1250: if ($remoteurl =~ /^con_lost by/) {
1251: &logthis("Subscribe returned $remoteurl: $filename");
1252: return 'unavailable';
1253: } elsif ($remoteurl eq 'not_found') {
1254: #&logthis("Subscribe returned not_found: $filename");
1255: return 'not_found';
1256: } elsif ($remoteurl =~ /^rejected by/) {
1257: &logthis("Subscribe returned $remoteurl: $filename");
1258: return 'forbidden';
1259: } elsif ($remoteurl eq 'directory') {
1260: return 'ok';
1261: } else {
1262: my $author=$filename;
1263: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1264: my ($udom,$uname)=split(/\//,$author);
1265: my $home=homeserver($uname,$udom);
1266: unless ($home eq $perlvar{'lonHostID'}) {
1267: my @parts=split(/\//,$filename);
1268: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1269: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1270: &logthis("Malconfiguration for replication: $filename");
1271: return 'bad_request';
1272: }
1273: my $count;
1274: for ($count=5;$count<$#parts;$count++) {
1275: $path.="/$parts[$count]";
1276: if ((-e $path)!=1) {
1277: mkdir($path,0777);
1278: }
1279: }
1280: my $ua=new LWP::UserAgent;
1281: my $request=new HTTP::Request('GET',"$remoteurl");
1282: my $response=$ua->request($request,$transname);
1283: if ($response->is_error()) {
1284: unlink($transname);
1285: my $message=$response->status_line;
1286: &logthis("<font color=\"blue\">WARNING:"
1287: ." LWP get: $message: $filename</font>");
1288: return 'unavailable';
1289: } else {
1290: if ($remoteurl!~/\.meta$/) {
1291: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1292: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1293: if ($mresponse->is_error()) {
1294: unlink($filename.'.meta');
1295: &logthis(
1296: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1297: }
1298: }
1299: rename($transname,$filename);
1300: return 'ok';
1301: }
1302: }
1303: }
1304: }
1305:
1306: # ------------------------------------------------ Get server side include body
1307: sub ssi_body {
1308: my ($filelink,%form)=@_;
1309: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1310: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1311: }
1312: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1313: &ssi($filelink,%form));
1314: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1315: $output=~s/^.*?\<body[^\>]*\>//si;
1316: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1317: return $output;
1318: }
1319:
1320: # --------------------------------------------------------- Server Side Include
1321:
1322: sub absolute_url {
1323: my ($host_name) = @_;
1324: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1325: if ($host_name eq '') {
1326: $host_name = $ENV{'SERVER_NAME'};
1327: }
1328: return $protocol.$host_name;
1329: }
1330:
1331: sub ssi {
1332:
1333: my ($fn,%form)=@_;
1334:
1335: my $ua=new LWP::UserAgent;
1336:
1337: my $request;
1338:
1339: $form{'no_update_last_known'}=1;
1340:
1341: if (%form) {
1342: $request=new HTTP::Request('POST',&absolute_url().$fn);
1343: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1344: } else {
1345: $request=new HTTP::Request('GET',&absolute_url().$fn);
1346: }
1347:
1348: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1349: my $response=$ua->request($request);
1350:
1351: return $response->content;
1352: }
1353:
1354: sub externalssi {
1355: my ($url)=@_;
1356: my $ua=new LWP::UserAgent;
1357: my $request=new HTTP::Request('GET',$url);
1358: my $response=$ua->request($request);
1359: return $response->content;
1360: }
1361:
1362: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1363:
1364: sub allowuploaded {
1365: my ($srcurl,$url)=@_;
1366: $url=&clutter(&declutter($url));
1367: my $dir=$url;
1368: $dir=~s/\/[^\/]+$//;
1369: my %httpref=();
1370: my $httpurl=&hreflocation('',$url);
1371: $httpref{'httpref.'.$httpurl}=$srcurl;
1372: &Apache::lonnet::appenv(%httpref);
1373: }
1374:
1375: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1376: # input: action, courseID, current domain, intended
1377: # path to file, source of file, instruction to parse file for objects,
1378: # ref to hash for embedded objects,
1379: # ref to hash for codebase of java objects.
1380: #
1381: # output: url to file (if action was uploaddoc),
1382: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1383: #
1384: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1385: # course.
1386: #
1387: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1388: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1389: # course's home server.
1390: #
1391: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1392: # be copied from $source (current location) to
1393: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1394: # and will then be copied to
1395: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1396: # course's home server.
1397: #
1398: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1399: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1400: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1401: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1402: # in course's home server.
1403: #
1404:
1405: sub process_coursefile {
1406: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1407: my $fetchresult;
1408: my $home=&homeserver($docuname,$docudom);
1409: if ($action eq 'propagate') {
1410: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1411: $home);
1412: } else {
1413: my $fpath = '';
1414: my $fname = $file;
1415: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1416: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1417: my $filepath = &build_filepath($fpath);
1418: if ($action eq 'copy') {
1419: if ($source eq '') {
1420: $fetchresult = 'no source file';
1421: return $fetchresult;
1422: } else {
1423: my $destination = $filepath.'/'.$fname;
1424: rename($source,$destination);
1425: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1426: $home);
1427: }
1428: } elsif ($action eq 'uploaddoc') {
1429: open(my $fh,'>'.$filepath.'/'.$fname);
1430: print $fh $env{'form.'.$source};
1431: close($fh);
1432: if ($parser eq 'parse') {
1433: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1434: unless ($parse_result eq 'ok') {
1435: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1436: }
1437: }
1438: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1439: $home);
1440: if ($fetchresult eq 'ok') {
1441: return '/uploaded/'.$fpath.'/'.$fname;
1442: } else {
1443: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1444: ' to host '.$home.': '.$fetchresult);
1445: return '/adm/notfound.html';
1446: }
1447: }
1448: }
1449: unless ( $fetchresult eq 'ok') {
1450: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1451: ' to host '.$home.': '.$fetchresult);
1452: }
1453: return $fetchresult;
1454: }
1455:
1456: sub build_filepath {
1457: my ($fpath) = @_;
1458: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1459: unless ($fpath eq '') {
1460: my @parts=split('/',$fpath);
1461: foreach my $part (@parts) {
1462: $filepath.= '/'.$part;
1463: if ((-e $filepath)!=1) {
1464: mkdir($filepath,0777);
1465: }
1466: }
1467: }
1468: return $filepath;
1469: }
1470:
1471: sub store_edited_file {
1472: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1473: my $file = $primary_url;
1474: $file =~ s#^/uploaded/$docudom/$docuname/##;
1475: my $fpath = '';
1476: my $fname = $file;
1477: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1478: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1479: my $filepath = &build_filepath($fpath);
1480: open(my $fh,'>'.$filepath.'/'.$fname);
1481: print $fh $content;
1482: close($fh);
1483: my $home=&homeserver($docuname,$docudom);
1484: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1485: $home);
1486: if ($$fetchresult eq 'ok') {
1487: return '/uploaded/'.$fpath.'/'.$fname;
1488: } else {
1489: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1490: ' to host '.$home.': '.$$fetchresult);
1491: return '/adm/notfound.html';
1492: }
1493: }
1494:
1495: sub clean_filename {
1496: my ($fname,$args)=@_;
1497: # Replace Windows backslashes by forward slashes
1498: $fname=~s/\\/\//g;
1499: if (!$args->{'keep_path'}) {
1500: # Get rid of everything but the actual filename
1501: $fname=~s/^.*\/([^\/]+)$/$1/;
1502: }
1503: # Replace spaces by underscores
1504: $fname=~s/\s+/\_/g;
1505: # Replace all other weird characters by nothing
1506: $fname=~s{[^/\w\.\-]}{}g;
1507: # Replace all .\d. sequences with _\d. so they no longer look like version
1508: # numbers
1509: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1510: return $fname;
1511: }
1512:
1513: # --------------- Take an uploaded file and put it into the userfiles directory
1514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1515: # the desired filenam is in $env{"form.$formname.filename"}
1516: # $coursedoc - if true up to the current course
1517: # if false
1518: # $subdir - directory in userfile to store the file into
1519: # $parser - instruction to parse file for objects ($parser = parse)
1520: # $allfiles - reference to hash for embedded objects
1521: # $codebase - reference to hash for codebase of java objects
1522: # $desuname - username for permanent storage of uploaded file
1523: # $dsetudom - domain for permanaent storage of uploaded file
1524: #
1525: # output: url of file in userspace, or error: <message>
1526: # or /adm/notfound.html if failure to upload occurse
1527:
1528:
1529: sub userfileupload {
1530: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1531: if (!defined($subdir)) { $subdir='unknown'; }
1532: my $fname=$env{'form.'.$formname.'.filename'};
1533: $fname=&clean_filename($fname);
1534: # See if there is anything left
1535: unless ($fname) { return 'error: no uploaded file'; }
1536: chop($env{'form.'.$formname});
1537: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1538: my $now = time;
1539: my $filepath = 'tmp/helprequests/'.$now;
1540: my @parts=split(/\//,$filepath);
1541: my $fullpath = $perlvar{'lonDaemons'};
1542: for (my $i=0;$i<@parts;$i++) {
1543: $fullpath .= '/'.$parts[$i];
1544: if ((-e $fullpath)!=1) {
1545: mkdir($fullpath,0777);
1546: }
1547: }
1548: open(my $fh,'>'.$fullpath.'/'.$fname);
1549: print $fh $env{'form.'.$formname};
1550: close($fh);
1551: return $fullpath.'/'.$fname;
1552: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1553: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1554: '_'.$env{'user.domain'}.'/pending';
1555: my @parts=split(/\//,$filepath);
1556: my $fullpath = $perlvar{'lonDaemons'};
1557: for (my $i=0;$i<@parts;$i++) {
1558: $fullpath .= '/'.$parts[$i];
1559: if ((-e $fullpath)!=1) {
1560: mkdir($fullpath,0777);
1561: }
1562: }
1563: open(my $fh,'>'.$fullpath.'/'.$fname);
1564: print $fh $env{'form.'.$formname};
1565: close($fh);
1566: return $fullpath.'/'.$fname;
1567: }
1568:
1569: # Create the directory if not present
1570: $fname="$subdir/$fname";
1571: if ($coursedoc) {
1572: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1573: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1574: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1575: return &finishuserfileupload($docuname,$docudom,
1576: $formname,$fname,$parser,$allfiles,
1577: $codebase);
1578: } else {
1579: $fname=$env{'form.folder'}.'/'.$fname;
1580: return &process_coursefile('uploaddoc',$docuname,$docudom,
1581: $fname,$formname,$parser,
1582: $allfiles,$codebase);
1583: }
1584: } elsif (defined($destuname)) {
1585: my $docuname=$destuname;
1586: my $docudom=$destudom;
1587: return &finishuserfileupload($docuname,$docudom,$formname,
1588: $fname,$parser,$allfiles,$codebase);
1589:
1590: } else {
1591: my $docuname=$env{'user.name'};
1592: my $docudom=$env{'user.domain'};
1593: if (exists($env{'form.group'})) {
1594: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1595: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1596: }
1597: return &finishuserfileupload($docuname,$docudom,$formname,
1598: $fname,$parser,$allfiles,$codebase);
1599: }
1600: }
1601:
1602: sub finishuserfileupload {
1603: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1604: my $path=$docudom.'/'.$docuname.'/';
1605: my $filepath=$perlvar{'lonDocRoot'};
1606: my ($fnamepath,$file);
1607: $file=$fname;
1608: if ($fname=~m|/|) {
1609: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1610: $path.=$fnamepath.'/';
1611: }
1612: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1613: my $count;
1614: for ($count=4;$count<=$#parts;$count++) {
1615: $filepath.="/$parts[$count]";
1616: if ((-e $filepath)!=1) {
1617: mkdir($filepath,0777);
1618: }
1619: }
1620: # Save the file
1621: {
1622: if (!open(FH,'>'.$filepath.'/'.$file)) {
1623: &logthis('Failed to create '.$filepath.'/'.$file);
1624: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1625: return '/adm/notfound.html';
1626: }
1627: if (!print FH ($env{'form.'.$formname})) {
1628: &logthis('Failed to write to '.$filepath.'/'.$file);
1629: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1630: return '/adm/notfound.html';
1631: }
1632: close(FH);
1633: }
1634: if ($parser eq 'parse') {
1635: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1636: $codebase);
1637: unless ($parse_result eq 'ok') {
1638: &logthis('Failed to parse '.$filepath.$file.
1639: ' for embedded media: '.$parse_result);
1640: }
1641: }
1642:
1643: # Notify homeserver to grep it
1644: #
1645: my $docuhome=&homeserver($docuname,$docudom);
1646: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1647: if ($fetchresult eq 'ok') {
1648: #
1649: # Return the URL to it
1650: return '/uploaded/'.$path.$file;
1651: } else {
1652: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1653: ': '.$fetchresult);
1654: return '/adm/notfound.html';
1655: }
1656: }
1657:
1658: sub extract_embedded_items {
1659: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1660: my @state = ();
1661: my %javafiles = (
1662: codebase => '',
1663: code => '',
1664: archive => ''
1665: );
1666: my %mediafiles = (
1667: src => '',
1668: movie => '',
1669: );
1670: my $p;
1671: if ($content) {
1672: $p = HTML::LCParser->new($content);
1673: } else {
1674: $p = HTML::LCParser->new($filepath.'/'.$file);
1675: }
1676: while (my $t=$p->get_token()) {
1677: if ($t->[0] eq 'S') {
1678: my ($tagname, $attr) = ($t->[1],$t->[2]);
1679: push (@state, $tagname);
1680: if (lc($tagname) eq 'allow') {
1681: &add_filetype($allfiles,$attr->{'src'},'src');
1682: }
1683: if (lc($tagname) eq 'img') {
1684: &add_filetype($allfiles,$attr->{'src'},'src');
1685: }
1686: if (lc($tagname) eq 'script') {
1687: if ($attr->{'archive'} =~ /\.jar$/i) {
1688: &add_filetype($allfiles,$attr->{'archive'},'archive');
1689: } else {
1690: &add_filetype($allfiles,$attr->{'src'},'src');
1691: }
1692: }
1693: if (lc($tagname) eq 'link') {
1694: if (lc($attr->{'rel'}) eq 'stylesheet') {
1695: &add_filetype($allfiles,$attr->{'href'},'href');
1696: }
1697: }
1698: if (lc($tagname) eq 'object' ||
1699: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1700: foreach my $item (keys(%javafiles)) {
1701: $javafiles{$item} = '';
1702: }
1703: }
1704: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1705: my $name = lc($attr->{'name'});
1706: foreach my $item (keys(%javafiles)) {
1707: if ($name eq $item) {
1708: $javafiles{$item} = $attr->{'value'};
1709: last;
1710: }
1711: }
1712: foreach my $item (keys(%mediafiles)) {
1713: if ($name eq $item) {
1714: &add_filetype($allfiles, $attr->{'value'}, 'value');
1715: last;
1716: }
1717: }
1718: }
1719: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1720: foreach my $item (keys(%javafiles)) {
1721: if ($attr->{$item}) {
1722: $javafiles{$item} = $attr->{$item};
1723: last;
1724: }
1725: }
1726: foreach my $item (keys(%mediafiles)) {
1727: if ($attr->{$item}) {
1728: &add_filetype($allfiles,$attr->{$item},$item);
1729: last;
1730: }
1731: }
1732: }
1733: } elsif ($t->[0] eq 'E') {
1734: my ($tagname) = ($t->[1]);
1735: if ($javafiles{'codebase'} ne '') {
1736: $javafiles{'codebase'} .= '/';
1737: }
1738: if (lc($tagname) eq 'applet' ||
1739: lc($tagname) eq 'object' ||
1740: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1741: ) {
1742: foreach my $item (keys(%javafiles)) {
1743: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1744: my $file=$javafiles{'codebase'}.$javafiles{$item};
1745: &add_filetype($allfiles,$file,$item);
1746: }
1747: }
1748: }
1749: pop @state;
1750: }
1751: }
1752: return 'ok';
1753: }
1754:
1755: sub add_filetype {
1756: my ($allfiles,$file,$type)=@_;
1757: if (exists($allfiles->{$file})) {
1758: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1759: push(@{$allfiles->{$file}}, &escape($type));
1760: }
1761: } else {
1762: @{$allfiles->{$file}} = (&escape($type));
1763: }
1764: }
1765:
1766: sub removeuploadedurl {
1767: my ($url)=@_;
1768: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1769: return &removeuserfile($uname,$udom,$fname);
1770: }
1771:
1772: sub removeuserfile {
1773: my ($docuname,$docudom,$fname)=@_;
1774: my $home=&homeserver($docuname,$docudom);
1775: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1776: if ($result eq 'ok') {
1777: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1778: my $metafile = $fname.'.meta';
1779: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1780: my $url = "/uploaded/$docudom/$docuname/$fname";
1781: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1782: my $sqlresult =
1783: &update_portfolio_table($docuname,$docudom,$file,
1784: 'portfolio_metadata',$group,
1785: 'delete');
1786: }
1787: }
1788: return $result;
1789: }
1790:
1791: sub mkdiruserfile {
1792: my ($docuname,$docudom,$dir)=@_;
1793: my $home=&homeserver($docuname,$docudom);
1794: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1795: }
1796:
1797: sub renameuserfile {
1798: my ($docuname,$docudom,$old,$new)=@_;
1799: my $home=&homeserver($docuname,$docudom);
1800: my $result = &reply("renameuserfile:$docudom:$docuname:".
1801: &escape("$old").':'.&escape("$new"),$home);
1802: if ($result eq 'ok') {
1803: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1804: my $oldmeta = $old.'.meta';
1805: my $newmeta = $new.'.meta';
1806: my $metaresult =
1807: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1808: my $url = "/uploaded/$docudom/$docuname/$old";
1809: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1810: my $sqlresult =
1811: &update_portfolio_table($docuname,$docudom,$file,
1812: 'portfolio_metadata',$group,
1813: 'delete');
1814: }
1815: }
1816: return $result;
1817: }
1818:
1819: # ------------------------------------------------------------------------- Log
1820:
1821: sub log {
1822: my ($dom,$nam,$hom,$what)=@_;
1823: return critical("log:$dom:$nam:$what",$hom);
1824: }
1825:
1826: # ------------------------------------------------------------------ Course Log
1827: #
1828: # This routine flushes several buffers of non-mission-critical nature
1829: #
1830:
1831: sub flushcourselogs {
1832: &logthis('Flushing log buffers');
1833: #
1834: # course logs
1835: # This is a log of all transactions in a course, which can be used
1836: # for data mining purposes
1837: #
1838: # It also collects the courseid database, which lists last transaction
1839: # times and course titles for all courseids
1840: #
1841: my %courseidbuffer=();
1842: foreach my $crsid (keys %courselogs) {
1843: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1844: &escape($courselogs{$crsid}),
1845: $coursehombuf{$crsid}) eq 'ok') {
1846: delete $courselogs{$crsid};
1847: } else {
1848: &logthis('Failed to flush log buffer for '.$crsid);
1849: if (length($courselogs{$crsid})>40000) {
1850: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1851: " exceeded maximum size, deleting.</font>");
1852: delete $courselogs{$crsid};
1853: }
1854: }
1855: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1856: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1857: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1858: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1859: } else {
1860: $courseidbuffer{$coursehombuf{$crsid}}=
1861: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1862: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1863: }
1864: }
1865: #
1866: # Write course id database (reverse lookup) to homeserver of courses
1867: # Is used in pickcourse
1868: #
1869: foreach my $crs_home (keys(%courseidbuffer)) {
1870: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1871: $crs_home);
1872: }
1873: #
1874: # File accesses
1875: # Writes to the dynamic metadata of resources to get hit counts, etc.
1876: #
1877: foreach my $entry (keys(%accesshash)) {
1878: if ($entry =~ /___count$/) {
1879: my ($dom,$name);
1880: ($dom,$name,undef)=
1881: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1882: if (! defined($dom) || $dom eq '' ||
1883: ! defined($name) || $name eq '') {
1884: my $cid = $env{'request.course.id'};
1885: $dom = $env{'request.'.$cid.'.domain'};
1886: $name = $env{'request.'.$cid.'.num'};
1887: }
1888: my $value = $accesshash{$entry};
1889: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1890: my %temphash=($url => $value);
1891: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1892: if ($result eq 'ok') {
1893: delete $accesshash{$entry};
1894: } elsif ($result eq 'unknown_cmd') {
1895: # Target server has old code running on it.
1896: my %temphash=($entry => $value);
1897: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1898: delete $accesshash{$entry};
1899: }
1900: }
1901: } else {
1902: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1903: my %temphash=($entry => $accesshash{$entry});
1904: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1905: delete $accesshash{$entry};
1906: }
1907: }
1908: }
1909: #
1910: # Roles
1911: # Reverse lookup of user roles for course faculty/staff and co-authorship
1912: #
1913: foreach my $entry (keys(%userrolehash)) {
1914: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1915: split(/\:/,$entry);
1916: if (&Apache::lonnet::put('nohist_userroles',
1917: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1918: $rudom,$runame) eq 'ok') {
1919: delete $userrolehash{$entry};
1920: }
1921: }
1922: #
1923: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1924: #
1925: my %domrolebuffer = ();
1926: foreach my $entry (keys %domainrolehash) {
1927: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1928: if ($domrolebuffer{$rudom}) {
1929: $domrolebuffer{$rudom}.='&'.&escape($entry).
1930: '='.&escape($domainrolehash{$entry});
1931: } else {
1932: $domrolebuffer{$rudom}.=&escape($entry).
1933: '='.&escape($domainrolehash{$entry});
1934: }
1935: delete $domainrolehash{$entry};
1936: }
1937: foreach my $dom (keys(%domrolebuffer)) {
1938: my %servers = &get_servers($dom,'library');
1939: foreach my $tryserver (keys(%servers)) {
1940: unless (&reply('domroleput:'.$dom.':'.
1941: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1942: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1943: }
1944: }
1945: }
1946: $dumpcount++;
1947: }
1948:
1949: sub courselog {
1950: my $what=shift;
1951: $what=time.':'.$what;
1952: unless ($env{'request.course.id'}) { return ''; }
1953: $coursedombuf{$env{'request.course.id'}}=
1954: $env{'course.'.$env{'request.course.id'}.'.domain'};
1955: $coursenumbuf{$env{'request.course.id'}}=
1956: $env{'course.'.$env{'request.course.id'}.'.num'};
1957: $coursehombuf{$env{'request.course.id'}}=
1958: $env{'course.'.$env{'request.course.id'}.'.home'};
1959: $coursedescrbuf{$env{'request.course.id'}}=
1960: $env{'course.'.$env{'request.course.id'}.'.description'};
1961: $courseinstcodebuf{$env{'request.course.id'}}=
1962: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1963: $courseownerbuf{$env{'request.course.id'}}=
1964: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1965: $coursetypebuf{$env{'request.course.id'}}=
1966: $env{'course.'.$env{'request.course.id'}.'.type'};
1967: if (defined $courselogs{$env{'request.course.id'}}) {
1968: $courselogs{$env{'request.course.id'}}.='&'.$what;
1969: } else {
1970: $courselogs{$env{'request.course.id'}}.=$what;
1971: }
1972: if (length($courselogs{$env{'request.course.id'}})>4048) {
1973: &flushcourselogs();
1974: }
1975: }
1976:
1977: sub courseacclog {
1978: my $fnsymb=shift;
1979: unless ($env{'request.course.id'}) { return ''; }
1980: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1981: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1982: $what.=':POST';
1983: # FIXME: Probably ought to escape things....
1984: foreach my $key (keys(%env)) {
1985: if ($key=~/^form\.(.*)/) {
1986: $what.=':'.$1.'='.$env{$key};
1987: }
1988: }
1989: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1990: # FIXME: We should not be depending on a form parameter that someone
1991: # editing lonsearchcat.pm might change in the future.
1992: if ($env{'form.phase'} eq 'course_search') {
1993: $what.= ':POST';
1994: # FIXME: Probably ought to escape things....
1995: foreach my $element ('courseexp','crsfulltext','crsrelated',
1996: 'crsdiscuss') {
1997: $what.=':'.$element.'='.$env{'form.'.$element};
1998: }
1999: }
2000: }
2001: &courselog($what);
2002: }
2003:
2004: sub countacc {
2005: my $url=&declutter(shift);
2006: return if (! defined($url) || $url eq '');
2007: unless ($env{'request.course.id'}) { return ''; }
2008: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2009: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2010: $accesshash{$key}++;
2011: }
2012:
2013: sub linklog {
2014: my ($from,$to)=@_;
2015: $from=&declutter($from);
2016: $to=&declutter($to);
2017: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2018: $accesshash{$to.'___'.$from.'___goto'}=1;
2019: }
2020:
2021: sub userrolelog {
2022: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2023: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2024: ($trole=~/^in/) || ($trole=~/^cc/) ||
2025: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2026: ($trole=~/^ta/)) {
2027: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2028: $userrolehash
2029: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2030: =$tend.':'.$tstart;
2031: }
2032: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2033: ($trole=~/^li/) || ($trole=~/^li/) ||
2034: ($trole=~/^au/) || ($trole=~/^dg/) ||
2035: ($trole=~/^sc/)) {
2036: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2037: $domainrolehash
2038: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2039: = $tend.':'.$tstart;
2040: }
2041: }
2042:
2043: sub get_course_adv_roles {
2044: my $cid=shift;
2045: $cid=$env{'request.course.id'} unless (defined($cid));
2046: my %coursehash=&coursedescription($cid);
2047: my %nothide=();
2048: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2049: $nothide{join(':',split(/[\@\:]/,$user))}=1;
2050: }
2051: my %returnhash=();
2052: my %dumphash=
2053: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2054: my $now=time;
2055: foreach my $entry (keys %dumphash) {
2056: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2057: if (($tstart) && ($tstart<0)) { next; }
2058: if (($tend) && ($tend<$now)) { next; }
2059: if (($tstart) && ($now<$tstart)) { next; }
2060: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2061: if ($username eq '' || $domain eq '') { next; }
2062: if ((&privileged($username,$domain)) &&
2063: (!$nothide{$username.':'.$domain})) { next; }
2064: if ($role eq 'cr') { next; }
2065: my $key=&plaintext($role);
2066: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2067: if ($returnhash{$key}) {
2068: $returnhash{$key}.=','.$username.':'.$domain;
2069: } else {
2070: $returnhash{$key}=$username.':'.$domain;
2071: }
2072: }
2073: return %returnhash;
2074: }
2075:
2076: sub get_my_roles {
2077: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
2078: unless (defined($uname)) { $uname=$env{'user.name'}; }
2079: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2080: my %dumphash;
2081: if ($context eq 'userroles') {
2082: %dumphash = &dump('roles',$udom,$uname);
2083: } else {
2084: %dumphash=
2085: &dump('nohist_userroles',$udom,$uname);
2086: }
2087: my %returnhash=();
2088: my $now=time;
2089: foreach my $entry (keys(%dumphash)) {
2090: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2091: if (($tstart) && ($tstart<0)) { next; }
2092: my $status = 'active';
2093: if (($tend) && ($tend<$now)) {
2094: $status = 'previous';
2095: }
2096: if (($tstart) && ($now<$tstart)) {
2097: $status = 'future';
2098: }
2099: if (ref($types) eq 'ARRAY') {
2100: if (!grep(/^\Q$status\E$/,@{$types})) {
2101: next;
2102: }
2103: } else {
2104: if ($status ne 'active') {
2105: next;
2106: }
2107: }
2108: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2109: if (ref($roledoms) eq 'ARRAY') {
2110: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2111: next;
2112: }
2113: }
2114: if (ref($roles) eq 'ARRAY') {
2115: if (!grep(/^\Q$role\E$/,@{$roles})) {
2116: next;
2117: }
2118: }
2119: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2120: }
2121: return %returnhash;
2122: }
2123:
2124: # ----------------------------------------------------- Frontpage Announcements
2125: #
2126: #
2127:
2128: sub postannounce {
2129: my ($server,$text)=@_;
2130: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2131: unless ($text=~/\w/) { $text=''; }
2132: return &reply('setannounce:'.&escape($text),$server);
2133: }
2134:
2135: sub getannounce {
2136:
2137: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2138: my $announcement='';
2139: while (my $line = <$fh>) { $announcement .= $line; }
2140: close($fh);
2141: if ($announcement=~/\w/) {
2142: return
2143: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2144: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2145: } else {
2146: return '';
2147: }
2148: } else {
2149: return '';
2150: }
2151: }
2152:
2153: # ---------------------------------------------------------- Course ID routines
2154: # Deal with domain's nohist_courseid.db files
2155: #
2156:
2157: sub courseidput {
2158: my ($domain,$what,$coursehome)=@_;
2159: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2160: }
2161:
2162: sub courseiddump {
2163: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
2164: my %returnhash=();
2165: unless ($domfilter) { $domfilter=''; }
2166: my %libserv = &all_library();
2167: foreach my $tryserver (keys(%libserv)) {
2168: if ( ( $hostidflag == 1
2169: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2170: || (!defined($hostidflag)) ) {
2171:
2172: if ($domfilter eq ''
2173: || (&host_domain($tryserver) eq $domfilter)) {
2174: foreach my $line (
2175: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
2176: $sincefilter.':'.&escape($descfilter).':'.
2177: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
2178: $tryserver))) {
2179: my ($key,$value)=split(/\=/,$line,2);
2180: if (($key) && ($value)) {
2181: $returnhash{&unescape($key)}=$value;
2182: }
2183: }
2184: }
2185: }
2186: }
2187: return %returnhash;
2188: }
2189:
2190: # ---------------------------------------------------------- DC e-mail
2191:
2192: sub dcmailput {
2193: my ($domain,$msgid,$message,$server)=@_;
2194: my $status = &Apache::lonnet::critical(
2195: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2196: &escape($message),$server);
2197: return $status;
2198: }
2199:
2200: sub dcmaildump {
2201: my ($dom,$startdate,$enddate,$senders) = @_;
2202: my %returnhash=();
2203:
2204: if (defined(&domain($dom,'primary'))) {
2205: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2206: &escape($enddate).':';
2207: my @esc_senders=map { &escape($_)} @$senders;
2208: $cmd.=&escape(join('&',@esc_senders));
2209: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
2210: my ($key,$value) = split(/\=/,$line,2);
2211: if (($key) && ($value)) {
2212: $returnhash{&unescape($key)} = &unescape($value);
2213: }
2214: }
2215: }
2216: return %returnhash;
2217: }
2218: # ---------------------------------------------------------- Domain roles
2219:
2220: sub get_domain_roles {
2221: my ($dom,$roles,$startdate,$enddate)=@_;
2222: if (undef($startdate) || $startdate eq '') {
2223: $startdate = '.';
2224: }
2225: if (undef($enddate) || $enddate eq '') {
2226: $enddate = '.';
2227: }
2228: my $rolelist = join(':',@{$roles});
2229: my %personnel = ();
2230:
2231: my %servers = &get_servers($dom,'library');
2232: foreach my $tryserver (keys(%servers)) {
2233: %{$personnel{$tryserver}}=();
2234: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2235: &escape($startdate).':'.
2236: &escape($enddate).':'.
2237: &escape($rolelist), $tryserver))) {
2238: my ($key,$value) = split(/\=/,$line,2);
2239: if (($key) && ($value)) {
2240: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2241: }
2242: }
2243: }
2244: return %personnel;
2245: }
2246:
2247: # ----------------------------------------------------------- Check out an item
2248:
2249: sub get_first_access {
2250: my ($type,$argsymb)=@_;
2251: my ($symb,$courseid,$udom,$uname)=&whichuser();
2252: if ($argsymb) { $symb=$argsymb; }
2253: my ($map,$id,$res)=&decode_symb($symb);
2254: if ($type eq 'map') {
2255: $res=&symbread($map);
2256: } else {
2257: $res=$symb;
2258: }
2259: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2260: return $times{"$courseid\0$res"};
2261: }
2262:
2263: sub set_first_access {
2264: my ($type)=@_;
2265: my ($symb,$courseid,$udom,$uname)=&whichuser();
2266: my ($map,$id,$res)=&decode_symb($symb);
2267: if ($type eq 'map') {
2268: $res=&symbread($map);
2269: } else {
2270: $res=$symb;
2271: }
2272: my $firstaccess=&get_first_access($type,$symb);
2273: if (!$firstaccess) {
2274: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2275: }
2276: return 'already_set';
2277: }
2278:
2279: sub checkout {
2280: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2281: my $now=time;
2282: my $lonhost=$perlvar{'lonHostID'};
2283: my $infostr=&escape(
2284: 'CHECKOUTTOKEN&'.
2285: $tuname.'&'.
2286: $tudom.'&'.
2287: $tcrsid.'&'.
2288: $symb.'&'.
2289: $now.'&'.$ENV{'REMOTE_ADDR'});
2290: my $token=&reply('tmpput:'.$infostr,$lonhost);
2291: if ($token=~/^error\:/) {
2292: &logthis("<font color=\"blue\">WARNING: ".
2293: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2294: "</font>");
2295: return '';
2296: }
2297:
2298: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2299: $token=~tr/a-z/A-Z/;
2300:
2301: my %infohash=('resource.0.outtoken' => $token,
2302: 'resource.0.checkouttime' => $now,
2303: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2304:
2305: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2306: return '';
2307: } else {
2308: &logthis("<font color=\"blue\">WARNING: ".
2309: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2310: "</font>");
2311: }
2312:
2313: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2314: &escape('Checkout '.$infostr.' - '.
2315: $token)) ne 'ok') {
2316: return '';
2317: } else {
2318: &logthis("<font color=\"blue\">WARNING: ".
2319: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2320: "</font>");
2321: }
2322: return $token;
2323: }
2324:
2325: # ------------------------------------------------------------ Check in an item
2326:
2327: sub checkin {
2328: my $token=shift;
2329: my $now=time;
2330: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2331: $lonhost=~tr/A-Z/a-z/;
2332: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
2333: $dtoken=~s/\W/\_/g;
2334: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2335: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2336:
2337: unless (($tuname) && ($tudom)) {
2338: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2339: return '';
2340: }
2341:
2342: unless (&allowed('mgr',$tcrsid)) {
2343: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
2344: $env{'user.name'}.' - '.$env{'user.domain'});
2345: return '';
2346: }
2347:
2348: my %infohash=('resource.0.intoken' => $token,
2349: 'resource.0.checkintime' => $now,
2350: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
2351:
2352: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2353: return '';
2354: }
2355:
2356: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2357: &escape('Checkin - '.$token)) ne 'ok') {
2358: return '';
2359: }
2360:
2361: return ($symb,$tuname,$tudom,$tcrsid);
2362: }
2363:
2364: # --------------------------------------------- Set Expire Date for Spreadsheet
2365:
2366: sub expirespread {
2367: my ($uname,$udom,$stype,$usymb)=@_;
2368: my $cid=$env{'request.course.id'};
2369: if ($cid) {
2370: my $now=time;
2371: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2372: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2373: $env{'course.'.$cid.'.num'}.
2374: ':nohist_expirationdates:'.
2375: &escape($key).'='.$now,
2376: $env{'course.'.$cid.'.home'})
2377: }
2378: return 'ok';
2379: }
2380:
2381: # ----------------------------------------------------- Devalidate Spreadsheets
2382:
2383: sub devalidate {
2384: my ($symb,$uname,$udom)=@_;
2385: my $cid=$env{'request.course.id'};
2386: if ($cid) {
2387: # delete the stored spreadsheets for
2388: # - the student level sheet of this user in course's homespace
2389: # - the assessment level sheet for this resource
2390: # for this user in user's homespace
2391: # - current conditional state info
2392: my $key=$uname.':'.$udom.':';
2393: my $status=
2394: &del('nohist_calculatedsheets',
2395: [$key.'studentcalc:'],
2396: $env{'course.'.$cid.'.domain'},
2397: $env{'course.'.$cid.'.num'})
2398: .' '.
2399: &del('nohist_calculatedsheets_'.$cid,
2400: [$key.'assesscalc:'.$symb],$udom,$uname);
2401: unless ($status eq 'ok ok') {
2402: &logthis('Could not devalidate spreadsheet '.
2403: $uname.' at '.$udom.' for '.
2404: $symb.': '.$status);
2405: }
2406: &delenv('user.state.'.$cid);
2407: }
2408: }
2409:
2410: sub get_scalar {
2411: my ($string,$end) = @_;
2412: my $value;
2413: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2414: $value = $1;
2415: } elsif ($$string =~ s/^([^&]*?)&//) {
2416: $value = $1;
2417: }
2418: return &unescape($value);
2419: }
2420:
2421: sub array2str {
2422: my (@array) = @_;
2423: my $result=&arrayref2str(\@array);
2424: $result=~s/^__ARRAY_REF__//;
2425: $result=~s/__END_ARRAY_REF__$//;
2426: return $result;
2427: }
2428:
2429: sub arrayref2str {
2430: my ($arrayref) = @_;
2431: my $result='__ARRAY_REF__';
2432: foreach my $elem (@$arrayref) {
2433: if(ref($elem) eq 'ARRAY') {
2434: $result.=&arrayref2str($elem).'&';
2435: } elsif(ref($elem) eq 'HASH') {
2436: $result.=&hashref2str($elem).'&';
2437: } elsif(ref($elem)) {
2438: #print("Got a ref of ".(ref($elem))." skipping.");
2439: } else {
2440: $result.=&escape($elem).'&';
2441: }
2442: }
2443: $result=~s/\&$//;
2444: $result .= '__END_ARRAY_REF__';
2445: return $result;
2446: }
2447:
2448: sub hash2str {
2449: my (%hash) = @_;
2450: my $result=&hashref2str(\%hash);
2451: $result=~s/^__HASH_REF__//;
2452: $result=~s/__END_HASH_REF__$//;
2453: return $result;
2454: }
2455:
2456: sub hashref2str {
2457: my ($hashref)=@_;
2458: my $result='__HASH_REF__';
2459: foreach my $key (sort(keys(%$hashref))) {
2460: if (ref($key) eq 'ARRAY') {
2461: $result.=&arrayref2str($key).'=';
2462: } elsif (ref($key) eq 'HASH') {
2463: $result.=&hashref2str($key).'=';
2464: } elsif (ref($key)) {
2465: $result.='=';
2466: #print("Got a ref of ".(ref($key))." skipping.");
2467: } else {
2468: if ($key) {$result.=&escape($key).'=';} else { last; }
2469: }
2470:
2471: if(ref($hashref->{$key}) eq 'ARRAY') {
2472: $result.=&arrayref2str($hashref->{$key}).'&';
2473: } elsif(ref($hashref->{$key}) eq 'HASH') {
2474: $result.=&hashref2str($hashref->{$key}).'&';
2475: } elsif(ref($hashref->{$key})) {
2476: $result.='&';
2477: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
2478: } else {
2479: $result.=&escape($hashref->{$key}).'&';
2480: }
2481: }
2482: $result=~s/\&$//;
2483: $result .= '__END_HASH_REF__';
2484: return $result;
2485: }
2486:
2487: sub str2hash {
2488: my ($string)=@_;
2489: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2490: return %$hash;
2491: }
2492:
2493: sub str2hashref {
2494: my ($string) = @_;
2495:
2496: my %hash;
2497:
2498: if($string !~ /^__HASH_REF__/) {
2499: if (! ($string eq '' || !defined($string))) {
2500: $hash{'error'}='Not hash reference';
2501: }
2502: return (\%hash, $string);
2503: }
2504:
2505: $string =~ s/^__HASH_REF__//;
2506:
2507: while($string !~ /^__END_HASH_REF__/) {
2508: #key
2509: my $key='';
2510: if($string =~ /^__HASH_REF__/) {
2511: ($key, $string)=&str2hashref($string);
2512: if(defined($key->{'error'})) {
2513: $hash{'error'}='Bad data';
2514: return (\%hash, $string);
2515: }
2516: } elsif($string =~ /^__ARRAY_REF__/) {
2517: ($key, $string)=&str2arrayref($string);
2518: if($key->[0] eq 'Array reference error') {
2519: $hash{'error'}='Bad data';
2520: return (\%hash, $string);
2521: }
2522: } else {
2523: $string =~ s/^(.*?)=//;
2524: $key=&unescape($1);
2525: }
2526: $string =~ s/^=//;
2527:
2528: #value
2529: my $value='';
2530: if($string =~ /^__HASH_REF__/) {
2531: ($value, $string)=&str2hashref($string);
2532: if(defined($value->{'error'})) {
2533: $hash{'error'}='Bad data';
2534: return (\%hash, $string);
2535: }
2536: } elsif($string =~ /^__ARRAY_REF__/) {
2537: ($value, $string)=&str2arrayref($string);
2538: if($value->[0] eq 'Array reference error') {
2539: $hash{'error'}='Bad data';
2540: return (\%hash, $string);
2541: }
2542: } else {
2543: $value=&get_scalar(\$string,'__END_HASH_REF__');
2544: }
2545: $string =~ s/^&//;
2546:
2547: $hash{$key}=$value;
2548: }
2549:
2550: $string =~ s/^__END_HASH_REF__//;
2551:
2552: return (\%hash, $string);
2553: }
2554:
2555: sub str2array {
2556: my ($string)=@_;
2557: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2558: return @$array;
2559: }
2560:
2561: sub str2arrayref {
2562: my ($string) = @_;
2563: my @array;
2564:
2565: if($string !~ /^__ARRAY_REF__/) {
2566: if (! ($string eq '' || !defined($string))) {
2567: $array[0]='Array reference error';
2568: }
2569: return (\@array, $string);
2570: }
2571:
2572: $string =~ s/^__ARRAY_REF__//;
2573:
2574: while($string !~ /^__END_ARRAY_REF__/) {
2575: my $value='';
2576: if($string =~ /^__HASH_REF__/) {
2577: ($value, $string)=&str2hashref($string);
2578: if(defined($value->{'error'})) {
2579: $array[0] ='Array reference error';
2580: return (\@array, $string);
2581: }
2582: } elsif($string =~ /^__ARRAY_REF__/) {
2583: ($value, $string)=&str2arrayref($string);
2584: if($value->[0] eq 'Array reference error') {
2585: $array[0] ='Array reference error';
2586: return (\@array, $string);
2587: }
2588: } else {
2589: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2590: }
2591: $string =~ s/^&//;
2592:
2593: push(@array, $value);
2594: }
2595:
2596: $string =~ s/^__END_ARRAY_REF__//;
2597:
2598: return (\@array, $string);
2599: }
2600:
2601: # -------------------------------------------------------------------Temp Store
2602:
2603: sub tmpreset {
2604: my ($symb,$namespace,$domain,$stuname) = @_;
2605: if (!$symb) {
2606: $symb=&symbread();
2607: if (!$symb) { $symb= $env{'request.url'}; }
2608: }
2609: $symb=escape($symb);
2610:
2611: if (!$namespace) { $namespace=$env{'request.state'}; }
2612: $namespace=~s/\//\_/g;
2613: $namespace=~s/\W//g;
2614:
2615: if (!$domain) { $domain=$env{'user.domain'}; }
2616: if (!$stuname) { $stuname=$env{'user.name'}; }
2617: if ($domain eq 'public' && $stuname eq 'public') {
2618: $stuname=$ENV{'REMOTE_ADDR'};
2619: }
2620: my $path=$perlvar{'lonDaemons'}.'/tmp';
2621: my %hash;
2622: if (tie(%hash,'GDBM_File',
2623: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2624: &GDBM_WRCREAT(),0640)) {
2625: foreach my $key (keys %hash) {
2626: if ($key=~ /:$symb/) {
2627: delete($hash{$key});
2628: }
2629: }
2630: }
2631: }
2632:
2633: sub tmpstore {
2634: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2635:
2636: if (!$symb) {
2637: $symb=&symbread();
2638: if (!$symb) { $symb= $env{'request.url'}; }
2639: }
2640: $symb=escape($symb);
2641:
2642: if (!$namespace) {
2643: # I don't think we would ever want to store this for a course.
2644: # it seems this will only be used if we don't have a course.
2645: #$namespace=$env{'request.course.id'};
2646: #if (!$namespace) {
2647: $namespace=$env{'request.state'};
2648: #}
2649: }
2650: $namespace=~s/\//\_/g;
2651: $namespace=~s/\W//g;
2652: if (!$domain) { $domain=$env{'user.domain'}; }
2653: if (!$stuname) { $stuname=$env{'user.name'}; }
2654: if ($domain eq 'public' && $stuname eq 'public') {
2655: $stuname=$ENV{'REMOTE_ADDR'};
2656: }
2657: my $now=time;
2658: my %hash;
2659: my $path=$perlvar{'lonDaemons'}.'/tmp';
2660: if (tie(%hash,'GDBM_File',
2661: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2662: &GDBM_WRCREAT(),0640)) {
2663: $hash{"version:$symb"}++;
2664: my $version=$hash{"version:$symb"};
2665: my $allkeys='';
2666: foreach my $key (keys(%$storehash)) {
2667: $allkeys.=$key.':';
2668: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
2669: }
2670: $hash{"$version:$symb:timestamp"}=$now;
2671: $allkeys.='timestamp';
2672: $hash{"$version:keys:$symb"}=$allkeys;
2673: if (untie(%hash)) {
2674: return 'ok';
2675: } else {
2676: return "error:$!";
2677: }
2678: } else {
2679: return "error:$!";
2680: }
2681: }
2682:
2683: # -----------------------------------------------------------------Temp Restore
2684:
2685: sub tmprestore {
2686: my ($symb,$namespace,$domain,$stuname) = @_;
2687:
2688: if (!$symb) {
2689: $symb=&symbread();
2690: if (!$symb) { $symb= $env{'request.url'}; }
2691: }
2692: $symb=escape($symb);
2693:
2694: if (!$namespace) { $namespace=$env{'request.state'}; }
2695:
2696: if (!$domain) { $domain=$env{'user.domain'}; }
2697: if (!$stuname) { $stuname=$env{'user.name'}; }
2698: if ($domain eq 'public' && $stuname eq 'public') {
2699: $stuname=$ENV{'REMOTE_ADDR'};
2700: }
2701: my %returnhash;
2702: $namespace=~s/\//\_/g;
2703: $namespace=~s/\W//g;
2704: my %hash;
2705: my $path=$perlvar{'lonDaemons'}.'/tmp';
2706: if (tie(%hash,'GDBM_File',
2707: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2708: &GDBM_READER(),0640)) {
2709: my $version=$hash{"version:$symb"};
2710: $returnhash{'version'}=$version;
2711: my $scope;
2712: for ($scope=1;$scope<=$version;$scope++) {
2713: my $vkeys=$hash{"$scope:keys:$symb"};
2714: my @keys=split(/:/,$vkeys);
2715: my $key;
2716: $returnhash{"$scope:keys"}=$vkeys;
2717: foreach $key (@keys) {
2718: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2719: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2720: }
2721: }
2722: if (!(untie(%hash))) {
2723: return "error:$!";
2724: }
2725: } else {
2726: return "error:$!";
2727: }
2728: return %returnhash;
2729: }
2730:
2731: # ----------------------------------------------------------------------- Store
2732:
2733: sub store {
2734: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2735: my $home='';
2736:
2737: if ($stuname) { $home=&homeserver($stuname,$domain); }
2738:
2739: $symb=&symbclean($symb);
2740: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2741:
2742: if (!$domain) { $domain=$env{'user.domain'}; }
2743: if (!$stuname) { $stuname=$env{'user.name'}; }
2744:
2745: &devalidate($symb,$stuname,$domain);
2746:
2747: $symb=escape($symb);
2748: if (!$namespace) {
2749: unless ($namespace=$env{'request.course.id'}) {
2750: return '';
2751: }
2752: }
2753: if (!$home) { $home=$env{'user.home'}; }
2754:
2755: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2756: $$storehash{'host'}=$perlvar{'lonHostID'};
2757:
2758: my $namevalue='';
2759: foreach my $key (keys(%$storehash)) {
2760: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2761: }
2762: $namevalue=~s/\&$//;
2763: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2764: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2765: }
2766:
2767: # -------------------------------------------------------------- Critical Store
2768:
2769: sub cstore {
2770: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2771: my $home='';
2772:
2773: if ($stuname) { $home=&homeserver($stuname,$domain); }
2774:
2775: $symb=&symbclean($symb);
2776: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2777:
2778: if (!$domain) { $domain=$env{'user.domain'}; }
2779: if (!$stuname) { $stuname=$env{'user.name'}; }
2780:
2781: &devalidate($symb,$stuname,$domain);
2782:
2783: $symb=escape($symb);
2784: if (!$namespace) {
2785: unless ($namespace=$env{'request.course.id'}) {
2786: return '';
2787: }
2788: }
2789: if (!$home) { $home=$env{'user.home'}; }
2790:
2791: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2792: $$storehash{'host'}=$perlvar{'lonHostID'};
2793:
2794: my $namevalue='';
2795: foreach my $key (keys(%$storehash)) {
2796: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2797: }
2798: $namevalue=~s/\&$//;
2799: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2800: return critical
2801: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2802: }
2803:
2804: # --------------------------------------------------------------------- Restore
2805:
2806: sub restore {
2807: my ($symb,$namespace,$domain,$stuname) = @_;
2808: my $home='';
2809:
2810: if ($stuname) { $home=&homeserver($stuname,$domain); }
2811:
2812: if (!$symb) {
2813: unless ($symb=escape(&symbread())) { return ''; }
2814: } else {
2815: $symb=&escape(&symbclean($symb));
2816: }
2817: if (!$namespace) {
2818: unless ($namespace=$env{'request.course.id'}) {
2819: return '';
2820: }
2821: }
2822: if (!$domain) { $domain=$env{'user.domain'}; }
2823: if (!$stuname) { $stuname=$env{'user.name'}; }
2824: if (!$home) { $home=$env{'user.home'}; }
2825: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2826:
2827: my %returnhash=();
2828: foreach my $line (split(/\&/,$answer)) {
2829: my ($name,$value)=split(/\=/,$line);
2830: $returnhash{&unescape($name)}=&thaw_unescape($value);
2831: }
2832: my $version;
2833: for ($version=1;$version<=$returnhash{'version'};$version++) {
2834: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2835: $returnhash{$item}=$returnhash{$version.':'.$item};
2836: }
2837: }
2838: return %returnhash;
2839: }
2840:
2841: # ---------------------------------------------------------- Course Description
2842:
2843: sub coursedescription {
2844: my ($courseid,$args)=@_;
2845: $courseid=~s/^\///;
2846: $courseid=~s/\_/\//g;
2847: my ($cdomain,$cnum)=split(/\//,$courseid);
2848: my $chome=&homeserver($cnum,$cdomain);
2849: my $normalid=$cdomain.'_'.$cnum;
2850: # need to always cache even if we get errors otherwise we keep
2851: # trying and trying and trying to get the course description.
2852: my %envhash=();
2853: my %returnhash=();
2854:
2855: my $expiretime=600;
2856: if ($env{'request.course.id'} eq $normalid) {
2857: $expiretime=120;
2858: }
2859:
2860: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2861: if (!$args->{'freshen_cache'}
2862: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2863: foreach my $key (keys(%env)) {
2864: next if ($key !~ /^\Q$prefix\E(.*)/);
2865: my ($setting) = $1;
2866: $returnhash{$setting} = $env{$key};
2867: }
2868: return %returnhash;
2869: }
2870:
2871: # get the data agin
2872: if (!$args->{'one_time'}) {
2873: $envhash{'course.'.$normalid.'.last_cache'}=time;
2874: }
2875:
2876: if ($chome ne 'no_host') {
2877: %returnhash=&dump('environment',$cdomain,$cnum);
2878: if (!exists($returnhash{'con_lost'})) {
2879: $returnhash{'home'}= $chome;
2880: $returnhash{'domain'} = $cdomain;
2881: $returnhash{'num'} = $cnum;
2882: if (!defined($returnhash{'type'})) {
2883: $returnhash{'type'} = 'Course';
2884: }
2885: while (my ($name,$value) = each %returnhash) {
2886: $envhash{'course.'.$normalid.'.'.$name}=$value;
2887: }
2888: $returnhash{'url'}=&clutter($returnhash{'url'});
2889: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2890: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2891: $envhash{'course.'.$normalid.'.home'}=$chome;
2892: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2893: $envhash{'course.'.$normalid.'.num'}=$cnum;
2894: }
2895: }
2896: if (!$args->{'one_time'}) {
2897: &appenv(%envhash);
2898: }
2899: return %returnhash;
2900: }
2901:
2902: # -------------------------------------------------See if a user is privileged
2903:
2904: sub privileged {
2905: my ($username,$domain)=@_;
2906: my $rolesdump=&reply("dump:$domain:$username:roles",
2907: &homeserver($username,$domain));
2908: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2909: my $now=time;
2910: if ($rolesdump ne '') {
2911: foreach my $entry (split(/&/,$rolesdump)) {
2912: if ($entry!~/^rolesdef_/) {
2913: my ($area,$role)=split(/=/,$entry);
2914: $area=~s/\_\w\w$//;
2915: my ($trole,$tend,$tstart)=split(/_/,$role);
2916: if (($trole eq 'dc') || ($trole eq 'su')) {
2917: my $active=1;
2918: if ($tend) {
2919: if ($tend<$now) { $active=0; }
2920: }
2921: if ($tstart) {
2922: if ($tstart>$now) { $active=0; }
2923: }
2924: if ($active) { return 1; }
2925: }
2926: }
2927: }
2928: }
2929: return 0;
2930: }
2931:
2932: # -------------------------------------------------------- Get user privileges
2933:
2934: sub rolesinit {
2935: my ($domain,$username,$authhost)=@_;
2936: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
2937: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
2938: my %allroles=();
2939: my %allgroups=();
2940: my $now=time;
2941: my %userroles = ('user.login.time' => $now);
2942: my $group_privs;
2943:
2944: if ($rolesdump ne '') {
2945: foreach my $entry (split(/&/,$rolesdump)) {
2946: if ($entry!~/^rolesdef_/) {
2947: my ($area,$role)=split(/=/,$entry);
2948: $area=~s/\_\w\w$//;
2949: my ($trole,$tend,$tstart,$group_privs);
2950: if ($role=~/^cr/) {
2951: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
2952: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
2953: ($tend,$tstart)=split('_',$trest);
2954: } else {
2955: $trole=$role;
2956: }
2957: } elsif ($role =~ m|^gr/|) {
2958: ($trole,$tend,$tstart) = split(/_/,$role);
2959: ($trole,$group_privs) = split(/\//,$trole);
2960: $group_privs = &unescape($group_privs);
2961: } else {
2962: ($trole,$tend,$tstart)=split(/_/,$role);
2963: }
2964: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2965: $username);
2966: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
2967: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2968: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2969: if (($area ne '') && ($trole ne '')) {
2970: my $spec=$trole.'.'.$area;
2971: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2972: if ($trole =~ /^cr\//) {
2973: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2974: } elsif ($trole eq 'gr') {
2975: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
2976: } else {
2977: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2978: }
2979: }
2980: }
2981: }
2982: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2983: $userroles{'user.adv'} = $adv;
2984: $userroles{'user.author'} = $author;
2985: $env{'user.adv'}=$adv;
2986: }
2987: return \%userroles;
2988: }
2989:
2990: sub set_arearole {
2991: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2992: # log the associated role with the area
2993: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2994: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
2995: }
2996:
2997: sub custom_roleprivs {
2998: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2999: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3000: my $homsvr=homeserver($rauthor,$rdomain);
3001: if (&hostname($homsvr) ne '') {
3002: my ($rdummy,$roledef)=
3003: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3004: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3005: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3006: if (defined($syspriv)) {
3007: $$allroles{'cm./'}.=':'.$syspriv;
3008: $$allroles{$spec.'./'}.=':'.$syspriv;
3009: }
3010: if ($tdomain ne '') {
3011: if (defined($dompriv)) {
3012: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3013: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3014: }
3015: if (($trest ne '') && (defined($coursepriv))) {
3016: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3017: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3018: }
3019: }
3020: }
3021: }
3022: }
3023:
3024: sub group_roleprivs {
3025: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3026: my $access = 1;
3027: my $now = time;
3028: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3029: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3030: if ($access) {
3031: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3032: $$allgroups{$course}{$group} .=':'.$group_privs;
3033: }
3034: }
3035:
3036: sub standard_roleprivs {
3037: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3038: if (defined($pr{$trole.':s'})) {
3039: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3040: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3041: }
3042: if ($tdomain ne '') {
3043: if (defined($pr{$trole.':d'})) {
3044: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3045: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3046: }
3047: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3048: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3049: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3050: }
3051: }
3052: }
3053:
3054: sub set_userprivs {
3055: my ($userroles,$allroles,$allgroups) = @_;
3056: my $author=0;
3057: my $adv=0;
3058: my %grouproles = ();
3059: if (keys(%{$allgroups}) > 0) {
3060: foreach my $role (keys %{$allroles}) {
3061: my ($trole,$area,$sec,$extendedarea);
3062: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
3063: $trole = $1;
3064: $area = $2;
3065: $sec = $3;
3066: $extendedarea = $area.$sec;
3067: if (exists($$allgroups{$area})) {
3068: foreach my $group (keys(%{$$allgroups{$area}})) {
3069: my $spec = $trole.'.'.$extendedarea;
3070: $grouproles{$spec.'.'.$area.'/'.$group} =
3071: $$allgroups{$area}{$group};
3072: }
3073: }
3074: }
3075: }
3076: }
3077: foreach my $group (keys(%grouproles)) {
3078: $$allroles{$group} = $grouproles{$group};
3079: }
3080: foreach my $role (keys(%{$allroles})) {
3081: my %thesepriv;
3082: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3083: foreach my $item (split(/:/,$$allroles{$role})) {
3084: if ($item ne '') {
3085: my ($privilege,$restrictions)=split(/&/,$item);
3086: if ($restrictions eq '') {
3087: $thesepriv{$privilege}='F';
3088: } elsif ($thesepriv{$privilege} ne 'F') {
3089: $thesepriv{$privilege}.=$restrictions;
3090: }
3091: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3092: }
3093: }
3094: my $thesestr='';
3095: foreach my $priv (keys(%thesepriv)) {
3096: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3097: }
3098: $userroles->{'user.priv.'.$role} = $thesestr;
3099: }
3100: return ($author,$adv);
3101: }
3102:
3103: # --------------------------------------------------------------- get interface
3104:
3105: sub get {
3106: my ($namespace,$storearr,$udomain,$uname)=@_;
3107: my $items='';
3108: foreach my $item (@$storearr) {
3109: $items.=&escape($item).'&';
3110: }
3111: $items=~s/\&$//;
3112: if (!$udomain) { $udomain=$env{'user.domain'}; }
3113: if (!$uname) { $uname=$env{'user.name'}; }
3114: my $uhome=&homeserver($uname,$udomain);
3115:
3116: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
3117: my @pairs=split(/\&/,$rep);
3118: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3119: return @pairs;
3120: }
3121: my %returnhash=();
3122: my $i=0;
3123: foreach my $item (@$storearr) {
3124: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3125: $i++;
3126: }
3127: return %returnhash;
3128: }
3129:
3130: # --------------------------------------------------------------- del interface
3131:
3132: sub del {
3133: my ($namespace,$storearr,$udomain,$uname)=@_;
3134: my $items='';
3135: foreach my $item (@$storearr) {
3136: $items.=&escape($item).'&';
3137: }
3138: $items=~s/\&$//;
3139: if (!$udomain) { $udomain=$env{'user.domain'}; }
3140: if (!$uname) { $uname=$env{'user.name'}; }
3141: my $uhome=&homeserver($uname,$udomain);
3142:
3143: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3144: }
3145:
3146: # -------------------------------------------------------------- dump interface
3147:
3148: sub dump {
3149: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3150: if (!$udomain) { $udomain=$env{'user.domain'}; }
3151: if (!$uname) { $uname=$env{'user.name'}; }
3152: my $uhome=&homeserver($uname,$udomain);
3153: if ($regexp) {
3154: $regexp=&escape($regexp);
3155: } else {
3156: $regexp='.';
3157: }
3158: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3159: my @pairs=split(/\&/,$rep);
3160: my %returnhash=();
3161: foreach my $item (@pairs) {
3162: my ($key,$value)=split(/=/,$item,2);
3163: $key = &unescape($key);
3164: next if ($key =~ /^error: 2 /);
3165: $returnhash{$key}=&thaw_unescape($value);
3166: }
3167: return %returnhash;
3168: }
3169:
3170: # --------------------------------------------------------- dumpstore interface
3171:
3172: sub dumpstore {
3173: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3174: if (!$udomain) { $udomain=$env{'user.domain'}; }
3175: if (!$uname) { $uname=$env{'user.name'}; }
3176: my $uhome=&homeserver($uname,$udomain);
3177: if ($regexp) {
3178: $regexp=&escape($regexp);
3179: } else {
3180: $regexp='.';
3181: }
3182: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3183: my @pairs=split(/\&/,$rep);
3184: my %returnhash=();
3185: foreach my $item (@pairs) {
3186: my ($key,$value)=split(/=/,$item,2);
3187: next if ($key =~ /^error: 2 /);
3188: $returnhash{$key}=&thaw_unescape($value);
3189: }
3190: return %returnhash;
3191: }
3192:
3193: # -------------------------------------------------------------- keys interface
3194:
3195: sub getkeys {
3196: my ($namespace,$udomain,$uname)=@_;
3197: if (!$udomain) { $udomain=$env{'user.domain'}; }
3198: if (!$uname) { $uname=$env{'user.name'}; }
3199: my $uhome=&homeserver($uname,$udomain);
3200: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3201: my @keyarray=();
3202: foreach my $key (split(/\&/,$rep)) {
3203: next if ($key =~ /^error: 2 /);
3204: push(@keyarray,&unescape($key));
3205: }
3206: return @keyarray;
3207: }
3208:
3209: # --------------------------------------------------------------- currentdump
3210: sub currentdump {
3211: my ($courseid,$sdom,$sname)=@_;
3212: $courseid = $env{'request.course.id'} if (! defined($courseid));
3213: $sdom = $env{'user.domain'} if (! defined($sdom));
3214: $sname = $env{'user.name'} if (! defined($sname));
3215: my $uhome = &homeserver($sname,$sdom);
3216: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3217: return if ($rep =~ /^(error:|no_such_host)/);
3218: #
3219: my %returnhash=();
3220: #
3221: if ($rep eq "unknown_cmd") {
3222: # an old lond will not know currentdump
3223: # Do a dump and make it look like a currentdump
3224: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
3225: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3226: my %hash = @tmp;
3227: @tmp=();
3228: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3229: } else {
3230: my @pairs=split(/\&/,$rep);
3231: foreach my $pair (@pairs) {
3232: my ($key,$value)=split(/=/,$pair,2);
3233: my ($symb,$param) = split(/:/,$key);
3234: $returnhash{&unescape($symb)}->{&unescape($param)} =
3235: &thaw_unescape($value);
3236: }
3237: }
3238: return %returnhash;
3239: }
3240:
3241: sub convert_dump_to_currentdump{
3242: my %hash = %{shift()};
3243: my %returnhash;
3244: # Code ripped from lond, essentially. The only difference
3245: # here is the unescaping done by lonnet::dump(). Conceivably
3246: # we might run in to problems with parameter names =~ /^v\./
3247: while (my ($key,$value) = each(%hash)) {
3248: my ($v,$symb,$param) = split(/:/,$key);
3249: $symb = &unescape($symb);
3250: $param = &unescape($param);
3251: next if ($v eq 'version' || $symb eq 'keys');
3252: next if (exists($returnhash{$symb}) &&
3253: exists($returnhash{$symb}->{$param}) &&
3254: $returnhash{$symb}->{'v.'.$param} > $v);
3255: $returnhash{$symb}->{$param}=$value;
3256: $returnhash{$symb}->{'v.'.$param}=$v;
3257: }
3258: #
3259: # Remove all of the keys in the hashes which keep track of
3260: # the version of the parameter.
3261: while (my ($symb,$param_hash) = each(%returnhash)) {
3262: # use a foreach because we are going to delete from the hash.
3263: foreach my $key (keys(%$param_hash)) {
3264: delete($param_hash->{$key}) if ($key =~ /^v\./);
3265: }
3266: }
3267: return \%returnhash;
3268: }
3269:
3270: # ------------------------------------------------------ critical inc interface
3271:
3272: sub cinc {
3273: return &inc(@_,'critical');
3274: }
3275:
3276: # --------------------------------------------------------------- inc interface
3277:
3278: sub inc {
3279: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3280: if (!$udomain) { $udomain=$env{'user.domain'}; }
3281: if (!$uname) { $uname=$env{'user.name'}; }
3282: my $uhome=&homeserver($uname,$udomain);
3283: my $items='';
3284: if (! ref($store)) {
3285: # got a single value, so use that instead
3286: $items = &escape($store).'=&';
3287: } elsif (ref($store) eq 'SCALAR') {
3288: $items = &escape($$store).'=&';
3289: } elsif (ref($store) eq 'ARRAY') {
3290: $items = join('=&',map {&escape($_);} @{$store});
3291: } elsif (ref($store) eq 'HASH') {
3292: while (my($key,$value) = each(%{$store})) {
3293: $items.= &escape($key).'='.&escape($value).'&';
3294: }
3295: }
3296: $items=~s/\&$//;
3297: if ($critical) {
3298: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3299: } else {
3300: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3301: }
3302: }
3303:
3304: # --------------------------------------------------------------- put interface
3305:
3306: sub put {
3307: my ($namespace,$storehash,$udomain,$uname)=@_;
3308: if (!$udomain) { $udomain=$env{'user.domain'}; }
3309: if (!$uname) { $uname=$env{'user.name'}; }
3310: my $uhome=&homeserver($uname,$udomain);
3311: my $items='';
3312: foreach my $item (keys(%$storehash)) {
3313: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3314: }
3315: $items=~s/\&$//;
3316: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3317: }
3318:
3319: # ------------------------------------------------------------ newput interface
3320:
3321: sub newput {
3322: my ($namespace,$storehash,$udomain,$uname)=@_;
3323: if (!$udomain) { $udomain=$env{'user.domain'}; }
3324: if (!$uname) { $uname=$env{'user.name'}; }
3325: my $uhome=&homeserver($uname,$udomain);
3326: my $items='';
3327: foreach my $key (keys(%$storehash)) {
3328: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3329: }
3330: $items=~s/\&$//;
3331: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3332: }
3333:
3334: # --------------------------------------------------------- putstore interface
3335:
3336: sub putstore {
3337: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3338: if (!$udomain) { $udomain=$env{'user.domain'}; }
3339: if (!$uname) { $uname=$env{'user.name'}; }
3340: my $uhome=&homeserver($uname,$udomain);
3341: my $items='';
3342: foreach my $key (keys(%$storehash)) {
3343: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3344: }
3345: $items=~s/\&$//;
3346: my $esc_symb=&escape($symb);
3347: my $esc_v=&escape($version);
3348: my $reply =
3349: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3350: $uhome);
3351: if ($reply eq 'unknown_cmd') {
3352: # gfall back to way things use to be done
3353: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3354: $uname);
3355: }
3356: return $reply;
3357: }
3358:
3359: sub old_putstore {
3360: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3361: if (!$udomain) { $udomain=$env{'user.domain'}; }
3362: if (!$uname) { $uname=$env{'user.name'}; }
3363: my $uhome=&homeserver($uname,$udomain);
3364: my %newstorehash;
3365: foreach my $item (keys(%$storehash)) {
3366: my $key = $version.':'.&escape($symb).':'.$item;
3367: $newstorehash{$key} = $storehash->{$item};
3368: }
3369: my $items='';
3370: my %allitems = ();
3371: foreach my $item (keys(%newstorehash)) {
3372: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3373: my $key = $1.':keys:'.$2;
3374: $allitems{$key} .= $3.':';
3375: }
3376: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
3377: }
3378: foreach my $item (keys(%allitems)) {
3379: $allitems{$item} =~ s/\:$//;
3380: $items.= $item.'='.$allitems{$item}.'&';
3381: }
3382: $items=~s/\&$//;
3383: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3384: }
3385:
3386: # ------------------------------------------------------ critical put interface
3387:
3388: sub cput {
3389: my ($namespace,$storehash,$udomain,$uname)=@_;
3390: if (!$udomain) { $udomain=$env{'user.domain'}; }
3391: if (!$uname) { $uname=$env{'user.name'}; }
3392: my $uhome=&homeserver($uname,$udomain);
3393: my $items='';
3394: foreach my $item (keys(%$storehash)) {
3395: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3396: }
3397: $items=~s/\&$//;
3398: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3399: }
3400:
3401: # -------------------------------------------------------------- eget interface
3402:
3403: sub eget {
3404: my ($namespace,$storearr,$udomain,$uname)=@_;
3405: my $items='';
3406: foreach my $item (@$storearr) {
3407: $items.=&escape($item).'&';
3408: }
3409: $items=~s/\&$//;
3410: if (!$udomain) { $udomain=$env{'user.domain'}; }
3411: if (!$uname) { $uname=$env{'user.name'}; }
3412: my $uhome=&homeserver($uname,$udomain);
3413: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3414: my @pairs=split(/\&/,$rep);
3415: my %returnhash=();
3416: my $i=0;
3417: foreach my $item (@$storearr) {
3418: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3419: $i++;
3420: }
3421: return %returnhash;
3422: }
3423:
3424: # ------------------------------------------------------------ tmpput interface
3425: sub tmpput {
3426: my ($storehash,$server,$context)=@_;
3427: my $items='';
3428: foreach my $item (keys(%$storehash)) {
3429: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3430: }
3431: $items=~s/\&$//;
3432: if (defined($context)) {
3433: $items .= ':'.&escape($context);
3434: }
3435: return &reply("tmpput:$items",$server);
3436: }
3437:
3438: # ------------------------------------------------------------ tmpget interface
3439: sub tmpget {
3440: my ($token,$server)=@_;
3441: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3442: my $rep=&reply("tmpget:$token",$server);
3443: my %returnhash;
3444: foreach my $item (split(/\&/,$rep)) {
3445: my ($key,$value)=split(/=/,$item);
3446: $returnhash{&unescape($key)}=&thaw_unescape($value);
3447: }
3448: return %returnhash;
3449: }
3450:
3451: # ------------------------------------------------------------ tmpget interface
3452: sub tmpdel {
3453: my ($token,$server)=@_;
3454: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3455: return &reply("tmpdel:$token",$server);
3456: }
3457:
3458: # -------------------------------------------------- portfolio access checking
3459:
3460: sub portfolio_access {
3461: my ($requrl) = @_;
3462: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3463: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3464: if ($result) {
3465: my %setters;
3466: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3467: my ($startblock,$endblock) =
3468: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3469: if ($startblock && $endblock) {
3470: return 'B';
3471: }
3472: } else {
3473: my ($startblock,$endblock) =
3474: &Apache::loncommon::blockcheck(\%setters,'port');
3475: if ($startblock && $endblock) {
3476: return 'B';
3477: }
3478: }
3479: }
3480: if ($result eq 'ok') {
3481: return 'F';
3482: } elsif ($result =~ /^[^:]+:guest_/) {
3483: return 'A';
3484: }
3485: return '';
3486: }
3487:
3488: sub get_portfolio_access {
3489: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3490:
3491: if (!ref($access_hash)) {
3492: my $current_perms = &get_portfile_permissions($udom,$unum);
3493: my %access_controls = &get_access_controls($current_perms,$group,
3494: $file_name);
3495: $access_hash = $access_controls{$file_name};
3496: }
3497:
3498: my ($public,$guest,@domains,@users,@courses,@groups);
3499: my $now = time;
3500: if (ref($access_hash) eq 'HASH') {
3501: foreach my $key (keys(%{$access_hash})) {
3502: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3503: if ($start > $now) {
3504: next;
3505: }
3506: if ($end && $end<$now) {
3507: next;
3508: }
3509: if ($scope eq 'public') {
3510: $public = $key;
3511: last;
3512: } elsif ($scope eq 'guest') {
3513: $guest = $key;
3514: } elsif ($scope eq 'domains') {
3515: push(@domains,$key);
3516: } elsif ($scope eq 'users') {
3517: push(@users,$key);
3518: } elsif ($scope eq 'course') {
3519: push(@courses,$key);
3520: } elsif ($scope eq 'group') {
3521: push(@groups,$key);
3522: }
3523: }
3524: if ($public) {
3525: return 'ok';
3526: }
3527: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3528: if ($guest) {
3529: return $guest;
3530: }
3531: } else {
3532: if (@domains > 0) {
3533: foreach my $domkey (@domains) {
3534: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3535: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3536: return 'ok';
3537: }
3538: }
3539: }
3540: }
3541: if (@users > 0) {
3542: foreach my $userkey (@users) {
3543: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3544: return 'ok';
3545: }
3546: }
3547: }
3548: my %roleshash;
3549: my @courses_and_groups = @courses;
3550: push(@courses_and_groups,@groups);
3551: if (@courses_and_groups > 0) {
3552: my (%allgroups,%allroles);
3553: my ($start,$end,$role,$sec,$group);
3554: foreach my $envkey (%env) {
3555: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
3556: my $cid = $2.'_'.$3;
3557: if ($1 eq 'gr') {
3558: $group = $4;
3559: $allgroups{$cid}{$group} = $env{$envkey};
3560: } else {
3561: if ($4 eq '') {
3562: $sec = 'none';
3563: } else {
3564: $sec = $4;
3565: }
3566: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3567: }
3568: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
3569: my $cid = $2.'_'.$3;
3570: if ($4 eq '') {
3571: $sec = 'none';
3572: } else {
3573: $sec = $4;
3574: }
3575: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3576: }
3577: }
3578: if (keys(%allroles) == 0) {
3579: return;
3580: }
3581: foreach my $key (@courses_and_groups) {
3582: my %content = %{$$access_hash{$key}};
3583: my $cnum = $content{'number'};
3584: my $cdom = $content{'domain'};
3585: my $cid = $cdom.'_'.$cnum;
3586: if (!exists($allroles{$cid})) {
3587: next;
3588: }
3589: foreach my $role_id (keys(%{$content{'roles'}})) {
3590: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3591: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3592: my @status = @{$content{'roles'}{$role_id}{'access'}};
3593: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3594: foreach my $role (keys(%{$allroles{$cid}})) {
3595: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3596: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3597: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3598: if (grep/^all$/,@sections) {
3599: return 'ok';
3600: } else {
3601: if (grep/^$sec$/,@sections) {
3602: return 'ok';
3603: }
3604: }
3605: }
3606: }
3607: if (keys(%{$allgroups{$cid}}) == 0) {
3608: if (grep/^none$/,@groups) {
3609: return 'ok';
3610: }
3611: } else {
3612: if (grep/^all$/,@groups) {
3613: return 'ok';
3614: }
3615: foreach my $group (keys(%{$allgroups{$cid}})) {
3616: if (grep/^$group$/,@groups) {
3617: return 'ok';
3618: }
3619: }
3620: }
3621: }
3622: }
3623: }
3624: }
3625: }
3626: if ($guest) {
3627: return $guest;
3628: }
3629: }
3630: }
3631: return;
3632: }
3633:
3634: sub course_group_datechecker {
3635: my ($dates,$now,$status) = @_;
3636: my ($start,$end) = split(/\./,$dates);
3637: if (!$start && !$end) {
3638: return 'ok';
3639: }
3640: if (grep/^active$/,@{$status}) {
3641: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3642: return 'ok';
3643: }
3644: }
3645: if (grep/^previous$/,@{$status}) {
3646: if ($end > $now ) {
3647: return 'ok';
3648: }
3649: }
3650: if (grep/^future$/,@{$status}) {
3651: if ($start > $now) {
3652: return 'ok';
3653: }
3654: }
3655: return;
3656: }
3657:
3658: sub parse_portfolio_url {
3659: my ($url) = @_;
3660:
3661: my ($type,$udom,$unum,$group,$file_name);
3662:
3663: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
3664: $type = 1;
3665: $udom = $1;
3666: $unum = $2;
3667: $file_name = $3;
3668: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
3669: $type = 2;
3670: $udom = $1;
3671: $unum = $2;
3672: $group = $3;
3673: $file_name = $3.'/'.$4;
3674: }
3675: if (wantarray) {
3676: return ($type,$udom,$unum,$file_name,$group);
3677: }
3678: return $type;
3679: }
3680:
3681: sub is_portfolio_url {
3682: my ($url) = @_;
3683: return scalar(&parse_portfolio_url($url));
3684: }
3685:
3686: sub is_portfolio_file {
3687: my ($file) = @_;
3688: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
3689: return 1;
3690: }
3691: return;
3692: }
3693:
3694:
3695: # ---------------------------------------------- Custom access rule evaluation
3696:
3697: sub customaccess {
3698: my ($priv,$uri)=@_;
3699: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
3700: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
3701: $udom = &LONCAPA::clean_domain($udom);
3702: $ucrs = &LONCAPA::clean_username($ucrs);
3703: my $access=0;
3704: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3705: my ($effect,$realm,$role)=split(/\:/,$right);
3706: if ($role) {
3707: if ($role ne $urole) { next; }
3708: }
3709: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3710: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
3711: if ($tdom) {
3712: if ($tdom ne $udom) { next; }
3713: }
3714: if ($tcrs) {
3715: if ($tcrs ne $ucrs) { next; }
3716: }
3717: if ($tsec) {
3718: if ($tsec ne $usec) { next; }
3719: }
3720: $access=($effect eq 'allow');
3721: last;
3722: }
3723: if ($realm eq '' && $role eq '') {
3724: $access=($effect eq 'allow');
3725: }
3726: }
3727: return $access;
3728: }
3729:
3730: # ------------------------------------------------- Check for a user privilege
3731:
3732: sub allowed {
3733: my ($priv,$uri,$symb,$role)=@_;
3734: my $ver_orguri=$uri;
3735: $uri=&deversion($uri);
3736: my $orguri=$uri;
3737: $uri=&declutter($uri);
3738:
3739: if ($priv eq 'evb') {
3740: # Evade communication block restrictions for specified role in a course
3741: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3742: return $1;
3743: } else {
3744: return;
3745: }
3746: }
3747:
3748: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3749: # Free bre access to adm and meta resources
3750: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
3751: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3752: && ($priv eq 'bre')) {
3753: return 'F';
3754: }
3755:
3756: # Free bre access to user's own portfolio contents
3757: my ($space,$domain,$name,@dir)=split('/',$uri);
3758: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3759: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
3760: my %setters;
3761: my ($startblock,$endblock) =
3762: &Apache::loncommon::blockcheck(\%setters,'port');
3763: if ($startblock && $endblock) {
3764: return 'B';
3765: } else {
3766: return 'F';
3767: }
3768: }
3769:
3770: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
3771: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3772: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3773: if (exists($env{'request.course.id'})) {
3774: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3775: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3776: if (($domain eq $cdom) && ($name eq $cnum)) {
3777: my $courseprivid=$env{'request.course.id'};
3778: $courseprivid=~s/\_/\//;
3779: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3780: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3781: return $1;
3782: } else {
3783: if ($env{'request.course.sec'}) {
3784: $courseprivid.='/'.$env{'request.course.sec'};
3785: }
3786: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3787: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3788: return $2;
3789: }
3790: }
3791: }
3792: }
3793: }
3794:
3795: # Free bre to public access
3796:
3797: if ($priv eq 'bre') {
3798: my $copyright=&metadata($uri,'copyright');
3799: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3800: return 'F';
3801: }
3802: if ($copyright eq 'priv') {
3803: $uri=~/([^\/]+)\/([^\/]+)\//;
3804: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3805: return '';
3806: }
3807: }
3808: if ($copyright eq 'domain') {
3809: $uri=~/([^\/]+)\/([^\/]+)\//;
3810: unless (($env{'user.domain'} eq $1) ||
3811: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3812: return '';
3813: }
3814: }
3815: if ($env{'request.role'}=~ /li\.\//) {
3816: # Library role, so allow browsing of resources in this domain.
3817: return 'F';
3818: }
3819: if ($copyright eq 'custom') {
3820: unless (&customaccess($priv,$uri)) { return ''; }
3821: }
3822: }
3823: # Domain coordinator is trying to create a course
3824: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3825: # uri is the requested domain in this case.
3826: # comparison to 'request.role.domain' shows if the user has selected
3827: # a role of dc for the domain in question.
3828: return 'F' if ($uri eq $env{'request.role.domain'});
3829: }
3830:
3831: my $thisallowed='';
3832: my $statecond=0;
3833: my $courseprivid='';
3834:
3835: # Course
3836:
3837: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3838: $thisallowed.=$1;
3839: }
3840:
3841: # Domain
3842:
3843: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3844: =~/\Q$priv\E\&([^\:]*)/) {
3845: $thisallowed.=$1;
3846: }
3847:
3848: # Course: uri itself is a course
3849: my $courseuri=$uri;
3850: $courseuri=~s/\_(\d)/\/$1/;
3851: $courseuri=~s/^([^\/])/\/$1/;
3852:
3853: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3854: =~/\Q$priv\E\&([^\:]*)/) {
3855: $thisallowed.=$1;
3856: }
3857:
3858: # URI is an uploaded document for this course, default permissions don't matter
3859: # not allowing 'edit' access (editupload) to uploaded course docs
3860: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3861: $thisallowed='';
3862: my ($match)=&is_on_map($uri);
3863: if ($match) {
3864: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3865: =~/\Q$priv\E\&([^\:]*)/) {
3866: $thisallowed.=$1;
3867: }
3868: } else {
3869: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3870: if ($refuri) {
3871: if ($refuri =~ m|^/adm/|) {
3872: $thisallowed='F';
3873: } else {
3874: $refuri=&declutter($refuri);
3875: my ($match) = &is_on_map($refuri);
3876: if ($match) {
3877: $thisallowed='F';
3878: }
3879: }
3880: }
3881: }
3882: }
3883:
3884: if ($priv eq 'bre'
3885: && $thisallowed ne 'F'
3886: && $thisallowed ne '2'
3887: && &is_portfolio_url($uri)) {
3888: $thisallowed = &portfolio_access($uri);
3889: }
3890:
3891: # Full access at system, domain or course-wide level? Exit.
3892:
3893: if ($thisallowed=~/F/) {
3894: return 'F';
3895: }
3896:
3897: # If this is generating or modifying users, exit with special codes
3898:
3899: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3900: if (($priv eq 'cca') || ($priv eq 'caa')) {
3901: my ($audom,$auname)=split('/',$uri);
3902: # no author name given, so this just checks on the general right to make a co-author in this domain
3903: unless ($auname) { return $thisallowed; }
3904: # an author name is given, so we are about to actually make a co-author for a certain account
3905: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3906: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3907: ($audom ne $env{'request.role.domain'}))) { return ''; }
3908: }
3909: return $thisallowed;
3910: }
3911: #
3912: # Gathered so far: system, domain and course wide privileges
3913: #
3914: # Course: See if uri or referer is an individual resource that is part of
3915: # the course
3916:
3917: if ($env{'request.course.id'}) {
3918:
3919: $courseprivid=$env{'request.course.id'};
3920: if ($env{'request.course.sec'}) {
3921: $courseprivid.='/'.$env{'request.course.sec'};
3922: }
3923: $courseprivid=~s/\_/\//;
3924: my $checkreferer=1;
3925: my ($match,$cond)=&is_on_map($uri);
3926: if ($match) {
3927: $statecond=$cond;
3928: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3929: =~/\Q$priv\E\&([^\:]*)/) {
3930: $thisallowed.=$1;
3931: $checkreferer=0;
3932: }
3933: }
3934:
3935: if ($checkreferer) {
3936: my $refuri=$env{'httpref.'.$orguri};
3937: unless ($refuri) {
3938: foreach my $key (keys(%env)) {
3939: if ($key=~/^httpref\..*\*/) {
3940: my $pattern=$key;
3941: $pattern=~s/^httpref\.\/res\///;
3942: $pattern=~s/\*/\[\^\/\]\+/g;
3943: $pattern=~s/\//\\\//g;
3944: if ($orguri=~/$pattern/) {
3945: $refuri=$env{$key};
3946: }
3947: }
3948: }
3949: }
3950:
3951: if ($refuri) {
3952: $refuri=&declutter($refuri);
3953: my ($match,$cond)=&is_on_map($refuri);
3954: if ($match) {
3955: my $refstatecond=$cond;
3956: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3957: =~/\Q$priv\E\&([^\:]*)/) {
3958: $thisallowed.=$1;
3959: $uri=$refuri;
3960: $statecond=$refstatecond;
3961: }
3962: }
3963: }
3964: }
3965: }
3966:
3967: #
3968: # Gathered now: all privileges that could apply, and condition number
3969: #
3970: #
3971: # Full or no access?
3972: #
3973:
3974: if ($thisallowed=~/F/) {
3975: return 'F';
3976: }
3977:
3978: unless ($thisallowed) {
3979: return '';
3980: }
3981:
3982: # Restrictions exist, deal with them
3983: #
3984: # C:according to course preferences
3985: # R:according to resource settings
3986: # L:unless locked
3987: # X:according to user session state
3988: #
3989:
3990: # Possibly locked functionality, check all courses
3991: # Locks might take effect only after 10 minutes cache expiration for other
3992: # courses, and 2 minutes for current course
3993:
3994: my $envkey;
3995: if ($thisallowed=~/L/) {
3996: foreach $envkey (keys %env) {
3997: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3998: my $courseid=$2;
3999: my $roleid=$1.'.'.$2;
4000: $courseid=~s/^\///;
4001: my $expiretime=600;
4002: if ($env{'request.role'} eq $roleid) {
4003: $expiretime=120;
4004: }
4005: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4006: my $prefix='course.'.$cdom.'_'.$cnum.'.';
4007: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
4008: &coursedescription($courseid,{'freshen_cache' => 1});
4009: }
4010: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4011: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4012: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4013: &log($env{'user.domain'},$env{'user.name'},
4014: $env{'user.home'},
4015: 'Locked by res: '.$priv.' for '.$uri.' due to '.
4016: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4017: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4018: return '';
4019: }
4020: }
4021: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4022: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4023: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4024: &log($env{'user.domain'},$env{'user.name'},
4025: $env{'user.home'},
4026: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
4027: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4028: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4029: return '';
4030: }
4031: }
4032: }
4033: }
4034: }
4035:
4036: #
4037: # Rest of the restrictions depend on selected course
4038: #
4039:
4040: unless ($env{'request.course.id'}) {
4041: if ($thisallowed eq 'A') {
4042: return 'A';
4043: } elsif ($thisallowed eq 'B') {
4044: return 'B';
4045: } else {
4046: return '1';
4047: }
4048: }
4049:
4050: #
4051: # Now user is definitely in a course
4052: #
4053:
4054:
4055: # Course preferences
4056:
4057: if ($thisallowed=~/C/) {
4058: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4059: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4060: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
4061: =~/\Q$rolecode\E/) {
4062: if ($priv ne 'pch') {
4063: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4064: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4065: $env{'request.course.id'});
4066: }
4067: return '';
4068: }
4069:
4070: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
4071: =~/\Q$unamedom\E/) {
4072: if ($priv ne 'pch') {
4073: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4074: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4075: $env{'request.course.id'});
4076: }
4077: return '';
4078: }
4079: }
4080:
4081: # Resource preferences
4082:
4083: if ($thisallowed=~/R/) {
4084: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4085: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
4086: if ($priv ne 'pch') {
4087: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4088: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4089: }
4090: return '';
4091: }
4092: }
4093:
4094: # Restricted by state or randomout?
4095:
4096: if ($thisallowed=~/X/) {
4097: if ($env{'acc.randomout'}) {
4098: if (!$symb) { $symb=&symbread($uri,1); }
4099: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
4100: return '';
4101: }
4102: }
4103: if (&condval($statecond)) {
4104: return '2';
4105: } else {
4106: return '';
4107: }
4108: }
4109:
4110: if ($thisallowed eq 'A') {
4111: return 'A';
4112: } elsif ($thisallowed eq 'B') {
4113: return 'B';
4114: }
4115: return 'F';
4116: }
4117:
4118: sub split_uri_for_cond {
4119: my $uri=&deversion(&declutter(shift));
4120: my @uriparts=split(/\//,$uri);
4121: my $filename=pop(@uriparts);
4122: my $pathname=join('/',@uriparts);
4123: return ($pathname,$filename);
4124: }
4125: # --------------------------------------------------- Is a resource on the map?
4126:
4127: sub is_on_map {
4128: my ($pathname,$filename) = &split_uri_for_cond(shift);
4129: #Trying to find the conditional for the file
4130: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
4131: /\&\Q$filename\E\:([\d\|]+)\&/);
4132: if ($match) {
4133: return (1,$1);
4134: } else {
4135: return (0,0);
4136: }
4137: }
4138:
4139: # --------------------------------------------------------- Get symb from alias
4140:
4141: sub get_symb_from_alias {
4142: my $symb=shift;
4143: my ($map,$resid,$url)=&decode_symb($symb);
4144: # Already is a symb
4145: if ($url) { return $symb; }
4146: # Must be an alias
4147: my $aliassymb='';
4148: my %bighash;
4149: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
4150: &GDBM_READER(),0640)) {
4151: my $rid=$bighash{'mapalias_'.$symb};
4152: if ($rid) {
4153: my ($mapid,$resid)=split(/\./,$rid);
4154: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4155: $resid,$bighash{'src_'.$rid});
4156: }
4157: untie %bighash;
4158: }
4159: return $aliassymb;
4160: }
4161:
4162: # ----------------------------------------------------------------- Define Role
4163:
4164: sub definerole {
4165: if (allowed('mcr','/')) {
4166: my ($rolename,$sysrole,$domrole,$courole)=@_;
4167: foreach my $role (split(':',$sysrole)) {
4168: my ($crole,$cqual)=split(/\&/,$role);
4169: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4170: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4171: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4172: return "refused:s:$crole&$cqual";
4173: }
4174: }
4175: }
4176: foreach my $role (split(':',$domrole)) {
4177: my ($crole,$cqual)=split(/\&/,$role);
4178: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4179: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4180: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
4181: return "refused:d:$crole&$cqual";
4182: }
4183: }
4184: }
4185: foreach my $role (split(':',$courole)) {
4186: my ($crole,$cqual)=split(/\&/,$role);
4187: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4188: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4189: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4190: return "refused:c:$crole&$cqual";
4191: }
4192: }
4193: }
4194: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4195: "$env{'user.domain'}:$env{'user.name'}:".
4196: "rolesdef_$rolename=".
4197: escape($sysrole.'_'.$domrole.'_'.$courole);
4198: return reply($command,$env{'user.home'});
4199: } else {
4200: return 'refused';
4201: }
4202: }
4203:
4204: # ---------------- Make a metadata query against the network of library servers
4205:
4206: sub metadata_query {
4207: my ($query,$custom,$customshow,$server_array)=@_;
4208: my %rhash;
4209: my %libserv = &all_library();
4210: my @server_list = (defined($server_array) ? @$server_array
4211: : keys(%libserv) );
4212: for my $server (@server_list) {
4213: unless ($custom or $customshow) {
4214: my $reply=&reply("querysend:".&escape($query),$server);
4215: $rhash{$server}=$reply;
4216: }
4217: else {
4218: my $reply=&reply("querysend:".&escape($query).':'.
4219: &escape($custom).':'.&escape($customshow),
4220: $server);
4221: $rhash{$server}=$reply;
4222: }
4223: }
4224: return \%rhash;
4225: }
4226:
4227: # ----------------------------------------- Send log queries and wait for reply
4228:
4229: sub log_query {
4230: my ($uname,$udom,$query,%filters)=@_;
4231: my $uhome=&homeserver($uname,$udom);
4232: if ($uhome eq 'no_host') { return 'error: no_host'; }
4233: my $uhost=&hostname($uhome);
4234: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
4235: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4236: $uhome);
4237: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
4238: return get_query_reply($queryid);
4239: }
4240:
4241: # -------------------------- Update MySQL table for portfolio file
4242:
4243: sub update_portfolio_table {
4244: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
4245: my $homeserver = &homeserver($uname,$udom);
4246: my $queryid=
4247: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4248: ':'.&escape($file_name).':'.$action,$homeserver);
4249: my $reply = &get_query_reply($queryid);
4250: return $reply;
4251: }
4252:
4253: # ------- Request retrieval of institutional classlists for course(s)
4254:
4255: sub fetch_enrollment_query {
4256: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
4257: my $homeserver;
4258: my $maxtries = 1;
4259: if ($context eq 'automated') {
4260: $homeserver = $perlvar{'lonHostID'};
4261: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
4262: } else {
4263: $homeserver = &homeserver($cnum,$dom);
4264: }
4265: my $host=&hostname($homeserver);
4266: my $cmd = '';
4267: foreach my $affiliate (keys %{$affiliatesref}) {
4268: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4269: }
4270: $cmd =~ s/%%$//;
4271: $cmd = &escape($cmd);
4272: my $query = 'fetchenrollment';
4273: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
4274: unless ($queryid=~/^\Q$host\E\_/) {
4275: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4276: return 'error: '.$queryid;
4277: }
4278: my $reply = &get_query_reply($queryid);
4279: my $tries = 1;
4280: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4281: $reply = &get_query_reply($queryid);
4282: $tries ++;
4283: }
4284: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4285: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4286: } else {
4287: my @responses = split/:/,$reply;
4288: if ($homeserver eq $perlvar{'lonHostID'}) {
4289: foreach my $line (@responses) {
4290: my ($key,$value) = split(/=/,$line,2);
4291: $$replyref{$key} = $value;
4292: }
4293: } else {
4294: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
4295: foreach my $line (@responses) {
4296: my ($key,$value) = split(/=/,$line);
4297: $$replyref{$key} = $value;
4298: if ($value > 0) {
4299: foreach my $item (@{$$affiliatesref{$key}}) {
4300: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
4301: my $destname = $pathname.'/'.$filename;
4302: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
4303: if ($xml_classlist =~ /^error/) {
4304: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4305: } else {
4306: if ( open(FILE,">$destname") ) {
4307: print FILE &unescape($xml_classlist);
4308: close(FILE);
4309: } else {
4310: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
4311: }
4312: }
4313: }
4314: }
4315: }
4316: }
4317: return 'ok';
4318: }
4319: return 'error';
4320: }
4321:
4322: sub get_query_reply {
4323: my $queryid=shift;
4324: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4325: my $reply='';
4326: for (1..100) {
4327: sleep 2;
4328: if (-e $replyfile.'.end') {
4329: if (open(my $fh,$replyfile)) {
4330: $reply.=<$fh>;
4331: close($fh);
4332: } else { return 'error: reply_file_error'; }
4333: return &unescape($reply);
4334: }
4335: }
4336: return 'timeout:'.$queryid;
4337: }
4338:
4339: sub courselog_query {
4340: #
4341: # possible filters:
4342: # url: url or symb
4343: # username
4344: # domain
4345: # action: view, submit, grade
4346: # start: timestamp
4347: # end: timestamp
4348: #
4349: my (%filters)=@_;
4350: unless ($env{'request.course.id'}) { return 'no_course'; }
4351: if ($filters{'url'}) {
4352: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4353: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4354: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4355: }
4356: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4357: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4358: return &log_query($cname,$cdom,'courselog',%filters);
4359: }
4360:
4361: sub userlog_query {
4362: #
4363: # possible filters:
4364: # action: log check role
4365: # start: timestamp
4366: # end: timestamp
4367: #
4368: my ($uname,$udom,%filters)=@_;
4369: return &log_query($uname,$udom,'userlog',%filters);
4370: }
4371:
4372: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4373:
4374: sub auto_run {
4375: my ($cnum,$cdom) = @_;
4376: my $homeserver = &homeserver($cnum,$cdom);
4377: my $response = &reply('autorun:'.$cdom,$homeserver);
4378: return $response;
4379: }
4380:
4381: sub auto_get_sections {
4382: my ($cnum,$cdom,$inst_coursecode) = @_;
4383: my $homeserver = &homeserver($cnum,$cdom);
4384: my @secs = ();
4385: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
4386: unless ($response eq 'refused') {
4387: @secs = split/:/,$response;
4388: }
4389: return @secs;
4390: }
4391:
4392: sub auto_new_course {
4393: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4394: my $homeserver = &homeserver($cnum,$cdom);
4395: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
4396: return $response;
4397: }
4398:
4399: sub auto_validate_courseID {
4400: my ($cnum,$cdom,$inst_course_id) = @_;
4401: my $homeserver = &homeserver($cnum,$cdom);
4402: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
4403: return $response;
4404: }
4405:
4406: sub auto_create_password {
4407: my ($cnum,$cdom,$authparam) = @_;
4408: my $homeserver = &homeserver($cnum,$cdom);
4409: my $create_passwd = 0;
4410: my $authchk = '';
4411: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4412: if ($response eq 'refused') {
4413: $authchk = 'refused';
4414: } else {
4415: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4416: }
4417: return ($authparam,$create_passwd,$authchk);
4418: }
4419:
4420: sub auto_photo_permission {
4421: my ($cnum,$cdom,$students) = @_;
4422: my $homeserver = &homeserver($cnum,$cdom);
4423: my ($outcome,$perm_reqd,$conditions) =
4424: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
4425: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4426: return (undef,undef);
4427: }
4428: return ($outcome,$perm_reqd,$conditions);
4429: }
4430:
4431: sub auto_checkphotos {
4432: my ($uname,$udom,$pid) = @_;
4433: my $homeserver = &homeserver($uname,$udom);
4434: my ($result,$resulttype);
4435: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
4436: &escape($uname).':'.&escape($pid),
4437: $homeserver));
4438: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4439: return (undef,undef);
4440: }
4441: if ($outcome) {
4442: ($result,$resulttype) = split(/:/,$outcome);
4443: }
4444: return ($result,$resulttype);
4445: }
4446:
4447: sub auto_photochoice {
4448: my ($cnum,$cdom) = @_;
4449: my $homeserver = &homeserver($cnum,$cdom);
4450: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
4451: &escape($cdom),
4452: $homeserver)));
4453: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4454: return (undef,undef);
4455: }
4456: return ($update,$comment);
4457: }
4458:
4459: sub auto_photoupdate {
4460: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4461: my $homeserver = &homeserver($cnum,$dom);
4462: my $host=&hostname($homeserver);
4463: my $cmd = '';
4464: my $maxtries = 1;
4465: foreach my $affiliate (keys(%{$affiliatesref})) {
4466: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4467: }
4468: $cmd =~ s/%%$//;
4469: $cmd = &escape($cmd);
4470: my $query = 'institutionalphotos';
4471: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4472: unless ($queryid=~/^\Q$host\E\_/) {
4473: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4474: return 'error: '.$queryid;
4475: }
4476: my $reply = &get_query_reply($queryid);
4477: my $tries = 1;
4478: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4479: $reply = &get_query_reply($queryid);
4480: $tries ++;
4481: }
4482: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4483: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4484: } else {
4485: my @responses = split(/:/,$reply);
4486: my $outcome = shift(@responses);
4487: foreach my $item (@responses) {
4488: my ($key,$value) = split(/=/,$item);
4489: $$photo{$key} = $value;
4490: }
4491: return $outcome;
4492: }
4493: return 'error';
4494: }
4495:
4496: sub auto_instcode_format {
4497: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4498: $cat_order) = @_;
4499: my $courses = '';
4500: my @homeservers;
4501: if ($caller eq 'global') {
4502: my %servers = &get_servers($codedom,'library');
4503: foreach my $tryserver (keys(%servers)) {
4504: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4505: push(@homeservers,$tryserver);
4506: }
4507: }
4508: } else {
4509: push(@homeservers,&homeserver($caller,$codedom));
4510: }
4511: foreach my $code (keys(%{$instcodes})) {
4512: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
4513: }
4514: chop($courses);
4515: my $ok_response = 0;
4516: my $response;
4517: while (@homeservers > 0 && $ok_response == 0) {
4518: my $server = shift(@homeservers);
4519: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4520: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4521: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
4522: split/:/,$response;
4523: %{$codes} = (%{$codes},&str2hash($codes_str));
4524: push(@{$codetitles},&str2array($codetitles_str));
4525: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4526: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4527: $ok_response = 1;
4528: }
4529: }
4530: if ($ok_response) {
4531: return 'ok';
4532: } else {
4533: return $response;
4534: }
4535: }
4536:
4537: sub auto_instcode_defaults {
4538: my ($domain,$returnhash,$code_order) = @_;
4539: my @homeservers;
4540:
4541: my %servers = &get_servers($domain,'library');
4542: foreach my $tryserver (keys(%servers)) {
4543: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4544: push(@homeservers,$tryserver);
4545: }
4546: }
4547:
4548: my $response;
4549: foreach my $server (@homeservers) {
4550: $response=&reply('autoinstcodedefaults:'.$domain,$server);
4551: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4552:
4553: foreach my $pair (split(/\&/,$response)) {
4554: my ($name,$value)=split(/\=/,$pair);
4555: if ($name eq 'code_order') {
4556: @{$code_order} = split(/\&/,&unescape($value));
4557: } else {
4558: $returnhash->{&unescape($name)}=&unescape($value);
4559: }
4560: }
4561: return 'ok';
4562: }
4563:
4564: return $response;
4565: }
4566:
4567: sub auto_validate_class_sec {
4568: my ($cdom,$cnum,$owner,$inst_class) = @_;
4569: my $homeserver = &homeserver($cnum,$cdom);
4570: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
4571: &escape($owner).':'.$cdom,$homeserver);
4572: return $response;
4573: }
4574:
4575: # ------------------------------------------------------- Course Group routines
4576:
4577: sub get_coursegroups {
4578: my ($cdom,$cnum,$group,$namespace) = @_;
4579: return(&dump($namespace,$cdom,$cnum,$group));
4580: }
4581:
4582: sub modify_coursegroup {
4583: my ($cdom,$cnum,$groupsettings) = @_;
4584: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4585: }
4586:
4587: sub toggle_coursegroup_status {
4588: my ($cdom,$cnum,$group,$action) = @_;
4589: my ($from_namespace,$to_namespace);
4590: if ($action eq 'delete') {
4591: $from_namespace = 'coursegroups';
4592: $to_namespace = 'deleted_groups';
4593: } else {
4594: $from_namespace = 'deleted_groups';
4595: $to_namespace = 'coursegroups';
4596: }
4597: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
4598: if (my $tmp = &error(%curr_group)) {
4599: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4600: return ('read error',$tmp);
4601: } else {
4602: my %savedsettings = %curr_group;
4603: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
4604: my $deloutcome;
4605: if ($result eq 'ok') {
4606: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
4607: } else {
4608: return ('write error',$result);
4609: }
4610: if ($deloutcome eq 'ok') {
4611: return 'ok';
4612: } else {
4613: return ('delete error',$deloutcome);
4614: }
4615: }
4616: }
4617:
4618: sub modify_group_roles {
4619: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4620: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4621: my $role = 'gr/'.&escape($userprivs);
4622: my ($uname,$udom) = split(/:/,$user);
4623: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
4624: if ($result eq 'ok') {
4625: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4626: }
4627: return $result;
4628: }
4629:
4630: sub modify_coursegroup_membership {
4631: my ($cdom,$cnum,$membership) = @_;
4632: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4633: return $result;
4634: }
4635:
4636: sub get_active_groups {
4637: my ($udom,$uname,$cdom,$cnum) = @_;
4638: my $now = time;
4639: my %groups = ();
4640: foreach my $key (keys(%env)) {
4641: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
4642: my ($start,$end) = split(/\./,$env{$key});
4643: if (($end!=0) && ($end<$now)) { next; }
4644: if (($start!=0) && ($start>$now)) { next; }
4645: if ($1 eq $cdom && $2 eq $cnum) {
4646: $groups{$3} = $env{$key} ;
4647: }
4648: }
4649: }
4650: return %groups;
4651: }
4652:
4653: sub get_group_membership {
4654: my ($cdom,$cnum,$group) = @_;
4655: return(&dump('groupmembership',$cdom,$cnum,$group));
4656: }
4657:
4658: sub get_users_groups {
4659: my ($udom,$uname,$courseid) = @_;
4660: my @usersgroups;
4661: my $cachetime=1800;
4662:
4663: my $hashid="$udom:$uname:$courseid";
4664: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4665: if (defined($cached)) {
4666: @usersgroups = split(/:/,$grouplist);
4667: } else {
4668: $grouplist = '';
4669: my $courseurl = &courseid_to_courseurl($courseid);
4670: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
4671: my $access_end = $env{'course.'.$courseid.
4672: '.default_enrollment_end_date'};
4673: my $now = time;
4674: foreach my $key (keys(%roleshash)) {
4675: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4676: my $group = $1;
4677: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4678: my $start = $2;
4679: my $end = $1;
4680: if ($start == -1) { next; } # deleted from group
4681: if (($start!=0) && ($start>$now)) { next; }
4682: if (($end!=0) && ($end<$now)) {
4683: if ($access_end && $access_end < $now) {
4684: if ($access_end - $end < 86400) {
4685: push(@usersgroups,$group);
4686: }
4687: }
4688: next;
4689: }
4690: push(@usersgroups,$group);
4691: }
4692: }
4693: }
4694: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4695: $grouplist = join(':',@usersgroups);
4696: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4697: }
4698: return @usersgroups;
4699: }
4700:
4701: sub devalidate_getgroups_cache {
4702: my ($udom,$uname,$cdom,$cnum)=@_;
4703: my $courseid = $cdom.'_'.$cnum;
4704:
4705: my $hashid="$udom:$uname:$courseid";
4706: &devalidate_cache_new('getgroups',$hashid);
4707: }
4708:
4709: # ------------------------------------------------------------------ Plain Text
4710:
4711: sub plaintext {
4712: my ($short,$type,$cid) = @_;
4713: if ($short =~ /^cr/) {
4714: return (split('/',$short))[-1];
4715: }
4716: if (!defined($cid)) {
4717: $cid = $env{'request.course.id'};
4718: }
4719: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4720: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4721: '.plaintext'});
4722: }
4723: my %rolenames = (
4724: Course => 'std',
4725: Group => 'alt1',
4726: );
4727: if (defined($type) &&
4728: defined($rolenames{$type}) &&
4729: defined($prp{$short}{$rolenames{$type}})) {
4730: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4731: } else {
4732: return &Apache::lonlocal::mt($prp{$short}{'std'});
4733: }
4734: }
4735:
4736: # ----------------------------------------------------------------- Assign Role
4737:
4738: sub assignrole {
4739: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4740: my $mrole;
4741: if ($role =~ /^cr\//) {
4742: my $cwosec=$url;
4743: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4744: unless (&allowed('ccr',$cwosec)) {
4745: &logthis('Refused custom assignrole: '.
4746: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4747: $env{'user.name'}.' at '.$env{'user.domain'});
4748: return 'refused';
4749: }
4750: $mrole='cr';
4751: } elsif ($role =~ /^gr\//) {
4752: my $cwogrp=$url;
4753: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
4754: unless (&allowed('mdg',$cwogrp)) {
4755: &logthis('Refused group assignrole: '.
4756: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4757: $env{'user.name'}.' at '.$env{'user.domain'});
4758: return 'refused';
4759: }
4760: $mrole='gr';
4761: } else {
4762: my $cwosec=$url;
4763: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4764: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4765: &logthis('Refused assignrole: '.
4766: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4767: $env{'user.name'}.' at '.$env{'user.domain'});
4768: return 'refused';
4769: }
4770: $mrole=$role;
4771: }
4772: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4773: "$udom:$uname:$url".'_'."$mrole=$role";
4774: if ($end) { $command.='_'.$end; }
4775: if ($start) {
4776: if ($end) {
4777: $command.='_'.$start;
4778: } else {
4779: $command.='_0_'.$start;
4780: }
4781: }
4782: my $origstart = $start;
4783: my $origend = $end;
4784: # actually delete
4785: if ($deleteflag) {
4786: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4787: # modify command to delete the role
4788: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4789: "$udom:$uname:$url".'_'."$mrole";
4790: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4791: # set start and finish to negative values for userrolelog
4792: $start=-1;
4793: $end=-1;
4794: }
4795: }
4796: # send command
4797: my $answer=&reply($command,&homeserver($uname,$udom));
4798: # log new user role if status is ok
4799: if ($answer eq 'ok') {
4800: &userrolelog($role,$uname,$udom,$url,$start,$end);
4801: # for course roles, perform group memberships changes triggered by role change.
4802: unless ($role =~ /^gr/) {
4803: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4804: $origstart);
4805: }
4806: }
4807: return $answer;
4808: }
4809:
4810: # -------------------------------------------------- Modify user authentication
4811: # Overrides without validation
4812:
4813: sub modifyuserauth {
4814: my ($udom,$uname,$umode,$upass)=@_;
4815: my $uhome=&homeserver($uname,$udom);
4816: unless (&allowed('mau',$udom)) { return 'refused'; }
4817: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4818: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4819: ' in domain '.$env{'request.role.domain'});
4820: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4821: &escape($upass),$uhome);
4822: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4823: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4824: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4825: &log($udom,,$uname,$uhome,
4826: 'Authentication changed by '.$env{'user.domain'}.', '.
4827: $env{'user.name'}.', '.$umode.
4828: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4829: unless ($reply eq 'ok') {
4830: &logthis('Authentication mode error: '.$reply);
4831: return 'error: '.$reply;
4832: }
4833: return 'ok';
4834: }
4835:
4836: # --------------------------------------------------------------- Modify a user
4837:
4838: sub modifyuser {
4839: my ($udom, $uname, $uid,
4840: $umode, $upass, $first,
4841: $middle, $last, $gene,
4842: $forceid, $desiredhome, $email)=@_;
4843: $udom= &LONCAPA::clean_domain($udom);
4844: $uname=&LONCAPA::clean_username($uname);
4845: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4846: $umode.', '.$first.', '.$middle.', '.
4847: $last.', '.$gene.'(forceid: '.$forceid.')'.
4848: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4849: ' desiredhome not specified').
4850: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4851: ' in domain '.$env{'request.role.domain'});
4852: my $uhome=&homeserver($uname,$udom,'true');
4853: # ----------------------------------------------------------------- Create User
4854: if (($uhome eq 'no_host') &&
4855: (($umode && $upass) || ($umode eq 'localauth'))) {
4856: my $unhome='';
4857: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
4858: $unhome = $desiredhome;
4859: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4860: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4861: } else { # load balancing routine for determining $unhome
4862: my $loadm=10000000;
4863: my %servers = &get_servers($udom,'library');
4864: foreach my $tryserver (keys(%servers)) {
4865: my $answer=reply('load',$tryserver);
4866: if (($answer=~/\d+/) && ($answer<$loadm)) {
4867: $loadm=$answer;
4868: $unhome=$tryserver;
4869: }
4870: }
4871: }
4872: if (($unhome eq '') || ($unhome eq 'no_host')) {
4873: return 'error: unable to find a home server for '.$uname.
4874: ' in domain '.$udom;
4875: }
4876: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4877: &escape($upass),$unhome);
4878: unless ($reply eq 'ok') {
4879: return 'error: '.$reply;
4880: }
4881: $uhome=&homeserver($uname,$udom,'true');
4882: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4883: return 'error: unable verify users home machine.';
4884: }
4885: } # End of creation of new user
4886: # ---------------------------------------------------------------------- Add ID
4887: if ($uid) {
4888: $uid=~tr/A-Z/a-z/;
4889: my %uidhash=&idrget($udom,$uname);
4890: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4891: && (!$forceid)) {
4892: unless ($uid eq $uidhash{$uname}) {
4893: return 'error: user id "'.$uid.'" does not match '.
4894: 'current user id "'.$uidhash{$uname}.'".';
4895: }
4896: } else {
4897: &idput($udom,($uname => $uid));
4898: }
4899: }
4900: # -------------------------------------------------------------- Add names, etc
4901: my @tmp=&get('environment',
4902: ['firstname','middlename','lastname','generation'],
4903: $udom,$uname);
4904: my %names;
4905: if ($tmp[0] =~ m/^error:.*/) {
4906: %names=();
4907: } else {
4908: %names = @tmp;
4909: }
4910: #
4911: # Make sure to not trash student environment if instructor does not bother
4912: # to supply name and email information
4913: #
4914: if ($first) { $names{'firstname'} = $first; }
4915: if (defined($middle)) { $names{'middlename'} = $middle; }
4916: if ($last) { $names{'lastname'} = $last; }
4917: if (defined($gene)) { $names{'generation'} = $gene; }
4918: if ($email) {
4919: $email=~s/[^\w\@\.\-\,]//gs;
4920: if ($email=~/\@/) { $names{'notification'} = $email;
4921: $names{'critnotification'} = $email;
4922: $names{'permanentemail'} = $email; }
4923: }
4924: my $reply = &put('environment', \%names, $udom,$uname);
4925: if ($reply ne 'ok') { return 'error: '.$reply; }
4926: &devalidate_cache_new('namescache',$uname.':'.$udom);
4927: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
4928: $umode.', '.$first.', '.$middle.', '.
4929: $last.', '.$gene.' by '.
4930: $env{'user.name'}.' at '.$env{'user.domain'});
4931: return 'ok';
4932: }
4933:
4934: # -------------------------------------------------------------- Modify student
4935:
4936: sub modifystudent {
4937: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
4938: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
4939: if (!$cid) {
4940: unless ($cid=$env{'request.course.id'}) {
4941: return 'not_in_class';
4942: }
4943: }
4944: # --------------------------------------------------------------- Make the user
4945: my $reply=&modifyuser
4946: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
4947: $desiredhome,$email);
4948: unless ($reply eq 'ok') { return $reply; }
4949: # This will cause &modify_student_enrollment to get the uid from the
4950: # students environment
4951: $uid = undef if (!$forceid);
4952: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
4953: $gene,$usec,$end,$start,$type,$locktype,$cid);
4954: return $reply;
4955: }
4956:
4957: sub modify_student_enrollment {
4958: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
4959: my ($cdom,$cnum,$chome);
4960: if (!$cid) {
4961: unless ($cid=$env{'request.course.id'}) {
4962: return 'not_in_class';
4963: }
4964: $cdom=$env{'course.'.$cid.'.domain'};
4965: $cnum=$env{'course.'.$cid.'.num'};
4966: } else {
4967: ($cdom,$cnum)=split(/_/,$cid);
4968: }
4969: $chome=$env{'course.'.$cid.'.home'};
4970: if (!$chome) {
4971: $chome=&homeserver($cnum,$cdom);
4972: }
4973: if (!$chome) { return 'unknown_course'; }
4974: # Make sure the user exists
4975: my $uhome=&homeserver($uname,$udom);
4976: if (($uhome eq '') || ($uhome eq 'no_host')) {
4977: return 'error: no such user';
4978: }
4979: # Get student data if we were not given enough information
4980: if (!defined($first) || $first eq '' ||
4981: !defined($last) || $last eq '' ||
4982: !defined($uid) || $uid eq '' ||
4983: !defined($middle) || $middle eq '' ||
4984: !defined($gene) || $gene eq '') {
4985: # They did not supply us with enough data to enroll the student, so
4986: # we need to pick up more information.
4987: my %tmp = &get('environment',
4988: ['firstname','middlename','lastname', 'generation','id']
4989: ,$udom,$uname);
4990:
4991: #foreach my $key (keys(%tmp)) {
4992: # &logthis("key $key = ".$tmp{$key});
4993: #}
4994: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4995: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4996: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
4997: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
4998: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4999: }
5000: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
5001: my $reply=cput('classlist',
5002: {"$uname:$udom" =>
5003: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
5004: $cdom,$cnum);
5005: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5006: return 'error: '.$reply;
5007: } else {
5008: &devalidate_getsection_cache($udom,$uname,$cid);
5009: }
5010: # Add student role to user
5011: my $uurl='/'.$cid;
5012: $uurl=~s/\_/\//g;
5013: if ($usec) {
5014: $uurl.='/'.$usec;
5015: }
5016: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
5017: }
5018:
5019: sub format_name {
5020: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5021: my $name;
5022: if ($first ne 'lastname') {
5023: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5024: } else {
5025: if ($lastname=~/\S/) {
5026: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5027: $name=~s/\s+,/,/;
5028: } else {
5029: $name.= $firstname.' '.$middlename.' '.$generation;
5030: }
5031: }
5032: $name=~s/^\s+//;
5033: $name=~s/\s+$//;
5034: $name=~s/\s+/ /g;
5035: return $name;
5036: }
5037:
5038: # ------------------------------------------------- Write to course preferences
5039:
5040: sub writecoursepref {
5041: my ($courseid,%prefs)=@_;
5042: $courseid=~s/^\///;
5043: $courseid=~s/\_/\//g;
5044: my ($cdomain,$cnum)=split(/\//,$courseid);
5045: my $chome=homeserver($cnum,$cdomain);
5046: if (($chome eq '') || ($chome eq 'no_host')) {
5047: return 'error: no such course';
5048: }
5049: my $cstring='';
5050: foreach my $pref (keys(%prefs)) {
5051: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
5052: }
5053: $cstring=~s/\&$//;
5054: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5055: }
5056:
5057: # ---------------------------------------------------------- Make/modify course
5058:
5059: sub createcourse {
5060: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5061: $course_owner,$crstype)=@_;
5062: $url=&declutter($url);
5063: my $cid='';
5064: unless (&allowed('ccc',$udom)) {
5065: return 'refused';
5066: }
5067: # ------------------------------------------------------------------- Create ID
5068: my $uname=int(1+rand(9)).
5069: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5070: substr($$.time,0,5).unpack("H8",pack("I32",time)).
5071: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5072: # ----------------------------------------------- Make sure that does not exist
5073: my $uhome=&homeserver($uname,$udom,'true');
5074: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5075: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5076: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5077: $uhome=&homeserver($uname,$udom,'true');
5078: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5079: return 'error: unable to generate unique course-ID';
5080: }
5081: }
5082: # ------------------------------------------------ Check supplied server name
5083: $course_server = $env{'user.homeserver'} if (! defined($course_server));
5084: if (! &is_library($course_server)) {
5085: return 'error:bad server name '.$course_server;
5086: }
5087: # ------------------------------------------------------------- Make the course
5088: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
5089: $course_server);
5090: unless ($reply eq 'ok') { return 'error: '.$reply; }
5091: $uhome=&homeserver($uname,$udom,'true');
5092: if (($uhome eq '') || ($uhome eq 'no_host')) {
5093: return 'error: no such course';
5094: }
5095: # ----------------------------------------------------------------- Course made
5096: # log existence
5097: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
5098: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5099: &escape($crstype),$uhome);
5100: &flushcourselogs();
5101: # set toplevel url
5102: my $topurl=$url;
5103: unless ($nonstandard) {
5104: # ------------------------------------------ For standard courses, make top url
5105: my $mapurl=&clutter($url);
5106: if ($mapurl eq '/res/') { $mapurl=''; }
5107: $env{'form.initmap'}=(<<ENDINITMAP);
5108: <map>
5109: <resource id="1" type="start"></resource>
5110: <resource id="2" src="$mapurl"></resource>
5111: <resource id="3" type="finish"></resource>
5112: <link index="1" from="1" to="2"></link>
5113: <link index="2" from="2" to="3"></link>
5114: </map>
5115: ENDINITMAP
5116: $topurl=&declutter(
5117: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
5118: );
5119: }
5120: # ----------------------------------------------------------- Write preferences
5121: &writecoursepref($udom.'_'.$uname,
5122: ('description' => $description,
5123: 'url' => $topurl));
5124: return '/'.$udom.'/'.$uname;
5125: }
5126:
5127: sub is_course {
5128: my ($cdom,$cnum) = @_;
5129: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5130: undef,'.');
5131: if (exists($courses{$cdom.'_'.$cnum})) {
5132: return 1;
5133: }
5134: return 0;
5135: }
5136:
5137: # ---------------------------------------------------------- Assign Custom Role
5138:
5139: sub assigncustomrole {
5140: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
5141: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
5142: $end,$start,$deleteflag);
5143: }
5144:
5145: # ----------------------------------------------------------------- Revoke Role
5146:
5147: sub revokerole {
5148: my ($udom,$uname,$url,$role,$deleteflag)=@_;
5149: my $now=time;
5150: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
5151: }
5152:
5153: # ---------------------------------------------------------- Revoke Custom Role
5154:
5155: sub revokecustomrole {
5156: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
5157: my $now=time;
5158: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5159: $deleteflag);
5160: }
5161:
5162: # ------------------------------------------------------------ Disk usage
5163: sub diskusage {
5164: my ($udom,$uname,$directoryRoot)=@_;
5165: $directoryRoot =~ s/\/$//;
5166: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
5167: return $listing;
5168: }
5169:
5170: sub is_locked {
5171: my ($file_name, $domain, $user) = @_;
5172: my @check;
5173: my $is_locked;
5174: push @check, $file_name;
5175: my %locked = &get('file_permissions',\@check,
5176: $env{'user.domain'},$env{'user.name'});
5177: my ($tmp)=keys(%locked);
5178: if ($tmp=~/^error:/) { undef(%locked); }
5179:
5180: if (ref($locked{$file_name}) eq 'ARRAY') {
5181: $is_locked = 'false';
5182: foreach my $entry (@{$locked{$file_name}}) {
5183: if (ref($entry) eq 'ARRAY') {
5184: $is_locked = 'true';
5185: last;
5186: }
5187: }
5188: } else {
5189: $is_locked = 'false';
5190: }
5191: }
5192:
5193: sub declutter_portfile {
5194: my ($file) = @_;
5195: $file =~ s{^(/portfolio/|portfolio/)}{/};
5196: return $file;
5197: }
5198:
5199: # ------------------------------------------------------------- Mark as Read Only
5200:
5201: sub mark_as_readonly {
5202: my ($domain,$user,$files,$what) = @_;
5203: my %current_permissions = &dump('file_permissions',$domain,$user);
5204: my ($tmp)=keys(%current_permissions);
5205: if ($tmp=~/^error:/) { undef(%current_permissions); }
5206: foreach my $file (@{$files}) {
5207: $file = &declutter_portfile($file);
5208: push(@{$current_permissions{$file}},$what);
5209: }
5210: &put('file_permissions',\%current_permissions,$domain,$user);
5211: return;
5212: }
5213:
5214: # ------------------------------------------------------------Save Selected Files
5215:
5216: sub save_selected_files {
5217: my ($user, $path, @files) = @_;
5218: my $filename = $user."savedfiles";
5219: my @other_files = &files_not_in_path($user, $path);
5220: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5221: foreach my $file (@files) {
5222: print (OUT $env{'form.currentpath'}.$file."\n");
5223: }
5224: foreach my $file (@other_files) {
5225: print (OUT $file."\n");
5226: }
5227: close (OUT);
5228: return 'ok';
5229: }
5230:
5231: sub clear_selected_files {
5232: my ($user) = @_;
5233: my $filename = $user."savedfiles";
5234: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5235: print (OUT undef);
5236: close (OUT);
5237: return ("ok");
5238: }
5239:
5240: sub files_in_path {
5241: my ($user, $path) = @_;
5242: my $filename = $user."savedfiles";
5243: my %return_files;
5244: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5245: while (my $line_in = <IN>) {
5246: chomp ($line_in);
5247: my @paths_and_file = split (m!/!, $line_in);
5248: my $file_part = pop (@paths_and_file);
5249: my $path_part = join ('/', @paths_and_file);
5250: $path_part.='/';
5251: my $path_and_file = $path_part.$file_part;
5252: if ($path_part eq $path) {
5253: $return_files{$file_part}= 'selected';
5254: }
5255: }
5256: close (IN);
5257: return (\%return_files);
5258: }
5259:
5260: # called in portfolio select mode, to show files selected NOT in current directory
5261: sub files_not_in_path {
5262: my ($user, $path) = @_;
5263: my $filename = $user."savedfiles";
5264: my @return_files;
5265: my $path_part;
5266: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5267: while (my $line = <IN>) {
5268: #ok, I know it's clunky, but I want it to work
5269: my @paths_and_file = split(m|/|, $line);
5270: my $file_part = pop(@paths_and_file);
5271: chomp($file_part);
5272: my $path_part = join('/', @paths_and_file);
5273: $path_part .= '/';
5274: my $path_and_file = $path_part.$file_part;
5275: if ($path_part ne $path) {
5276: push(@return_files, ($path_and_file));
5277: }
5278: }
5279: close(OUT);
5280: return (@return_files);
5281: }
5282:
5283: #----------------------------------------------Get portfolio file permissions
5284:
5285: sub get_portfile_permissions {
5286: my ($domain,$user) = @_;
5287: my %current_permissions = &dump('file_permissions',$domain,$user);
5288: my ($tmp)=keys(%current_permissions);
5289: if ($tmp=~/^error:/) { undef(%current_permissions); }
5290: return \%current_permissions;
5291: }
5292:
5293: #---------------------------------------------Get portfolio file access controls
5294:
5295: sub get_access_controls {
5296: my ($current_permissions,$group,$file) = @_;
5297: my %access;
5298: my $real_file = $file;
5299: $file =~ s/\.meta$//;
5300: if (defined($file)) {
5301: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5302: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
5303: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
5304: }
5305: }
5306: } else {
5307: foreach my $key (keys(%{$current_permissions})) {
5308: if ($key =~ /\0accesscontrol$/) {
5309: if (defined($group)) {
5310: if ($key !~ m-^\Q$group\E/-) {
5311: next;
5312: }
5313: }
5314: my ($fullpath) = split(/\0/,$key);
5315: if (ref($$current_permissions{$key}) eq 'HASH') {
5316: foreach my $control (keys(%{$$current_permissions{$key}})) {
5317: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5318: }
5319: }
5320: }
5321: }
5322: }
5323: return %access;
5324: }
5325:
5326: sub modify_access_controls {
5327: my ($file_name,$changes,$domain,$user)=@_;
5328: my ($outcome,$deloutcome);
5329: my %store_permissions;
5330: my %new_values;
5331: my %new_control;
5332: my %translation;
5333: my @deletions = ();
5334: my $now = time;
5335: if (exists($$changes{'activate'})) {
5336: if (ref($$changes{'activate'}) eq 'HASH') {
5337: my @newitems = sort(keys(%{$$changes{'activate'}}));
5338: my $numnew = scalar(@newitems);
5339: for (my $i=0; $i<$numnew; $i++) {
5340: my $newkey = $newitems[$i];
5341: my $newid = &Apache::loncommon::get_cgi_id();
5342: if ($newkey =~ /^\d+:/) {
5343: $newkey =~ s/^(\d+)/$newid/;
5344: $translation{$1} = $newid;
5345: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5346: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5347: $translation{$1} = $newid;
5348: }
5349: $new_values{$file_name."\0".$newkey} =
5350: $$changes{'activate'}{$newitems[$i]};
5351: $new_control{$newkey} = $now;
5352: }
5353: }
5354: }
5355: my %todelete;
5356: my %changed_items;
5357: foreach my $action ('delete','update') {
5358: if (exists($$changes{$action})) {
5359: if (ref($$changes{$action}) eq 'HASH') {
5360: foreach my $key (keys(%{$$changes{$action}})) {
5361: my ($itemnum) = ($key =~ /^([^:]+):/);
5362: if ($action eq 'delete') {
5363: $todelete{$itemnum} = 1;
5364: } else {
5365: $changed_items{$itemnum} = $key;
5366: }
5367: }
5368: }
5369: }
5370: }
5371: # get lock on access controls for file.
5372: my $lockhash = {
5373: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5374: ':'.$env{'user.domain'},
5375: };
5376: my $tries = 0;
5377: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5378:
5379: while (($gotlock ne 'ok') && $tries <3) {
5380: $tries ++;
5381: sleep 1;
5382: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5383: }
5384: if ($gotlock eq 'ok') {
5385: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5386: my ($tmp)=keys(%curr_permissions);
5387: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5388: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5389: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5390: if (ref($curr_controls) eq 'HASH') {
5391: foreach my $control_item (keys(%{$curr_controls})) {
5392: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5393: if (defined($todelete{$itemnum})) {
5394: push(@deletions,$file_name."\0".$control_item);
5395: } else {
5396: if (defined($changed_items{$itemnum})) {
5397: $new_control{$changed_items{$itemnum}} = $now;
5398: push(@deletions,$file_name."\0".$control_item);
5399: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5400: } else {
5401: $new_control{$control_item} = $$curr_controls{$control_item};
5402: }
5403: }
5404: }
5405: }
5406: }
5407: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5408: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5409: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5410: # remove lock
5411: my @del_lock = ($file_name."\0".'locked_access_records');
5412: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5413: my ($file,$group);
5414: if (&is_course($domain,$user)) {
5415: ($group,$file) = split(/\//,$file_name,2);
5416: } else {
5417: $file = $file_name;
5418: }
5419: my $sqlresult =
5420: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5421: $group);
5422: } else {
5423: $outcome = "error: could not obtain lockfile\n";
5424: }
5425: return ($outcome,$deloutcome,\%new_values,\%translation);
5426: }
5427:
5428: sub make_public_indefinitely {
5429: my ($requrl) = @_;
5430: my $now = time;
5431: my $action = 'activate';
5432: my $aclnum = 0;
5433: if (&is_portfolio_url($requrl)) {
5434: my (undef,$udom,$unum,$file_name,$group) =
5435: &parse_portfolio_url($requrl);
5436: my $current_perms = &get_portfile_permissions($udom,$unum);
5437: my %access_controls = &get_access_controls($current_perms,
5438: $group,$file_name);
5439: foreach my $key (keys(%{$access_controls{$file_name}})) {
5440: my ($num,$scope,$end,$start) =
5441: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5442: if ($scope eq 'public') {
5443: if ($start <= $now && $end == 0) {
5444: $action = 'none';
5445: } else {
5446: $action = 'update';
5447: $aclnum = $num;
5448: }
5449: last;
5450: }
5451: }
5452: if ($action eq 'none') {
5453: return 'ok';
5454: } else {
5455: my %changes;
5456: my $newend = 0;
5457: my $newstart = $now;
5458: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5459: $changes{$action}{$newkey} = {
5460: type => 'public',
5461: time => {
5462: start => $newstart,
5463: end => $newend,
5464: },
5465: };
5466: my ($outcome,$deloutcome,$new_values,$translation) =
5467: &modify_access_controls($file_name,\%changes,$udom,$unum);
5468: return $outcome;
5469: }
5470: } else {
5471: return 'invalid';
5472: }
5473: }
5474:
5475: #------------------------------------------------------Get Marked as Read Only
5476:
5477: sub get_marked_as_readonly {
5478: my ($domain,$user,$what,$group) = @_;
5479: my $current_permissions = &get_portfile_permissions($domain,$user);
5480: my @readonly_files;
5481: my $cmp1=$what;
5482: if (ref($what)) { $cmp1=join('',@{$what}) };
5483: while (my ($file_name,$value) = each(%{$current_permissions})) {
5484: if (defined($group)) {
5485: if ($file_name !~ m-^\Q$group\E/-) {
5486: next;
5487: }
5488: }
5489: if (ref($value) eq "ARRAY"){
5490: foreach my $stored_what (@{$value}) {
5491: my $cmp2=$stored_what;
5492: if (ref($stored_what) eq 'ARRAY') {
5493: $cmp2=join('',@{$stored_what});
5494: }
5495: if ($cmp1 eq $cmp2) {
5496: push(@readonly_files, $file_name);
5497: last;
5498: } elsif (!defined($what)) {
5499: push(@readonly_files, $file_name);
5500: last;
5501: }
5502: }
5503: }
5504: }
5505: return @readonly_files;
5506: }
5507: #-----------------------------------------------------------Get Marked as Read Only Hash
5508:
5509: sub get_marked_as_readonly_hash {
5510: my ($current_permissions,$group,$what) = @_;
5511: my %readonly_files;
5512: while (my ($file_name,$value) = each(%{$current_permissions})) {
5513: if (defined($group)) {
5514: if ($file_name !~ m-^\Q$group\E/-) {
5515: next;
5516: }
5517: }
5518: if (ref($value) eq "ARRAY"){
5519: foreach my $stored_what (@{$value}) {
5520: if (ref($stored_what) eq 'ARRAY') {
5521: foreach my $lock_descriptor(@{$stored_what}) {
5522: if ($lock_descriptor eq 'graded') {
5523: $readonly_files{$file_name} = 'graded';
5524: } elsif ($lock_descriptor eq 'handback') {
5525: $readonly_files{$file_name} = 'handback';
5526: } else {
5527: if (!exists($readonly_files{$file_name})) {
5528: $readonly_files{$file_name} = 'locked';
5529: }
5530: }
5531: }
5532: }
5533: }
5534: }
5535: }
5536: return %readonly_files;
5537: }
5538: # ------------------------------------------------------------ Unmark as Read Only
5539:
5540: sub unmark_as_readonly {
5541: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5542: # for portfolio submissions, $what contains [$symb,$crsid]
5543: my ($domain,$user,$what,$file_name,$group) = @_;
5544: $file_name = &declutter_portfile($file_name);
5545: my $symb_crs = $what;
5546: if (ref($what)) { $symb_crs=join('',@$what); }
5547: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
5548: my ($tmp)=keys(%current_permissions);
5549: if ($tmp=~/^error:/) { undef(%current_permissions); }
5550: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
5551: foreach my $file (@readonly_files) {
5552: my $clean_file = &declutter_portfile($file);
5553: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
5554: my $current_locks = $current_permissions{$file};
5555: my @new_locks;
5556: my @del_keys;
5557: if (ref($current_locks) eq "ARRAY"){
5558: foreach my $locker (@{$current_locks}) {
5559: my $compare=$locker;
5560: if (ref($locker) eq 'ARRAY') {
5561: $compare=join('',@{$locker});
5562: if ($compare ne $symb_crs) {
5563: push(@new_locks, $locker);
5564: }
5565: }
5566: }
5567: if (scalar(@new_locks) > 0) {
5568: $current_permissions{$file} = \@new_locks;
5569: } else {
5570: push(@del_keys, $file);
5571: &del('file_permissions',\@del_keys, $domain, $user);
5572: delete($current_permissions{$file});
5573: }
5574: }
5575: }
5576: &put('file_permissions',\%current_permissions,$domain,$user);
5577: return;
5578: }
5579:
5580: # ------------------------------------------------------------ Directory lister
5581:
5582: sub dirlist {
5583: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5584:
5585: $uri=~s/^\///;
5586: $uri=~s/\/$//;
5587: my ($udom, $uname);
5588: (undef,$udom,$uname)=split(/\//,$uri);
5589: if(defined($userdomain)) {
5590: $udom = $userdomain;
5591: }
5592: if(defined($username)) {
5593: $uname = $username;
5594: }
5595:
5596: my $dirRoot = $perlvar{'lonDocRoot'};
5597: if(defined($alternateDirectoryRoot)) {
5598: $dirRoot = $alternateDirectoryRoot;
5599: $dirRoot =~ s/\/$//;
5600: }
5601:
5602: if($udom) {
5603: if($uname) {
5604: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5605: &homeserver($uname,$udom));
5606: my @listing_results;
5607: if ($listing eq 'unknown_cmd') {
5608: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5609: &homeserver($uname,$udom));
5610: @listing_results = split(/:/,$listing);
5611: } else {
5612: @listing_results = map { &unescape($_); } split(/:/,$listing);
5613: }
5614: return @listing_results;
5615: } elsif(!defined($alternateDirectoryRoot)) {
5616: my %allusers;
5617: my %servers = &get_servers($udom,'library');
5618: foreach my $tryserver (keys(%servers)) {
5619: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5620: $udom, $tryserver);
5621: my @listing_results;
5622: if ($listing eq 'unknown_cmd') {
5623: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5624: $udom, $tryserver);
5625: @listing_results = split(/:/,$listing);
5626: } else {
5627: @listing_results =
5628: map { &unescape($_); } split(/:/,$listing);
5629: }
5630: if ($listing_results[0] ne 'no_such_dir' &&
5631: $listing_results[0] ne 'empty' &&
5632: $listing_results[0] ne 'con_lost') {
5633: foreach my $line (@listing_results) {
5634: my ($entry) = split(/&/,$line,2);
5635: $allusers{$entry} = 1;
5636: }
5637: }
5638: }
5639: my $alluserstr='';
5640: foreach my $user (sort(keys(%allusers))) {
5641: $alluserstr.=$user.'&user:';
5642: }
5643: $alluserstr=~s/:$//;
5644: return split(/:/,$alluserstr);
5645: } else {
5646: return ('missing user name');
5647: }
5648: } elsif(!defined($alternateDirectoryRoot)) {
5649: my @all_domains = sort(&all_domains());
5650: foreach my $domain (@all_domains) {
5651: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5652: }
5653: return @all_domains;
5654: } else {
5655: return ('missing domain');
5656: }
5657: }
5658:
5659: # --------------------------------------------- GetFileTimestamp
5660: # This function utilizes dirlist and returns the date stamp for
5661: # when it was last modified. It will also return an error of -1
5662: # if an error occurs
5663:
5664: ##
5665: ## FIXME: This subroutine assumes its caller knows something about the
5666: ## directory structure of the home server for the student ($root).
5667: ## Not a good assumption to make. Since this is for looking up files
5668: ## in user directories, the full path should be constructed by lond, not
5669: ## whatever machine we request data from.
5670: ##
5671: sub GetFileTimestamp {
5672: my ($studentDomain,$studentName,$filename,$root)=@_;
5673: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5674: $studentName = &LONCAPA::clean_username($studentName);
5675: my $subdir=$studentName.'__';
5676: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5677: my $proname="$studentDomain/$subdir/$studentName";
5678: $proname .= '/'.$filename;
5679: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5680: $studentName, $root);
5681: my @stats = split('&', $fileStat);
5682: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5683: # @stats contains first the filename, then the stat output
5684: return $stats[10]; # so this is 10 instead of 9.
5685: } else {
5686: return -1;
5687: }
5688: }
5689:
5690: sub stat_file {
5691: my ($uri) = @_;
5692: $uri = &clutter_with_no_wrapper($uri);
5693:
5694: my ($udom,$uname,$file,$dir);
5695: if ($uri =~ m-^/(uploaded|editupload)/-) {
5696: ($udom,$uname,$file) =
5697: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
5698: $file = 'userfiles/'.$file;
5699: $dir = &propath($udom,$uname);
5700: }
5701: if ($uri =~ m-^/res/-) {
5702: ($udom,$uname) =
5703: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
5704: $file = $uri;
5705: }
5706:
5707: if (!$udom || !$uname || !$file) {
5708: # unable to handle the uri
5709: return ();
5710: }
5711:
5712: my ($result) = &dirlist($file,$udom,$uname,$dir);
5713: my @stats = split('&', $result);
5714:
5715: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5716: shift(@stats); #filename is first
5717: return @stats;
5718: }
5719: return ();
5720: }
5721:
5722: # -------------------------------------------------------- Value of a Condition
5723:
5724: # gets the value of a specific preevaluated condition
5725: # stored in the string $env{user.state.<cid>}
5726: # or looks up a condition reference in the bighash and if if hasn't
5727: # already been evaluated recurses into docondval to get the value of
5728: # the condition, then memoizing it to
5729: # $env{user.state.<cid>.<condition>}
5730: sub directcondval {
5731: my $number=shift;
5732: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5733: &Apache::lonuserstate::evalstate();
5734: }
5735: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5736: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5737: } elsif ($number =~ /^_/) {
5738: my $sub_condition;
5739: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5740: &GDBM_READER(),0640)) {
5741: $sub_condition=$bighash{'conditions'.$number};
5742: untie(%bighash);
5743: }
5744: my $value = &docondval($sub_condition);
5745: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5746: return $value;
5747: }
5748: if ($env{'user.state.'.$env{'request.course.id'}}) {
5749: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5750: } else {
5751: return 2;
5752: }
5753: }
5754:
5755: # get the collection of conditions for this resource
5756: sub condval {
5757: my $condidx=shift;
5758: my $allpathcond='';
5759: foreach my $cond (split(/\|/,$condidx)) {
5760: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5761: $allpathcond.=
5762: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5763: }
5764: }
5765: $allpathcond=~s/\|$//;
5766: return &docondval($allpathcond);
5767: }
5768:
5769: #evaluates an expression of conditions
5770: sub docondval {
5771: my ($allpathcond) = @_;
5772: my $result=0;
5773: if ($env{'request.course.id'}
5774: && defined($allpathcond)) {
5775: my $operand='|';
5776: my @stack;
5777: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5778: if ($chunk eq '(') {
5779: push @stack,($operand,$result);
5780: } elsif ($chunk eq ')') {
5781: my $before=pop @stack;
5782: if (pop @stack eq '&') {
5783: $result=$result>$before?$before:$result;
5784: } else {
5785: $result=$result>$before?$result:$before;
5786: }
5787: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5788: $operand=$chunk;
5789: } else {
5790: my $new=directcondval($chunk);
5791: if ($operand eq '&') {
5792: $result=$result>$new?$new:$result;
5793: } else {
5794: $result=$result>$new?$result:$new;
5795: }
5796: }
5797: }
5798: }
5799: return $result;
5800: }
5801:
5802: # ---------------------------------------------------- Devalidate courseresdata
5803:
5804: sub devalidatecourseresdata {
5805: my ($coursenum,$coursedomain)=@_;
5806: my $hashid=$coursenum.':'.$coursedomain;
5807: &devalidate_cache_new('courseres',$hashid);
5808: }
5809:
5810:
5811: # --------------------------------------------------- Course Resourcedata Query
5812:
5813: sub get_courseresdata {
5814: my ($coursenum,$coursedomain)=@_;
5815: my $coursehom=&homeserver($coursenum,$coursedomain);
5816: my $hashid=$coursenum.':'.$coursedomain;
5817: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5818: my %dumpreply;
5819: unless (defined($cached)) {
5820: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5821: $result=\%dumpreply;
5822: my ($tmp) = keys(%dumpreply);
5823: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5824: &do_cache_new('courseres',$hashid,$result,600);
5825: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5826: return $tmp;
5827: } elsif ($tmp =~ /^(error)/) {
5828: $result=undef;
5829: &do_cache_new('courseres',$hashid,$result,600);
5830: }
5831: }
5832: return $result;
5833: }
5834:
5835: sub devalidateuserresdata {
5836: my ($uname,$udom)=@_;
5837: my $hashid="$udom:$uname";
5838: &devalidate_cache_new('userres',$hashid);
5839: }
5840:
5841: sub get_userresdata {
5842: my ($uname,$udom)=@_;
5843: #most student don\'t have any data set, check if there is some data
5844: if (&EXT_cache_status($udom,$uname)) { return undef; }
5845:
5846: my $hashid="$udom:$uname";
5847: my ($result,$cached)=&is_cached_new('userres',$hashid);
5848: if (!defined($cached)) {
5849: my %resourcedata=&dump('resourcedata',$udom,$uname);
5850: $result=\%resourcedata;
5851: &do_cache_new('userres',$hashid,$result,600);
5852: }
5853: my ($tmp)=keys(%$result);
5854: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5855: return $result;
5856: }
5857: #error 2 occurs when the .db doesn't exist
5858: if ($tmp!~/error: 2 /) {
5859: &logthis("<font color=\"blue\">WARNING:".
5860: " Trying to get resource data for ".
5861: $uname." at ".$udom.": ".
5862: $tmp."</font>");
5863: } elsif ($tmp=~/error: 2 /) {
5864: #&EXT_cache_set($udom,$uname);
5865: &do_cache_new('userres',$hashid,undef,600);
5866: undef($tmp); # not really an error so don't send it back
5867: }
5868: return $tmp;
5869: }
5870:
5871: sub resdata {
5872: my ($name,$domain,$type,@which)=@_;
5873: my $result;
5874: if ($type eq 'course') {
5875: $result=&get_courseresdata($name,$domain);
5876: } elsif ($type eq 'user') {
5877: $result=&get_userresdata($name,$domain);
5878: }
5879: if (!ref($result)) { return $result; }
5880: foreach my $item (@which) {
5881: if (defined($result->{$item})) {
5882: return $result->{$item};
5883: }
5884: }
5885: return undef;
5886: }
5887:
5888: #
5889: # EXT resource caching routines
5890: #
5891:
5892: sub clear_EXT_cache_status {
5893: &delenv('cache.EXT.');
5894: }
5895:
5896: sub EXT_cache_status {
5897: my ($target_domain,$target_user) = @_;
5898: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5899: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
5900: # We know already the user has no data
5901: return 1;
5902: } else {
5903: return 0;
5904: }
5905: }
5906:
5907: sub EXT_cache_set {
5908: my ($target_domain,$target_user) = @_;
5909: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5910: #&appenv($cachename => time);
5911: }
5912:
5913: # --------------------------------------------------------- Value of a Variable
5914: sub EXT {
5915:
5916: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5917: unless ($varname) { return ''; }
5918: #get real user name/domain, courseid and symb
5919: my $courseid;
5920: my $publicuser;
5921: if ($symbparm) {
5922: $symbparm=&get_symb_from_alias($symbparm);
5923: }
5924: if (!($uname && $udom)) {
5925: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
5926: if (!$symbparm) { $symbparm=$cursymb; }
5927: } else {
5928: $courseid=$env{'request.course.id'};
5929: }
5930: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5931: my $rest;
5932: if (defined($therest[0])) {
5933: $rest=join('.',@therest);
5934: } else {
5935: $rest='';
5936: }
5937:
5938: my $qualifierrest=$qualifier;
5939: if ($rest) { $qualifierrest.='.'.$rest; }
5940: my $spacequalifierrest=$space;
5941: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
5942: if ($realm eq 'user') {
5943: # --------------------------------------------------------------- user.resource
5944: if ($space eq 'resource') {
5945: if ( (defined($Apache::lonhomework::parsing_a_problem)
5946: || defined($Apache::lonhomework::parsing_a_task))
5947: &&
5948: ($symbparm eq &symbread()) ) {
5949: # if we are in the middle of processing the resource the
5950: # get the value we are planning on committing
5951: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5952: return $Apache::lonhomework::results{$qualifierrest};
5953: } else {
5954: return $Apache::lonhomework::history{$qualifierrest};
5955: }
5956: } else {
5957: my %restored;
5958: if ($publicuser || $env{'request.state'} eq 'construct') {
5959: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5960: } else {
5961: %restored=&restore($symbparm,$courseid,$udom,$uname);
5962: }
5963: return $restored{$qualifierrest};
5964: }
5965: # ----------------------------------------------------------------- user.access
5966: } elsif ($space eq 'access') {
5967: # FIXME - not supporting calls for a specific user
5968: return &allowed($qualifier,$rest);
5969: # ------------------------------------------ user.preferences, user.environment
5970: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
5971: if (($uname eq $env{'user.name'}) &&
5972: ($udom eq $env{'user.domain'})) {
5973: return $env{join('.',('environment',$qualifierrest))};
5974: } else {
5975: my %returnhash;
5976: if (!$publicuser) {
5977: %returnhash=&userenvironment($udom,$uname,
5978: $qualifierrest);
5979: }
5980: return $returnhash{$qualifierrest};
5981: }
5982: # ----------------------------------------------------------------- user.course
5983: } elsif ($space eq 'course') {
5984: # FIXME - not supporting calls for a specific user
5985: return $env{join('.',('request.course',$qualifier))};
5986: # ------------------------------------------------------------------- user.role
5987: } elsif ($space eq 'role') {
5988: # FIXME - not supporting calls for a specific user
5989: my ($role,$where)=split(/\./,$env{'request.role'});
5990: if ($qualifier eq 'value') {
5991: return $role;
5992: } elsif ($qualifier eq 'extent') {
5993: return $where;
5994: }
5995: # ----------------------------------------------------------------- user.domain
5996: } elsif ($space eq 'domain') {
5997: return $udom;
5998: # ------------------------------------------------------------------- user.name
5999: } elsif ($space eq 'name') {
6000: return $uname;
6001: # ---------------------------------------------------- Any other user namespace
6002: } else {
6003: my %reply;
6004: if (!$publicuser) {
6005: %reply=&get($space,[$qualifierrest],$udom,$uname);
6006: }
6007: return $reply{$qualifierrest};
6008: }
6009: } elsif ($realm eq 'query') {
6010: # ---------------------------------------------- pull stuff out of query string
6011: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6012: [$spacequalifierrest]);
6013: return $env{'form.'.$spacequalifierrest};
6014: } elsif ($realm eq 'request') {
6015: # ------------------------------------------------------------- request.browser
6016: if ($space eq 'browser') {
6017: if ($qualifier eq 'textremote') {
6018: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
6019: return 1;
6020: } else {
6021: return 0;
6022: }
6023: } else {
6024: return $env{'browser.'.$qualifier};
6025: }
6026: # ------------------------------------------------------------ request.filename
6027: } else {
6028: return $env{'request.'.$spacequalifierrest};
6029: }
6030: } elsif ($realm eq 'course') {
6031: # ---------------------------------------------------------- course.description
6032: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
6033: } elsif ($realm eq 'resource') {
6034:
6035: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
6036: if (!$symbparm) { $symbparm=&symbread(); }
6037: }
6038:
6039: if ($space eq 'title') {
6040: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6041: return &gettitle($symbparm);
6042: }
6043:
6044: if ($space eq 'map') {
6045: my ($map) = &decode_symb($symbparm);
6046: return &symbread($map);
6047: }
6048:
6049: my ($section, $group, @groups);
6050: my ($courselevelm,$courselevel);
6051: if ($symbparm && defined($courseid) &&
6052: $courseid eq $env{'request.course.id'}) {
6053:
6054: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
6055:
6056: # ----------------------------------------------------- Cascading lookup scheme
6057: my $symbp=$symbparm;
6058: my $mapp=&deversion((&decode_symb($symbp))[0]);
6059:
6060: my $symbparm=$symbp.'.'.$spacequalifierrest;
6061: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6062:
6063: if (($env{'user.name'} eq $uname) &&
6064: ($env{'user.domain'} eq $udom)) {
6065: $section=$env{'request.course.sec'};
6066: @groups = split(/:/,$env{'request.course.groups'});
6067: @groups=&sort_course_groups($courseid,@groups);
6068: } else {
6069: if (! defined($usection)) {
6070: $section=&getsection($udom,$uname,$courseid);
6071: } else {
6072: $section = $usection;
6073: }
6074: @groups = &get_users_groups($udom,$uname,$courseid);
6075: }
6076:
6077: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6078: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6079: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6080:
6081: $courselevel=$courseid.'.'.$spacequalifierrest;
6082: my $courselevelr=$courseid.'.'.$symbparm;
6083: $courselevelm=$courseid.'.'.$mapparm;
6084:
6085: # ----------------------------------------------------------- first, check user
6086:
6087: my $userreply=&resdata($uname,$udom,'user',
6088: ($courselevelr,$courselevelm,
6089: $courselevel));
6090: if (defined($userreply)) { return $userreply; }
6091:
6092: # ------------------------------------------------ second, check some of course
6093: my $coursereply;
6094: if (@groups > 0) {
6095: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6096: $mapparm,$spacequalifierrest);
6097: if (defined($coursereply)) { return $coursereply; }
6098: }
6099:
6100: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6101: $env{'course.'.$courseid.'.domain'},
6102: 'course',
6103: ($seclevelr,$seclevelm,$seclevel,
6104: $courselevelr));
6105: if (defined($coursereply)) { return $coursereply; }
6106:
6107: # ------------------------------------------------------ third, check map parms
6108: my %parmhash=();
6109: my $thisparm='';
6110: if (tie(%parmhash,'GDBM_File',
6111: $env{'request.course.fn'}.'_parms.db',
6112: &GDBM_READER(),0640)) {
6113: $thisparm=$parmhash{$symbparm};
6114: untie(%parmhash);
6115: }
6116: if ($thisparm) { return $thisparm; }
6117: }
6118: # ------------------------------------------ fourth, look in resource metadata
6119:
6120: $spacequalifierrest=~s/\./\_/;
6121: my $filename;
6122: if (!$symbparm) { $symbparm=&symbread(); }
6123: if ($symbparm) {
6124: $filename=(&decode_symb($symbparm))[2];
6125: } else {
6126: $filename=$env{'request.filename'};
6127: }
6128: my $metadata=&metadata($filename,$spacequalifierrest);
6129: if (defined($metadata)) { return $metadata; }
6130: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
6131: if (defined($metadata)) { return $metadata; }
6132:
6133: # ---------------------------------------------- fourth, look in rest pf course
6134: if ($symbparm && defined($courseid) &&
6135: $courseid eq $env{'request.course.id'}) {
6136: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6137: $env{'course.'.$courseid.'.domain'},
6138: 'course',
6139: ($courselevelm,$courselevel));
6140: if (defined($coursereply)) { return $coursereply; }
6141: }
6142: # ------------------------------------------------------------------ Cascade up
6143: unless ($space eq '0') {
6144: my @parts=split(/_/,$space);
6145: my $id=pop(@parts);
6146: my $part=join('_',@parts);
6147: if ($part eq '') { $part='0'; }
6148: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
6149: $symbparm,$udom,$uname,$section,1);
6150: if (defined($partgeneral)) { return $partgeneral; }
6151: }
6152: if ($recurse) { return undef; }
6153: my $pack_def=&packages_tab_default($filename,$varname);
6154: if (defined($pack_def)) { return $pack_def; }
6155:
6156: # ---------------------------------------------------- Any other user namespace
6157: } elsif ($realm eq 'environment') {
6158: # ----------------------------------------------------------------- environment
6159: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6160: return $env{'environment.'.$spacequalifierrest};
6161: } else {
6162: if ($uname eq 'anonymous' && $udom eq '') {
6163: return '';
6164: }
6165: my %returnhash=&userenvironment($udom,$uname,
6166: $spacequalifierrest);
6167: return $returnhash{$spacequalifierrest};
6168: }
6169: } elsif ($realm eq 'system') {
6170: # ----------------------------------------------------------------- system.time
6171: if ($space eq 'time') {
6172: return time;
6173: }
6174: } elsif ($realm eq 'server') {
6175: # ----------------------------------------------------------------- system.time
6176: if ($space eq 'name') {
6177: return $ENV{'SERVER_NAME'};
6178: }
6179: }
6180: return '';
6181: }
6182:
6183: sub check_group_parms {
6184: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6185: my @groupitems = ();
6186: my $resultitem;
6187: my @levels = ($symbparm,$mapparm,$what);
6188: foreach my $group (@{$groups}) {
6189: foreach my $level (@levels) {
6190: my $item = $courseid.'.['.$group.'].'.$level;
6191: push(@groupitems,$item);
6192: }
6193: }
6194: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6195: $env{'course.'.$courseid.'.domain'},
6196: 'course',@groupitems);
6197: return $coursereply;
6198: }
6199:
6200: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
6201: my ($courseid,@groups) = @_;
6202: @groups = sort(@groups);
6203: return @groups;
6204: }
6205:
6206: sub packages_tab_default {
6207: my ($uri,$varname)=@_;
6208: my (undef,$part,$name)=split(/\./,$varname);
6209:
6210: my (@extension,@specifics,$do_default);
6211: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
6212: my ($pack_type,$pack_part)=split(/_/,$package,2);
6213: if ($pack_type eq 'default') {
6214: $do_default=1;
6215: } elsif ($pack_type eq 'extension') {
6216: push(@extension,[$package,$pack_type,$pack_part]);
6217: } elsif ($pack_part eq $part) {
6218: # only look at packages defaults for packages that this id is
6219: push(@specifics,[$package,$pack_type,$pack_part]);
6220: }
6221: }
6222: # first look for a package that matches the requested part id
6223: foreach my $package (@specifics) {
6224: my (undef,$pack_type,$pack_part)=@{$package};
6225: next if ($pack_part ne $part);
6226: if (defined($packagetab{"$pack_type&$name&default"})) {
6227: return $packagetab{"$pack_type&$name&default"};
6228: }
6229: }
6230: # look for any possible matching non extension_ package
6231: foreach my $package (@specifics) {
6232: my (undef,$pack_type,$pack_part)=@{$package};
6233: if (defined($packagetab{"$pack_type&$name&default"})) {
6234: return $packagetab{"$pack_type&$name&default"};
6235: }
6236: if ($pack_type eq 'part') { $pack_part='0'; }
6237: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6238: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
6239: }
6240: }
6241: # look for any posible extension_ match
6242: foreach my $package (@extension) {
6243: my ($package,$pack_type)=@{$package};
6244: if (defined($packagetab{"$pack_type&$name&default"})) {
6245: return $packagetab{"$pack_type&$name&default"};
6246: }
6247: if (defined($packagetab{$package."&$name&default"})) {
6248: return $packagetab{$package."&$name&default"};
6249: }
6250: }
6251: # look for a global default setting
6252: if ($do_default && defined($packagetab{"default&$name&default"})) {
6253: return $packagetab{"default&$name&default"};
6254: }
6255: return undef;
6256: }
6257:
6258: sub add_prefix_and_part {
6259: my ($prefix,$part)=@_;
6260: my $keyroot;
6261: if (defined($prefix) && $prefix !~ /^__/) {
6262: # prefix that has a part already
6263: $keyroot=$prefix;
6264: } elsif (defined($prefix)) {
6265: # prefix that is missing a part
6266: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6267: } else {
6268: # no prefix at all
6269: if (defined($part)) { $keyroot='_'.$part; }
6270: }
6271: return $keyroot;
6272: }
6273:
6274: # ---------------------------------------------------------------- Get metadata
6275:
6276: my %metaentry;
6277: sub metadata {
6278: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
6279: $uri=&declutter($uri);
6280: # if it is a non metadata possible uri return quickly
6281: if (($uri eq '') ||
6282: (($uri =~ m|^/*adm/|) &&
6283: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
6284: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
6285: ($uri =~ m|home/$match_username/public_html/|)) {
6286: return undef;
6287: }
6288: my $filename=$uri;
6289: $uri=~s/\.meta$//;
6290: #
6291: # Is the metadata already cached?
6292: # Look at timestamp of caching
6293: # Everything is cached by the main uri, libraries are never directly cached
6294: #
6295: if (!defined($liburi)) {
6296: my ($result,$cached)=&is_cached_new('meta',$uri);
6297: if (defined($cached)) { return $result->{':'.$what}; }
6298: }
6299: {
6300: #
6301: # Is this a recursive call for a library?
6302: #
6303: # if (! exists($metacache{$uri})) {
6304: # $metacache{$uri}={};
6305: # }
6306: if ($liburi) {
6307: $liburi=&declutter($liburi);
6308: $filename=$liburi;
6309: } else {
6310: &devalidate_cache_new('meta',$uri);
6311: undef(%metaentry);
6312: }
6313: my %metathesekeys=();
6314: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
6315: my $metastring;
6316: if ($uri !~ m -^(editupload)/-) {
6317: my $file=&filelocation('',&clutter($filename));
6318: #push(@{$metaentry{$uri.'.file'}},$file);
6319: $metastring=&getfile($file);
6320: }
6321: my $parser=HTML::LCParser->new(\$metastring);
6322: my $token;
6323: undef %metathesekeys;
6324: while ($token=$parser->get_token) {
6325: if ($token->[0] eq 'S') {
6326: if (defined($token->[2]->{'package'})) {
6327: #
6328: # This is a package - get package info
6329: #
6330: my $package=$token->[2]->{'package'};
6331: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6332: if (defined($token->[2]->{'id'})) {
6333: $keyroot.='_'.$token->[2]->{'id'};
6334: }
6335: if ($metaentry{':packages'}) {
6336: $metaentry{':packages'}.=','.$package.$keyroot;
6337: } else {
6338: $metaentry{':packages'}=$package.$keyroot;
6339: }
6340: foreach my $pack_entry (keys(%packagetab)) {
6341: my $part=$keyroot;
6342: $part=~s/^\_//;
6343: if ($pack_entry=~/^\Q$package\E\&/ ||
6344: $pack_entry=~/^\Q$package\E_0\&/) {
6345: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
6346: # ignore package.tab specified default values
6347: # here &package_tab_default() will fetch those
6348: if ($subp eq 'default') { next; }
6349: my $value=$packagetab{$pack_entry};
6350: my $unikey;
6351: if ($pack =~ /_0$/) {
6352: $unikey='parameter_0_'.$name;
6353: $part=0;
6354: } else {
6355: $unikey='parameter'.$keyroot.'_'.$name;
6356: }
6357: if ($subp eq 'display') {
6358: $value.=' [Part: '.$part.']';
6359: }
6360: $metaentry{':'.$unikey.'.part'}=$part;
6361: $metathesekeys{$unikey}=1;
6362: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6363: $metaentry{':'.$unikey.'.'.$subp}=$value;
6364: }
6365: if (defined($metaentry{':'.$unikey.'.default'})) {
6366: $metaentry{':'.$unikey}=
6367: $metaentry{':'.$unikey.'.default'};
6368: }
6369: }
6370: }
6371: } else {
6372: #
6373: # This is not a package - some other kind of start tag
6374: #
6375: my $entry=$token->[1];
6376: my $unikey;
6377: if ($entry eq 'import') {
6378: $unikey='';
6379: } else {
6380: $unikey=$entry;
6381: }
6382: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6383:
6384: if (defined($token->[2]->{'id'})) {
6385: $unikey.='_'.$token->[2]->{'id'};
6386: }
6387:
6388: if ($entry eq 'import') {
6389: #
6390: # Importing a library here
6391: #
6392: if ($depthcount<20) {
6393: my $location=$parser->get_text('/import');
6394: my $dir=$filename;
6395: $dir=~s|[^/]*$||;
6396: $location=&filelocation($dir,$location);
6397: my $metadata =
6398: &metadata($uri,'keys', $location,$unikey,
6399: $depthcount+1);
6400: foreach my $meta (split(',',$metadata)) {
6401: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6402: $metathesekeys{$meta}=1;
6403: }
6404: }
6405: } else {
6406:
6407: if (defined($token->[2]->{'name'})) {
6408: $unikey.='_'.$token->[2]->{'name'};
6409: }
6410: $metathesekeys{$unikey}=1;
6411: foreach my $param (@{$token->[3]}) {
6412: $metaentry{':'.$unikey.'.'.$param} =
6413: $token->[2]->{$param};
6414: }
6415: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
6416: my $default=$metaentry{':'.$unikey.'.default'};
6417: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6418: # only ws inside the tag, and not in default, so use default
6419: # as value
6420: $metaentry{':'.$unikey}=$default;
6421: } else {
6422: # either something interesting inside the tag or default
6423: # uninteresting
6424: $metaentry{':'.$unikey}=$internaltext;
6425: }
6426: # end of not-a-package not-a-library import
6427: }
6428: # end of not-a-package start tag
6429: }
6430: # the next is the end of "start tag"
6431: }
6432: }
6433: my ($extension) = ($uri =~ /\.(\w+)$/);
6434: foreach my $key (keys(%packagetab)) {
6435: #no specific packages #how's our extension
6436: if ($key!~/^extension_\Q$extension\E&/) { next; }
6437: &metadata_create_package_def($uri,$key,'extension_'.$extension,
6438: \%metathesekeys);
6439: }
6440: if (!exists($metaentry{':packages'})) {
6441: foreach my $key (keys(%packagetab)) {
6442: #no specific packages well let's get default then
6443: if ($key!~/^default&/) { next; }
6444: &metadata_create_package_def($uri,$key,'default',
6445: \%metathesekeys);
6446: }
6447: }
6448: # are there custom rights to evaluate
6449: if ($metaentry{':copyright'} eq 'custom') {
6450:
6451: #
6452: # Importing a rights file here
6453: #
6454: unless ($depthcount) {
6455: my $location=$metaentry{':customdistributionfile'};
6456: my $dir=$filename;
6457: $dir=~s|[^/]*$||;
6458: $location=&filelocation($dir,$location);
6459: my $rights_metadata =
6460: &metadata($uri,'keys',$location,'_rights',
6461: $depthcount+1);
6462: foreach my $rights (split(',',$rights_metadata)) {
6463: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6464: $metathesekeys{$rights}=1;
6465: }
6466: }
6467: }
6468: # uniqifiy package listing
6469: my %seen;
6470: my @uniq_packages =
6471: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6472: $metaentry{':packages'} = join(',',@uniq_packages);
6473:
6474: $metaentry{':keys'} = join(',',keys(%metathesekeys));
6475: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6476: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
6477: &do_cache_new('meta',$uri,\%metaentry,60*60);
6478: # this is the end of "was not already recently cached
6479: }
6480: return $metaentry{':'.$what};
6481: }
6482:
6483: sub metadata_create_package_def {
6484: my ($uri,$key,$package,$metathesekeys)=@_;
6485: my ($pack,$name,$subp)=split(/\&/,$key);
6486: if ($subp eq 'default') { next; }
6487:
6488: if (defined($metaentry{':packages'})) {
6489: $metaentry{':packages'}.=','.$package;
6490: } else {
6491: $metaentry{':packages'}=$package;
6492: }
6493: my $value=$packagetab{$key};
6494: my $unikey;
6495: $unikey='parameter_0_'.$name;
6496: $metaentry{':'.$unikey.'.part'}=0;
6497: $$metathesekeys{$unikey}=1;
6498: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6499: $metaentry{':'.$unikey.'.'.$subp}=$value;
6500: }
6501: if (defined($metaentry{':'.$unikey.'.default'})) {
6502: $metaentry{':'.$unikey}=
6503: $metaentry{':'.$unikey.'.default'};
6504: }
6505: }
6506:
6507: sub metadata_generate_part0 {
6508: my ($metadata,$metacache,$uri) = @_;
6509: my %allnames;
6510: foreach my $metakey (keys(%$metadata)) {
6511: if ($metakey=~/^parameter\_(.*)/) {
6512: my $part=$$metacache{':'.$metakey.'.part'};
6513: my $name=$$metacache{':'.$metakey.'.name'};
6514: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
6515: $allnames{$name}=$part;
6516: }
6517: }
6518: }
6519: foreach my $name (keys(%allnames)) {
6520: $$metadata{"parameter_0_$name"}=1;
6521: my $key=":parameter_0_$name";
6522: $$metacache{"$key.part"}='0';
6523: $$metacache{"$key.name"}=$name;
6524: $$metacache{"$key.type"}=$$metacache{':parameter_'.
6525: $allnames{$name}.'_'.$name.
6526: '.type'};
6527: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
6528: '.display'};
6529: my $expr='[Part: '.$allnames{$name}.']';
6530: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
6531: $$metacache{"$key.display"}=$olddis;
6532: }
6533: }
6534:
6535: # ------------------------------------------------------ Devalidate title cache
6536:
6537: sub devalidate_title_cache {
6538: my ($url)=@_;
6539: if (!$env{'request.course.id'}) { return; }
6540: my $symb=&symbread($url);
6541: if (!$symb) { return; }
6542: my $key=$env{'request.course.id'}."\0".$symb;
6543: &devalidate_cache_new('title',$key);
6544: }
6545:
6546: # ------------------------------------------------- Get the title of a resource
6547:
6548: sub gettitle {
6549: my $urlsymb=shift;
6550: my $symb=&symbread($urlsymb);
6551: if ($symb) {
6552: my $key=$env{'request.course.id'}."\0".$symb;
6553: my ($result,$cached)=&is_cached_new('title',$key);
6554: if (defined($cached)) {
6555: return $result;
6556: }
6557: my ($map,$resid,$url)=&decode_symb($symb);
6558: my $title='';
6559: my %bighash;
6560: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6561: &GDBM_READER(),0640)) {
6562: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6563: $title=$bighash{'title_'.$mapid.'.'.$resid};
6564: untie %bighash;
6565: }
6566: $title=~s/\&colon\;/\:/gs;
6567: if ($title) {
6568: return &do_cache_new('title',$key,$title,600);
6569: }
6570: $urlsymb=$url;
6571: }
6572: my $title=&metadata($urlsymb,'title');
6573: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6574: return $title;
6575: }
6576:
6577: sub get_slot {
6578: my ($which,$cnum,$cdom)=@_;
6579: if (!$cnum || !$cdom) {
6580: (undef,my $courseid)=&whichuser();
6581: $cdom=$env{'course.'.$courseid.'.domain'};
6582: $cnum=$env{'course.'.$courseid.'.num'};
6583: }
6584: my $key=join("\0",'slots',$cdom,$cnum,$which);
6585: my %slotinfo;
6586: if (exists($remembered{$key})) {
6587: $slotinfo{$which} = $remembered{$key};
6588: } else {
6589: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6590: &Apache::lonhomework::showhash(%slotinfo);
6591: my ($tmp)=keys(%slotinfo);
6592: if ($tmp=~/^error:/) { return (); }
6593: $remembered{$key} = $slotinfo{$which};
6594: }
6595: if (ref($slotinfo{$which}) eq 'HASH') {
6596: return %{$slotinfo{$which}};
6597: }
6598: return $slotinfo{$which};
6599: }
6600: # ------------------------------------------------- Update symbolic store links
6601:
6602: sub symblist {
6603: my ($mapname,%newhash)=@_;
6604: $mapname=&deversion(&declutter($mapname));
6605: my %hash;
6606: if (($env{'request.course.fn'}) && (%newhash)) {
6607: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6608: &GDBM_WRCREAT(),0640)) {
6609: foreach my $url (keys %newhash) {
6610: next if ($url eq 'last_known'
6611: && $env{'form.no_update_last_known'});
6612: $hash{declutter($url)}=&encode_symb($mapname,
6613: $newhash{$url}->[1],
6614: $newhash{$url}->[0]);
6615: }
6616: if (untie(%hash)) {
6617: return 'ok';
6618: }
6619: }
6620: }
6621: return 'error';
6622: }
6623:
6624: # --------------------------------------------------------------- Verify a symb
6625:
6626: sub symbverify {
6627: my ($symb,$thisurl)=@_;
6628: my $thisfn=$thisurl;
6629: $thisfn=&declutter($thisfn);
6630: # direct jump to resource in page or to a sequence - will construct own symbs
6631: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6632: # check URL part
6633: my ($map,$resid,$url)=&decode_symb($symb);
6634:
6635: unless ($url eq $thisfn) { return 0; }
6636:
6637: $symb=&symbclean($symb);
6638: $thisurl=&deversion($thisurl);
6639: $thisfn=&deversion($thisfn);
6640:
6641: my %bighash;
6642: my $okay=0;
6643:
6644: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6645: &GDBM_READER(),0640)) {
6646: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6647: unless ($ids) {
6648: $ids=$bighash{'ids_/'.$thisurl};
6649: }
6650: if ($ids) {
6651: # ------------------------------------------------------------------- Has ID(s)
6652: foreach my $id (split(/\,/,$ids)) {
6653: my ($mapid,$resid)=split(/\./,$id);
6654: if (
6655: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6656: eq $symb) {
6657: if (($env{'request.role.adv'}) ||
6658: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
6659: $okay=1;
6660: }
6661: }
6662: }
6663: }
6664: untie(%bighash);
6665: }
6666: return $okay;
6667: }
6668:
6669: # --------------------------------------------------------------- Clean-up symb
6670:
6671: sub symbclean {
6672: my $symb=shift;
6673: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6674: # remove version from map
6675: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6676:
6677: # remove version from URL
6678: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6679:
6680: # remove wrapper
6681:
6682: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6683: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6684: return $symb;
6685: }
6686:
6687: # ---------------------------------------------- Split symb to find map and url
6688:
6689: sub encode_symb {
6690: my ($map,$resid,$url)=@_;
6691: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6692: }
6693:
6694: sub decode_symb {
6695: my $symb=shift;
6696: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6697: my ($map,$resid,$url)=split(/___/,$symb);
6698: return (&fixversion($map),$resid,&fixversion($url));
6699: }
6700:
6701: sub fixversion {
6702: my $fn=shift;
6703: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6704: my %bighash;
6705: my $uri=&clutter($fn);
6706: my $key=$env{'request.course.id'}.'_'.$uri;
6707: # is this cached?
6708: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6709: if (defined($cached)) { return $result; }
6710: # unfortunately not cached, or expired
6711: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6712: &GDBM_READER(),0640)) {
6713: if ($bighash{'version_'.$uri}) {
6714: my $version=$bighash{'version_'.$uri};
6715: unless (($version eq 'mostrecent') ||
6716: ($version==&getversion($uri))) {
6717: $uri=~s/\.(\w+)$/\.$version\.$1/;
6718: }
6719: }
6720: untie %bighash;
6721: }
6722: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6723: }
6724:
6725: sub deversion {
6726: my $url=shift;
6727: $url=~s/\.\d+\.(\w+)$/\.$1/;
6728: return $url;
6729: }
6730:
6731: # ------------------------------------------------------ Return symb list entry
6732:
6733: sub symbread {
6734: my ($thisfn,$donotrecurse)=@_;
6735: my $cache_str='request.symbread.cached.'.$thisfn;
6736: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6737: # no filename provided? try from environment
6738: unless ($thisfn) {
6739: if ($env{'request.symb'}) {
6740: return $env{$cache_str}=&symbclean($env{'request.symb'});
6741: }
6742: $thisfn=$env{'request.filename'};
6743: }
6744: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6745: # is that filename actually a symb? Verify, clean, and return
6746: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6747: if (&symbverify($thisfn,$1)) {
6748: return $env{$cache_str}=&symbclean($thisfn);
6749: }
6750: }
6751: $thisfn=declutter($thisfn);
6752: my %hash;
6753: my %bighash;
6754: my $syval='';
6755: if (($env{'request.course.fn'}) && ($thisfn)) {
6756: my $targetfn = $thisfn;
6757: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6758: $targetfn = 'adm/wrapper/'.$thisfn;
6759: }
6760: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6761: $targetfn=$1;
6762: }
6763: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6764: &GDBM_READER(),0640)) {
6765: $syval=$hash{$targetfn};
6766: untie(%hash);
6767: }
6768: # ---------------------------------------------------------- There was an entry
6769: if ($syval) {
6770: #unless ($syval=~/\_\d+$/) {
6771: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6772: #&appenv('request.ambiguous' => $thisfn);
6773: #return $env{$cache_str}='';
6774: #}
6775: #$syval.=$1;
6776: #}
6777: } else {
6778: # ------------------------------------------------------- Was not in symb table
6779: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6780: &GDBM_READER(),0640)) {
6781: # ---------------------------------------------- Get ID(s) for current resource
6782: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6783: unless ($ids) {
6784: $ids=$bighash{'ids_/'.$thisfn};
6785: }
6786: unless ($ids) {
6787: # alias?
6788: $ids=$bighash{'mapalias_'.$thisfn};
6789: }
6790: if ($ids) {
6791: # ------------------------------------------------------------------- Has ID(s)
6792: my @possibilities=split(/\,/,$ids);
6793: if ($#possibilities==0) {
6794: # ----------------------------------------------- There is only one possibility
6795: my ($mapid,$resid)=split(/\./,$ids);
6796: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6797: $resid,$thisfn);
6798: } elsif (!$donotrecurse) {
6799: # ------------------------------------------ There is more than one possibility
6800: my $realpossible=0;
6801: foreach my $id (@possibilities) {
6802: my $file=$bighash{'src_'.$id};
6803: if (&allowed('bre',$file)) {
6804: my ($mapid,$resid)=split(/\./,$id);
6805: if ($bighash{'map_type_'.$mapid} ne 'page') {
6806: $realpossible++;
6807: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6808: $resid,$thisfn);
6809: }
6810: }
6811: }
6812: if ($realpossible!=1) { $syval=''; }
6813: } else {
6814: $syval='';
6815: }
6816: }
6817: untie(%bighash)
6818: }
6819: }
6820: if ($syval) {
6821: return $env{$cache_str}=$syval;
6822: }
6823: }
6824: &appenv('request.ambiguous' => $thisfn);
6825: return $env{$cache_str}='';
6826: }
6827:
6828: # ---------------------------------------------------------- Return random seed
6829:
6830: sub numval {
6831: my $txt=shift;
6832: $txt=~tr/A-J/0-9/;
6833: $txt=~tr/a-j/0-9/;
6834: $txt=~tr/K-T/0-9/;
6835: $txt=~tr/k-t/0-9/;
6836: $txt=~tr/U-Z/0-5/;
6837: $txt=~tr/u-z/0-5/;
6838: $txt=~s/\D//g;
6839: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6840: return int($txt);
6841: }
6842:
6843: sub numval2 {
6844: my $txt=shift;
6845: $txt=~tr/A-J/0-9/;
6846: $txt=~tr/a-j/0-9/;
6847: $txt=~tr/K-T/0-9/;
6848: $txt=~tr/k-t/0-9/;
6849: $txt=~tr/U-Z/0-5/;
6850: $txt=~tr/u-z/0-5/;
6851: $txt=~s/\D//g;
6852: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6853: my $total;
6854: foreach my $val (@txts) { $total+=$val; }
6855: if ($_64bit) { if ($total > 2**32) { return -1; } }
6856: return int($total);
6857: }
6858:
6859: sub numval3 {
6860: use integer;
6861: my $txt=shift;
6862: $txt=~tr/A-J/0-9/;
6863: $txt=~tr/a-j/0-9/;
6864: $txt=~tr/K-T/0-9/;
6865: $txt=~tr/k-t/0-9/;
6866: $txt=~tr/U-Z/0-5/;
6867: $txt=~tr/u-z/0-5/;
6868: $txt=~s/\D//g;
6869: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6870: my $total;
6871: foreach my $val (@txts) { $total+=$val; }
6872: if ($_64bit) { $total=(($total<<32)>>32); }
6873: return $total;
6874: }
6875:
6876: sub digest {
6877: my ($data)=@_;
6878: my $digest=&Digest::MD5::md5($data);
6879: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6880: my ($e,$f);
6881: {
6882: use integer;
6883: $e=($a+$b);
6884: $f=($c+$d);
6885: if ($_64bit) {
6886: $e=(($e<<32)>>32);
6887: $f=(($f<<32)>>32);
6888: }
6889: }
6890: if (wantarray) {
6891: return ($e,$f);
6892: } else {
6893: my $g;
6894: {
6895: use integer;
6896: $g=($e+$f);
6897: if ($_64bit) {
6898: $g=(($g<<32)>>32);
6899: }
6900: }
6901: return $g;
6902: }
6903: }
6904:
6905: sub latest_rnd_algorithm_id {
6906: return '64bit5';
6907: }
6908:
6909: sub get_rand_alg {
6910: my ($courseid)=@_;
6911: if (!$courseid) { $courseid=(&whichuser())[1]; }
6912: if ($courseid) {
6913: return $env{"course.$courseid.rndseed"};
6914: }
6915: return &latest_rnd_algorithm_id();
6916: }
6917:
6918: sub validCODE {
6919: my ($CODE)=@_;
6920: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6921: return 0;
6922: }
6923:
6924: sub getCODE {
6925: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
6926: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6927: defined($Apache::lonhomework::parsing_a_task) ) &&
6928: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
6929: return $Apache::lonhomework::history{'resource.CODE'};
6930: }
6931: return undef;
6932: }
6933:
6934: sub rndseed {
6935: my ($symb,$courseid,$domain,$username)=@_;
6936: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
6937: if (!$symb) {
6938: unless ($symb=$wsymb) { return time; }
6939: }
6940: if (!$courseid) { $courseid=$wcourseid; }
6941: if (!$domain) { $domain=$wdomain; }
6942: if (!$username) { $username=$wusername }
6943: my $which=&get_rand_alg();
6944:
6945: if (defined(&getCODE())) {
6946: if ($which eq '64bit5') {
6947: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6948: } elsif ($which eq '64bit4') {
6949: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6950: } else {
6951: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6952: }
6953: } elsif ($which eq '64bit5') {
6954: return &rndseed_64bit5($symb,$courseid,$domain,$username);
6955: } elsif ($which eq '64bit4') {
6956: return &rndseed_64bit4($symb,$courseid,$domain,$username);
6957: } elsif ($which eq '64bit3') {
6958: return &rndseed_64bit3($symb,$courseid,$domain,$username);
6959: } elsif ($which eq '64bit2') {
6960: return &rndseed_64bit2($symb,$courseid,$domain,$username);
6961: } elsif ($which eq '64bit') {
6962: return &rndseed_64bit($symb,$courseid,$domain,$username);
6963: }
6964: return &rndseed_32bit($symb,$courseid,$domain,$username);
6965: }
6966:
6967: sub rndseed_32bit {
6968: my ($symb,$courseid,$domain,$username)=@_;
6969: {
6970: use integer;
6971: my $symbchck=unpack("%32C*",$symb) << 27;
6972: my $symbseed=numval($symb) << 22;
6973: my $namechck=unpack("%32C*",$username) << 17;
6974: my $nameseed=numval($username) << 12;
6975: my $domainseed=unpack("%32C*",$domain) << 7;
6976: my $courseseed=unpack("%32C*",$courseid);
6977: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6978: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6979: #&logthis("rndseed :$num:$symb");
6980: if ($_64bit) { $num=(($num<<32)>>32); }
6981: return $num;
6982: }
6983: }
6984:
6985: sub rndseed_64bit {
6986: my ($symb,$courseid,$domain,$username)=@_;
6987: {
6988: use integer;
6989: my $symbchck=unpack("%32S*",$symb) << 21;
6990: my $symbseed=numval($symb) << 10;
6991: my $namechck=unpack("%32S*",$username);
6992:
6993: my $nameseed=numval($username) << 21;
6994: my $domainseed=unpack("%32S*",$domain) << 10;
6995: my $courseseed=unpack("%32S*",$courseid);
6996:
6997: my $num1=$symbchck+$symbseed+$namechck;
6998: my $num2=$nameseed+$domainseed+$courseseed;
6999: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7000: #&logthis("rndseed :$num:$symb");
7001: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7002: return "$num1,$num2";
7003: }
7004: }
7005:
7006: sub rndseed_64bit2 {
7007: my ($symb,$courseid,$domain,$username)=@_;
7008: {
7009: use integer;
7010: # strings need to be an even # of cahracters long, it it is odd the
7011: # last characters gets thrown away
7012: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7013: my $symbseed=numval($symb) << 10;
7014: my $namechck=unpack("%32S*",$username.' ');
7015:
7016: my $nameseed=numval($username) << 21;
7017: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7018: my $courseseed=unpack("%32S*",$courseid.' ');
7019:
7020: my $num1=$symbchck+$symbseed+$namechck;
7021: my $num2=$nameseed+$domainseed+$courseseed;
7022: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7023: #&logthis("rndseed :$num:$symb");
7024: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7025: return "$num1,$num2";
7026: }
7027: }
7028:
7029: sub rndseed_64bit3 {
7030: my ($symb,$courseid,$domain,$username)=@_;
7031: {
7032: use integer;
7033: # strings need to be an even # of cahracters long, it it is odd the
7034: # last characters gets thrown away
7035: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7036: my $symbseed=numval2($symb) << 10;
7037: my $namechck=unpack("%32S*",$username.' ');
7038:
7039: my $nameseed=numval2($username) << 21;
7040: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7041: my $courseseed=unpack("%32S*",$courseid.' ');
7042:
7043: my $num1=$symbchck+$symbseed+$namechck;
7044: my $num2=$nameseed+$domainseed+$courseseed;
7045: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7046: #&logthis("rndseed :$num1:$num2:$_64bit");
7047: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7048:
7049: return "$num1:$num2";
7050: }
7051: }
7052:
7053: sub rndseed_64bit4 {
7054: my ($symb,$courseid,$domain,$username)=@_;
7055: {
7056: use integer;
7057: # strings need to be an even # of cahracters long, it it is odd the
7058: # last characters gets thrown away
7059: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7060: my $symbseed=numval3($symb) << 10;
7061: my $namechck=unpack("%32S*",$username.' ');
7062:
7063: my $nameseed=numval3($username) << 21;
7064: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7065: my $courseseed=unpack("%32S*",$courseid.' ');
7066:
7067: my $num1=$symbchck+$symbseed+$namechck;
7068: my $num2=$nameseed+$domainseed+$courseseed;
7069: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7070: #&logthis("rndseed :$num1:$num2:$_64bit");
7071: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7072:
7073: return "$num1:$num2";
7074: }
7075: }
7076:
7077: sub rndseed_64bit5 {
7078: my ($symb,$courseid,$domain,$username)=@_;
7079: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7080: return "$num1:$num2";
7081: }
7082:
7083: sub rndseed_CODE_64bit {
7084: my ($symb,$courseid,$domain,$username)=@_;
7085: {
7086: use integer;
7087: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7088: my $symbseed=numval2($symb);
7089: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7090: my $CODEseed=numval(&getCODE());
7091: my $courseseed=unpack("%32S*",$courseid.' ');
7092: my $num1=$symbseed+$CODEchck;
7093: my $num2=$CODEseed+$courseseed+$symbchck;
7094: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7095: #&logthis("rndseed :$num1:$num2:$symb");
7096: if ($_64bit) { $num1=(($num1<<32)>>32); }
7097: if ($_64bit) { $num2=(($num2<<32)>>32); }
7098: return "$num1:$num2";
7099: }
7100: }
7101:
7102: sub rndseed_CODE_64bit4 {
7103: my ($symb,$courseid,$domain,$username)=@_;
7104: {
7105: use integer;
7106: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7107: my $symbseed=numval3($symb);
7108: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7109: my $CODEseed=numval3(&getCODE());
7110: my $courseseed=unpack("%32S*",$courseid.' ');
7111: my $num1=$symbseed+$CODEchck;
7112: my $num2=$CODEseed+$courseseed+$symbchck;
7113: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7114: #&logthis("rndseed :$num1:$num2:$symb");
7115: if ($_64bit) { $num1=(($num1<<32)>>32); }
7116: if ($_64bit) { $num2=(($num2<<32)>>32); }
7117: return "$num1:$num2";
7118: }
7119: }
7120:
7121: sub rndseed_CODE_64bit5 {
7122: my ($symb,$courseid,$domain,$username)=@_;
7123: my $code = &getCODE();
7124: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7125: return "$num1:$num2";
7126: }
7127:
7128: sub setup_random_from_rndseed {
7129: my ($rndseed)=@_;
7130: if ($rndseed =~/([,:])/) {
7131: my ($num1,$num2)=split(/[,:]/,$rndseed);
7132: &Math::Random::random_set_seed(abs($num1),abs($num2));
7133: } else {
7134: &Math::Random::random_set_seed_from_phrase($rndseed);
7135: }
7136: }
7137:
7138: sub latest_receipt_algorithm_id {
7139: return 'receipt3';
7140: }
7141:
7142: sub recunique {
7143: my $fucourseid=shift;
7144: my $unique;
7145: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7146: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7147: $unique=$env{"course.$fucourseid.internal.encseed"};
7148: } else {
7149: $unique=$perlvar{'lonReceipt'};
7150: }
7151: return unpack("%32C*",$unique);
7152: }
7153:
7154: sub recprefix {
7155: my $fucourseid=shift;
7156: my $prefix;
7157: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7158: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7159: $prefix=$env{"course.$fucourseid.internal.encpref"};
7160: } else {
7161: $prefix=$perlvar{'lonHostID'};
7162: }
7163: return unpack("%32C*",$prefix);
7164: }
7165:
7166: sub ireceipt {
7167: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
7168:
7169: my $return =&recprefix($fucourseid).'-';
7170:
7171: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7172: $env{'request.state'} eq 'construct') {
7173: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7174: return $return;
7175: }
7176:
7177: my $cuname=unpack("%32C*",$funame);
7178: my $cudom=unpack("%32C*",$fudom);
7179: my $cucourseid=unpack("%32C*",$fucourseid);
7180: my $cusymb=unpack("%32C*",$fusymb);
7181: my $cunique=&recunique($fucourseid);
7182: my $cpart=unpack("%32S*",$part);
7183: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7184:
7185: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
7186:
7187: $return.= ($cunique%$cuname+
7188: $cunique%$cudom+
7189: $cusymb%$cuname+
7190: $cusymb%$cudom+
7191: $cucourseid%$cuname+
7192: $cucourseid%$cudom+
7193: $cpart%$cuname+
7194: $cpart%$cudom);
7195: } else {
7196: $return.= ($cunique%$cuname+
7197: $cunique%$cudom+
7198: $cusymb%$cuname+
7199: $cusymb%$cudom+
7200: $cucourseid%$cuname+
7201: $cucourseid%$cudom);
7202: }
7203: return $return;
7204: }
7205:
7206: sub receipt {
7207: my ($part)=@_;
7208: my ($symb,$courseid,$domain,$name) = &whichuser();
7209: return &ireceipt($name,$domain,$courseid,$symb,$part);
7210: }
7211:
7212: sub whichuser {
7213: my ($passedsymb)=@_;
7214: my ($symb,$courseid,$domain,$name,$publicuser);
7215: if (defined($env{'form.grade_symb'})) {
7216: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7217: my $allowed=&allowed('vgr',$tmp_courseid);
7218: if (!$allowed &&
7219: exists($env{'request.course.sec'}) &&
7220: $env{'request.course.sec'} !~ /^\s*$/) {
7221: $allowed=&allowed('vgr',$tmp_courseid.
7222: '/'.$env{'request.course.sec'});
7223: }
7224: if ($allowed) {
7225: ($symb)=&get_env_multiple('form.grade_symb');
7226: $courseid=$tmp_courseid;
7227: ($domain)=&get_env_multiple('form.grade_domain');
7228: ($name)=&get_env_multiple('form.grade_username');
7229: return ($symb,$courseid,$domain,$name,$publicuser);
7230: }
7231: }
7232: if (!$passedsymb) {
7233: $symb=&symbread();
7234: } else {
7235: $symb=$passedsymb;
7236: }
7237: $courseid=$env{'request.course.id'};
7238: $domain=$env{'user.domain'};
7239: $name=$env{'user.name'};
7240: if ($name eq 'public' && $domain eq 'public') {
7241: if (!defined($env{'form.username'})) {
7242: $env{'form.username'}.=time.rand(10000000);
7243: }
7244: $name.=$env{'form.username'};
7245: }
7246: return ($symb,$courseid,$domain,$name,$publicuser);
7247:
7248: }
7249:
7250: # ------------------------------------------------------------ Serves up a file
7251: # returns either the contents of the file or
7252: # -1 if the file doesn't exist
7253: #
7254: # if the target is a file that was uploaded via DOCS,
7255: # a check will be made to see if a current copy exists on the local server,
7256: # if it does this will be served, otherwise a copy will be retrieved from
7257: # the home server for the course and stored in /home/httpd/html/userfiles on
7258: # the local server.
7259:
7260: sub getfile {
7261: my ($file) = @_;
7262: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7263: &repcopy($file);
7264: return &readfile($file);
7265: }
7266:
7267: sub repcopy_userfile {
7268: my ($file)=@_;
7269: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7270: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
7271: my ($cdom,$cnum,$filename) =
7272: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
7273: my $uri="/uploaded/$cdom/$cnum/$filename";
7274: if (-e "$file") {
7275: # we already have a local copy, check it out
7276: my @fileinfo = stat($file);
7277: my $rtncode;
7278: my $info;
7279: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
7280: if ($lwpresp ne 'ok') {
7281: # there is no such file anymore, even though we had a local copy
7282: if ($rtncode eq '404') {
7283: unlink($file);
7284: }
7285: return -1;
7286: }
7287: if ($info < $fileinfo[9]) {
7288: # nice, the file we have is up-to-date, just say okay
7289: return 'ok';
7290: } else {
7291: # the file is outdated, get rid of it
7292: unlink($file);
7293: }
7294: }
7295: # one way or the other, at this point, we don't have the file
7296: # construct the correct path for the file
7297: my @parts = ($cdom,$cnum);
7298: if ($filename =~ m|^(.+)/[^/]+$|) {
7299: push @parts, split(/\//,$1);
7300: }
7301: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7302: foreach my $part (@parts) {
7303: $path .= '/'.$part;
7304: if (!-e $path) {
7305: mkdir($path,0770);
7306: }
7307: }
7308: # now the path exists for sure
7309: # get a user agent
7310: my $ua=new LWP::UserAgent;
7311: my $transferfile=$file.'.in.transfer';
7312: # FIXME: this should flock
7313: if (-e $transferfile) { return 'ok'; }
7314: my $request;
7315: $uri=~s/^\///;
7316: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
7317: my $response=$ua->request($request,$transferfile);
7318: # did it work?
7319: if ($response->is_error()) {
7320: unlink($transferfile);
7321: &logthis("Userfile repcopy failed for $uri");
7322: return -1;
7323: }
7324: # worked, rename the transfer file
7325: rename($transferfile,$file);
7326: return 'ok';
7327: }
7328:
7329: sub tokenwrapper {
7330: my $uri=shift;
7331: $uri=~s|^http\://([^/]+)||;
7332: $uri=~s|^/||;
7333: $env{'user.environment'}=~/\/([^\/]+)\.id/;
7334: my $token=$1;
7335: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7336: if ($udom && $uname && $file) {
7337: $file=~s|(\?\.*)*$||;
7338: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
7339: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
7340: (($uri=~/\?/)?'&':'?').'token='.$token.
7341: '&tokenissued='.$perlvar{'lonHostID'};
7342: } else {
7343: return '/adm/notfound.html';
7344: }
7345: }
7346:
7347: # call with reqtype HEAD: get last modification time
7348: # call with reqtype GET: get the file contents
7349: # Do not call this with reqtype GET for large files! It loads everything into memory
7350: #
7351: sub getuploaded {
7352: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7353: $uri=~s/^\///;
7354: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
7355: my $ua=new LWP::UserAgent;
7356: my $request=new HTTP::Request($reqtype,$uri);
7357: my $response=$ua->request($request);
7358: $$rtncode = $response->code;
7359: if (! $response->is_success()) {
7360: return 'failed';
7361: }
7362: if ($reqtype eq 'HEAD') {
7363: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
7364: } elsif ($reqtype eq 'GET') {
7365: $$info = $response->content;
7366: }
7367: return 'ok';
7368: }
7369:
7370: sub readfile {
7371: my $file = shift;
7372: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7373: my $fh;
7374: open($fh,"<$file");
7375: my $a='';
7376: while (my $line = <$fh>) { $a .= $line; }
7377: return $a;
7378: }
7379:
7380: sub filelocation {
7381: my ($dir,$file) = @_;
7382: my $location;
7383: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
7384:
7385: if ($file =~ m-^/adm/-) {
7386: $file=~s-^/adm/wrapper/-/-;
7387: $file=~s-^/adm/coursedocs/showdoc/-/-;
7388: }
7389: if ($file=~m:^/~:) { # is a contruction space reference
7390: $location = $file;
7391: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
7392: } elsif ($file=~m{^/home/$match_username/public_html/}) {
7393: # is a correct contruction space reference
7394: $location = $file;
7395: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
7396: my ($udom,$uname,$filename)=
7397: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
7398: my $home=&homeserver($uname,$udom);
7399: my $is_me=0;
7400: my @ids=¤t_machine_ids();
7401: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7402: if ($is_me) {
7403: $location=&propath($udom,$uname).
7404: '/userfiles/'.$filename;
7405: } else {
7406: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7407: $udom.'/'.$uname.'/'.$filename;
7408: }
7409: } else {
7410: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7411: $file=~s:^/res/:/:;
7412: if ( !( $file =~ m:^/:) ) {
7413: $location = $dir. '/'.$file;
7414: } else {
7415: $location = '/home/httpd/html/res'.$file;
7416: }
7417: }
7418: $location=~s://+:/:g; # remove duplicate /
7419: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7420: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7421: return $location;
7422: }
7423:
7424: sub hreflocation {
7425: my ($dir,$file)=@_;
7426: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
7427: $file=filelocation($dir,$file);
7428: } elsif ($file=~m-^/adm/-) {
7429: $file=~s-^/adm/wrapper/-/-;
7430: $file=~s-^/adm/coursedocs/showdoc/-/-;
7431: }
7432: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7433: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7434: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7435: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
7436: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7437: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
7438: -/uploaded/$1/$2/-x;
7439: }
7440: return $file;
7441: }
7442:
7443: sub current_machine_domains {
7444: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7445: }
7446:
7447: sub machine_domains {
7448: my ($hostname) = @_;
7449: my @domains;
7450: my %hostname = &all_hostnames();
7451: while( my($id, $name) = each(%hostname)) {
7452: # &logthis("-$id-$name-$hostname-");
7453: if ($hostname eq $name) {
7454: push(@domains,&host_domain($id));
7455: }
7456: }
7457: return @domains;
7458: }
7459:
7460: sub current_machine_ids {
7461: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7462: }
7463:
7464: sub machine_ids {
7465: my ($hostname) = @_;
7466: $hostname ||= &hostname($perlvar{'lonHostID'});
7467: my @ids;
7468: my %hostname = &all_hostnames();
7469: while( my($id, $name) = each(%hostname)) {
7470: # &logthis("-$id-$name-$hostname-");
7471: if ($hostname eq $name) {
7472: push(@ids,$id);
7473: }
7474: }
7475: return @ids;
7476: }
7477:
7478: sub additional_machine_domains {
7479: my @domains;
7480: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7481: while( my $line = <$fh>) {
7482: $line =~ s/\s//g;
7483: push(@domains,$line);
7484: }
7485: return @domains;
7486: }
7487:
7488: sub default_login_domain {
7489: my $domain = $perlvar{'lonDefDomain'};
7490: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7491: foreach my $posdom (¤t_machine_domains(),
7492: &additional_machine_domains()) {
7493: if (lc($posdom) eq lc($testdomain)) {
7494: $domain=$posdom;
7495: last;
7496: }
7497: }
7498: return $domain;
7499: }
7500:
7501: # ------------------------------------------------------------- Declutters URLs
7502:
7503: sub declutter {
7504: my $thisfn=shift;
7505: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7506: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7507: $thisfn=~s/^\///;
7508: $thisfn=~s|^adm/wrapper/||;
7509: $thisfn=~s|^adm/coursedocs/showdoc/||;
7510: $thisfn=~s/^res\///;
7511: $thisfn=~s/\?.+$//;
7512: return $thisfn;
7513: }
7514:
7515: # ------------------------------------------------------------- Clutter up URLs
7516:
7517: sub clutter {
7518: my $thisfn='/'.&declutter(shift);
7519: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
7520: $thisfn='/res'.$thisfn;
7521: }
7522: if ($thisfn !~m|/adm|) {
7523: if ($thisfn =~ m|/ext/|) {
7524: $thisfn='/adm/wrapper'.$thisfn;
7525: } else {
7526: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7527: my $embstyle=&Apache::loncommon::fileembstyle($ext);
7528: if ($embstyle eq 'ssi'
7529: || ($embstyle eq 'hdn')
7530: || ($embstyle eq 'rat')
7531: || ($embstyle eq 'prv')
7532: || ($embstyle eq 'ign')) {
7533: #do nothing with these
7534: } elsif (($embstyle eq 'img')
7535: || ($embstyle eq 'emb')
7536: || ($embstyle eq 'wrp')) {
7537: $thisfn='/adm/wrapper'.$thisfn;
7538: } elsif ($embstyle eq 'unk'
7539: && $thisfn!~/\.(sequence|page)$/) {
7540: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
7541: } else {
7542: # &logthis("Got a blank emb style");
7543: }
7544: }
7545: }
7546: return $thisfn;
7547: }
7548:
7549: sub clutter_with_no_wrapper {
7550: my $uri = &clutter(shift);
7551: if ($uri =~ m-^/adm/-) {
7552: $uri =~ s-^/adm/wrapper/-/-;
7553: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7554: }
7555: return $uri;
7556: }
7557:
7558: sub freeze_escape {
7559: my ($value)=@_;
7560: if (ref($value)) {
7561: $value=&nfreeze($value);
7562: return '__FROZEN__'.&escape($value);
7563: }
7564: return &escape($value);
7565: }
7566:
7567:
7568: sub thaw_unescape {
7569: my ($value)=@_;
7570: if ($value =~ /^__FROZEN__/) {
7571: substr($value,0,10,undef);
7572: $value=&unescape($value);
7573: return &thaw($value);
7574: }
7575: return &unescape($value);
7576: }
7577:
7578: sub correct_line_ends {
7579: my ($result)=@_;
7580: $$result =~s/\r\n/\n/mg;
7581: $$result =~s/\r/\n/mg;
7582: }
7583: # ================================================================ Main Program
7584:
7585: sub goodbye {
7586: &logthis("Starting Shut down");
7587: #not converted to using infrastruture and probably shouldn't be
7588: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
7589: #converted
7590: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7591: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7592: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7593: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
7594: #1.1 only
7595: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7596: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7597: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7598: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7599: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7600: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7601: &logthis(sprintf("%-20s is %s",'hits',$hits));
7602: &flushcourselogs();
7603: &logthis("Shutting down");
7604: }
7605:
7606: BEGIN {
7607:
7608: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7609: unless ($readit) {
7610: {
7611: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7612: %perlvar = (%perlvar,%{$configvars});
7613: }
7614:
7615: sub get_dns {
7616: my ($url,$func) = @_;
7617: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7618: foreach my $dns (<$config>) {
7619: next if ($dns !~ /^\^(\S*)/x);
7620: $dns = $1;
7621: my $ua=new LWP::UserAgent;
7622: my $request=new HTTP::Request('GET',"http://$dns$url");
7623: my $response=$ua->request($request);
7624: next if ($response->is_error());
7625: my @content = split("\n",$response->content);
7626: &$func(\@content);
7627: }
7628: close($config);
7629: }
7630: # ------------------------------------------------------------ Read domain file
7631: {
7632: my $loaded;
7633: my %domain;
7634:
7635: sub parse_domain_tab {
7636: my ($lines) = @_;
7637: foreach my $line (@$lines) {
7638: next if ($line =~ /^(\#|\s*$ )/x);
7639:
7640: chomp($line);
7641: my ($name,@elements) = split(/:/,$line,9);
7642: my %this_domain;
7643: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7644: 'lang_def', 'city', 'longi', 'lati',
7645: 'primary') {
7646: $this_domain{$field} = shift(@elements);
7647: }
7648: $domain{$name} = \%this_domain;
7649: &logthis("Domain.tab: $name ".$domain{$name}{'description'} );
7650: }
7651: }
7652:
7653: sub load_domain_tab {
7654: &get_dns('/adm/dns/domain',\&parse_domain_tab);
7655: my $fh;
7656: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7657: my @lines = <$fh>;
7658: &parse_domain_tab(\@lines);
7659: }
7660: close($fh);
7661: $loaded = 1;
7662: }
7663:
7664: sub domain {
7665: &load_domain_tab() if (!$loaded);
7666:
7667: my ($name,$what) = @_;
7668: return if ( !exists($domain{$name}) );
7669:
7670: if (!$what) {
7671: return $domain{$name}{'description'};
7672: }
7673: return $domain{$name}{$what};
7674: }
7675: }
7676:
7677:
7678: # ------------------------------------------------------------- Read hosts file
7679: {
7680: my %hostname;
7681: my %hostdom;
7682: my %libserv;
7683: my $loaded;
7684:
7685: sub parse_hosts_tab {
7686: my ($file) = @_;
7687: foreach my $configline (@$file) {
7688: next if ($configline =~ /^(\#|\s*$ )/x);
7689: next if ($configline =~ /^\^/);
7690: chomp($configline);
7691: my ($id,$domain,$role,$name)=split(/:/,$configline);
7692: $name=~s/\s//g;
7693: if ($id && $domain && $role && $name) {
7694: $hostname{$id}=$name;
7695: $hostdom{$id}=$domain;
7696: if ($role eq 'library') { $libserv{$id}=$name; }
7697: }
7698: &logthis("Hosts.tab: $name ".$id );
7699: }
7700: }
7701:
7702: sub load_hosts_tab {
7703: &get_dns('/adm/dns/hosts',\&parse_hosts_tab);
7704: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7705: my @config = <$config>;
7706: &parse_hosts_tab(\@config);
7707: close($config);
7708: $loaded=1;
7709: }
7710:
7711: # FIXME: dev server don't want this, production servers _do_ want this
7712: #&get_iphost();
7713:
7714: sub hostname {
7715: &load_hosts_tab() if (!$loaded);
7716:
7717: my ($lonid) = @_;
7718: return $hostname{$lonid};
7719: }
7720:
7721: sub all_hostnames {
7722: &load_hosts_tab() if (!$loaded);
7723:
7724: return %hostname;
7725: }
7726:
7727: sub is_library {
7728: &load_hosts_tab() if (!$loaded);
7729:
7730: return exists($libserv{$_[0]});
7731: }
7732:
7733: sub all_library {
7734: &load_hosts_tab() if (!$loaded);
7735:
7736: return %libserv;
7737: }
7738:
7739: sub get_servers {
7740: &load_hosts_tab() if (!$loaded);
7741:
7742: my ($domain,$type) = @_;
7743: my %possible_hosts = ($type eq 'library') ? %libserv
7744: : %hostname;
7745: my %result;
7746: if (ref($domain) eq 'ARRAY') {
7747: while ( my ($host,$hostname) = each(%possible_hosts)) {
7748: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
7749: $result{$host} = $hostname;
7750: }
7751: }
7752: } else {
7753: while ( my ($host,$hostname) = each(%possible_hosts)) {
7754: if ($hostdom{$host} eq $domain) {
7755: $result{$host} = $hostname;
7756: }
7757: }
7758: }
7759: return %result;
7760: }
7761:
7762: sub host_domain {
7763: &load_hosts_tab() if (!$loaded);
7764:
7765: my ($lonid) = @_;
7766: return $hostdom{$lonid};
7767: }
7768:
7769: sub all_domains {
7770: &load_hosts_tab() if (!$loaded);
7771:
7772: my %seen;
7773: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7774: return @uniq;
7775: }
7776: }
7777:
7778: {
7779: my %iphost;
7780: my %name_to_ip;
7781: my %lonid_to_ip;
7782: sub get_hosts_from_ip {
7783: my ($ip) = @_;
7784: my %iphosts = &get_iphost();
7785: if (ref($iphosts{$ip})) {
7786: return @{$iphosts{$ip}};
7787: }
7788: return;
7789: }
7790:
7791: sub get_host_ip {
7792: my ($lonid) = @_;
7793: if (exists($lonid_to_ip{$lonid})) {
7794: return $lonid_to_ip{$lonid};
7795: }
7796: my $name=&hostname($lonid);
7797: my $ip = gethostbyname($name);
7798: return if (!$ip || length($ip) ne 4);
7799: $ip=inet_ntoa($ip);
7800: $name_to_ip{$name} = $ip;
7801: $lonid_to_ip{$lonid} = $ip;
7802: return $ip;
7803: }
7804:
7805: sub get_iphost {
7806: if (%iphost) { return %iphost; }
7807: my %hostname = &all_hostnames();
7808: foreach my $id (keys(%hostname)) {
7809: my $name=$hostname{$id};
7810: my $ip;
7811: if (!exists($name_to_ip{$name})) {
7812: $ip = gethostbyname($name);
7813: if (!$ip || length($ip) ne 4) {
7814: &logthis("Skipping host $id name $name no IP found");
7815: next;
7816: }
7817: $ip=inet_ntoa($ip);
7818: $name_to_ip{$name} = $ip;
7819: } else {
7820: $ip = $name_to_ip{$name};
7821: }
7822: $lonid_to_ip{$id} = $ip;
7823: push(@{$iphost{$ip}},$id);
7824: }
7825: return %iphost;
7826: }
7827: }
7828:
7829: # ------------------------------------------------------ Read spare server file
7830: {
7831: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7832:
7833: while (my $configline=<$config>) {
7834: chomp($configline);
7835: if ($configline) {
7836: my ($host,$type) = split(':',$configline,2);
7837: if (!defined($type) || $type eq '') { $type = 'default' };
7838: push(@{ $spareid{$type} }, $host);
7839: }
7840: }
7841: close($config);
7842: }
7843: # ------------------------------------------------------------ Read permissions
7844: {
7845: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7846:
7847: while (my $configline=<$config>) {
7848: chomp($configline);
7849: if ($configline) {
7850: my ($role,$perm)=split(/ /,$configline);
7851: if ($perm ne '') { $pr{$role}=$perm; }
7852: }
7853: }
7854: close($config);
7855: }
7856:
7857: # -------------------------------------------- Read plain texts for permissions
7858: {
7859: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7860:
7861: while (my $configline=<$config>) {
7862: chomp($configline);
7863: if ($configline) {
7864: my ($short,@plain)=split(/:/,$configline);
7865: %{$prp{$short}} = ();
7866: if (@plain > 0) {
7867: $prp{$short}{'std'} = $plain[0];
7868: for (my $i=1; $i<@plain; $i++) {
7869: $prp{$short}{'alt'.$i} = $plain[$i];
7870: }
7871: }
7872: }
7873: }
7874: close($config);
7875: }
7876:
7877: # ---------------------------------------------------------- Read package table
7878: {
7879: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7880:
7881: while (my $configline=<$config>) {
7882: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
7883: chomp($configline);
7884: my ($short,$plain)=split(/:/,$configline);
7885: my ($pack,$name)=split(/\&/,$short);
7886: if ($plain ne '') {
7887: $packagetab{$pack.'&'.$name.'&name'}=$name;
7888: $packagetab{$short}=$plain;
7889: }
7890: }
7891: close($config);
7892: }
7893:
7894: # ------------- set up temporary directory
7895: {
7896: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7897:
7898: }
7899:
7900: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7901: 'compress_threshold'=> 20_000,
7902: });
7903:
7904: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7905: $dumpcount=0;
7906:
7907: &logtouch();
7908: &logthis('<font color="yellow">INFO: Read configuration</font>');
7909: $readit=1;
7910: {
7911: use integer;
7912: my $test=(2**32)+1;
7913: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
7914: &logthis(" Detected 64bit platform ($_64bit)");
7915: }
7916: }
7917: }
7918:
7919: 1;
7920: __END__
7921:
7922: =pod
7923:
7924: =head1 NAME
7925:
7926: Apache::lonnet - Subroutines to ask questions about things in the network.
7927:
7928: =head1 SYNOPSIS
7929:
7930: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
7931:
7932: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7933:
7934: Common parameters:
7935:
7936: =over 4
7937:
7938: =item *
7939:
7940: $uname : an internal username (if $cname expecting a course Id specifically)
7941:
7942: =item *
7943:
7944: $udom : a domain (if $cdom expecting a course's domain specifically)
7945:
7946: =item *
7947:
7948: $symb : a resource instance identifier
7949:
7950: =item *
7951:
7952: $namespace : the name of a .db file that contains the data needed or
7953: being set.
7954:
7955: =back
7956:
7957: =head1 OVERVIEW
7958:
7959: lonnet provides subroutines which interact with the
7960: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7961: about classes, users, and resources.
7962:
7963: For many of these objects you can also use this to store data about
7964: them or modify them in various ways.
7965:
7966: =head2 Symbs
7967:
7968: To identify a specific instance of a resource, LON-CAPA uses symbols
7969: or "symbs"X<symb>. These identifiers are built from the URL of the
7970: map, the resource number of the resource in the map, and the URL of
7971: the resource itself. The latter is somewhat redundant, but might help
7972: if maps change.
7973:
7974: An example is
7975:
7976: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7977:
7978: The respective map entry is
7979:
7980: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7981: title="Problem 2">
7982: </resource>
7983:
7984: Symbs are used by the random number generator, as well as to store and
7985: restore data specific to a certain instance of for example a problem.
7986:
7987: =head2 Storing And Retrieving Data
7988:
7989: X<store()>X<cstore()>X<restore()>Three of the most important functions
7990: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7991: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7992: is is the non-critical message twin of cstore. These functions are for
7993: handlers to store a perl hash to a user's permanent data space in an
7994: easy manner, and to retrieve it again on another call. It is expected
7995: that a handler would use this once at the beginning to retrieve data,
7996: and then again once at the end to send only the new data back.
7997:
7998: The data is stored in the user's data directory on the user's
7999: homeserver under the ID of the course.
8000:
8001: The hash that is returned by restore will have all of the previous
8002: value for all of the elements of the hash.
8003:
8004: Example:
8005:
8006: #creating a hash
8007: my %hash;
8008: $hash{'foo'}='bar';
8009:
8010: #storing it
8011: &Apache::lonnet::cstore(\%hash);
8012:
8013: #changing a value
8014: $hash{'foo'}='notbar';
8015:
8016: #adding a new value
8017: $hash{'bar'}='foo';
8018: &Apache::lonnet::cstore(\%hash);
8019:
8020: #retrieving the hash
8021: my %history=&Apache::lonnet::restore();
8022:
8023: #print the hash
8024: foreach my $key (sort(keys(%history))) {
8025: print("\%history{$key} = $history{$key}");
8026: }
8027:
8028: Will print out:
8029:
8030: %history{1:foo} = bar
8031: %history{1:keys} = foo:timestamp
8032: %history{1:timestamp} = 990455579
8033: %history{2:bar} = foo
8034: %history{2:foo} = notbar
8035: %history{2:keys} = foo:bar:timestamp
8036: %history{2:timestamp} = 990455580
8037: %history{bar} = foo
8038: %history{foo} = notbar
8039: %history{timestamp} = 990455580
8040: %history{version} = 2
8041:
8042: Note that the special hash entries C<keys>, C<version> and
8043: C<timestamp> were added to the hash. C<version> will be equal to the
8044: total number of versions of the data that have been stored. The
8045: C<timestamp> attribute will be the UNIX time the hash was
8046: stored. C<keys> is available in every historical section to list which
8047: keys were added or changed at a specific historical revision of a
8048: hash.
8049:
8050: B<Warning>: do not store the hash that restore returns directly. This
8051: will cause a mess since it will restore the historical keys as if the
8052: were new keys. I.E. 1:foo will become 1:1:foo etc.
8053:
8054: Calling convention:
8055:
8056: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8057: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
8058:
8059: For more detailed information, see lonnet specific documentation.
8060:
8061: =head1 RETURN MESSAGES
8062:
8063: =over 4
8064:
8065: =item * B<con_lost>: unable to contact remote host
8066:
8067: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8068: when the connection is brought back up
8069:
8070: =item * B<con_failed>: unable to contact remote host and unable to save message
8071: for later delivery
8072:
8073: =item * B<error:>: an error a occured, a description of the error follows the :
8074:
8075: =item * B<no_such_host>: unable to fund a host associated with the user/domain
8076: that was requested
8077:
8078: =back
8079:
8080: =head1 PUBLIC SUBROUTINES
8081:
8082: =head2 Session Environment Functions
8083:
8084: =over 4
8085:
8086: =item *
8087: X<appenv()>
8088: B<appenv(%hash)>: the value of %hash is written to
8089: the user envirnoment file, and will be restored for each access this
8090: user makes during this session, also modifies the %env for the current
8091: process
8092:
8093: =item *
8094: X<delenv()>
8095: B<delenv($regexp)>: removes all items from the session
8096: environment file that matches the regular expression in $regexp. The
8097: values are also delted from the current processes %env.
8098:
8099: =item * get_env_multiple($name)
8100:
8101: gets $name from the %env hash, it seemlessly handles the cases where multiple
8102: values may be defined and end up as an array ref.
8103:
8104: returns an array of values
8105:
8106: =back
8107:
8108: =head2 User Information
8109:
8110: =over 4
8111:
8112: =item *
8113: X<queryauthenticate()>
8114: B<queryauthenticate($uname,$udom)>: try to determine user's current
8115: authentication scheme
8116:
8117: =item *
8118: X<authenticate()>
8119: B<authenticate($uname,$upass,$udom)>: try to
8120: authenticate user from domain's lib servers (first use the current
8121: one). C<$upass> should be the users password.
8122:
8123: =item *
8124: X<homeserver()>
8125: B<homeserver($uname,$udom)>: find the server which has
8126: the user's directory and files (there must be only one), this caches
8127: the answer, and also caches if there is a borken connection.
8128:
8129: =item *
8130: X<idget()>
8131: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8132: (IDs are a unique resource in a domain, there must be only 1 ID per
8133: username, and only 1 username per ID in a specific domain) (returns
8134: hash: id=>name,id=>name)
8135:
8136: =item *
8137: X<idrget()>
8138: B<idrget($udom,@unames)>: find the IDs behind a list of
8139: usernames (returns hash: name=>id,name=>id)
8140:
8141: =item *
8142: X<idput()>
8143: B<idput($udom,%ids)>: store away a list of names and associated IDs
8144:
8145: =item *
8146: X<rolesinit()>
8147: B<rolesinit($udom,$username,$authhost)>: get user privileges
8148:
8149: =item *
8150: X<getsection()>
8151: B<getsection($udom,$uname,$cname)>: finds the section of student in the
8152: course $cname, return section name/number or '' for "not in course"
8153: and '-1' for "no section"
8154:
8155: =item *
8156: X<userenvironment()>
8157: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
8158: passed in @what from the requested user's environment, returns a hash
8159:
8160: =item *
8161: X<userlog_query()>
8162: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's activity.log file. %filters defines filters applied when parsing the log file. These can be start or end timestamps, or the type of action - log to look for Login or Logout events, check for Checkin or Checkout, role for role selection. The response is in the form timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are escaped strings of the action recorded in the activity.log file.
8163:
8164: =back
8165:
8166: =head2 User Roles
8167:
8168: =over 4
8169:
8170: =item *
8171:
8172: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
8173: F: full access
8174: U,I,K: authentication modes (cxx only)
8175: '': forbidden
8176: 1: user needs to choose course
8177: 2: browse allowed
8178: A: passphrase authentication needed
8179:
8180: =item *
8181:
8182: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8183: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8184: and course level
8185:
8186: =item *
8187:
8188: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8189: explanation of a user role term
8190:
8191: =item *
8192:
8193: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8194: All arguments are optional. Returns a hash of a roles, either for
8195: co-author/assistant author roles for a user's Construction Space
8196: (default), or if $context is 'user', roles for the user himself,
8197: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8198: and value is set to colon-separated start and end times for the role.
8199: If no username and domain are specified, will default to current
8200: user/domain. Types, roles, and roledoms are references to arrays,
8201: of role statuses (active, future or previous), roles
8202: (e.g., cc,in, st etc.) and domains of the roles which can be used
8203: to restrict the list of roles reported. If no array ref is
8204: provided for types, will default to return only active roles.
8205:
8206: =back
8207:
8208: =head2 User Modification
8209:
8210: =over 4
8211:
8212: =item *
8213:
8214: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8215: user for the level given by URL. Optional start and end dates (leave empty
8216: string or zero for "no date")
8217:
8218: =item *
8219:
8220: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8221: change a users, password, possible return values are: ok,
8222: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8223: refused
8224:
8225: =item *
8226:
8227: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
8228:
8229: =item *
8230:
8231: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8232: modify user
8233:
8234: =item *
8235:
8236: modifystudent
8237:
8238: modify a students enrollment and identification information.
8239: The course id is resolved based on the current users environment.
8240: This means the envoking user must be a course coordinator or otherwise
8241: associated with a course.
8242:
8243: This call is essentially a wrapper for lonnet::modifyuser and
8244: lonnet::modify_student_enrollment
8245:
8246: Inputs:
8247:
8248: =over 4
8249:
8250: =item B<$udom> Students loncapa domain
8251:
8252: =item B<$uname> Students loncapa login name
8253:
8254: =item B<$uid> Students id/student number
8255:
8256: =item B<$umode> Students authentication mode
8257:
8258: =item B<$upass> Students password
8259:
8260: =item B<$first> Students first name
8261:
8262: =item B<$middle> Students middle name
8263:
8264: =item B<$last> Students last name
8265:
8266: =item B<$gene> Students generation
8267:
8268: =item B<$usec> Students section in course
8269:
8270: =item B<$end> Unix time of the roles expiration
8271:
8272: =item B<$start> Unix time of the roles start date
8273:
8274: =item B<$forceid> If defined, allow $uid to be changed
8275:
8276: =item B<$desiredhome> server to use as home server for student
8277:
8278: =back
8279:
8280: =item *
8281:
8282: modify_student_enrollment
8283:
8284: Change a students enrollment status in a class. The environment variable
8285: 'role.request.course' must be defined for this function to proceed.
8286:
8287: Inputs:
8288:
8289: =over 4
8290:
8291: =item $udom, students domain
8292:
8293: =item $uname, students name
8294:
8295: =item $uid, students user id
8296:
8297: =item $first, students first name
8298:
8299: =item $middle
8300:
8301: =item $last
8302:
8303: =item $gene
8304:
8305: =item $usec
8306:
8307: =item $end
8308:
8309: =item $start
8310:
8311: =back
8312:
8313:
8314: =item *
8315:
8316: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8317: custom role; give a custom role to a user for the level given by URL. Specify
8318: name and domain of role author, and role name
8319:
8320: =item *
8321:
8322: revokerole($udom,$uname,$url,$role) : revoke a role for url
8323:
8324: =item *
8325:
8326: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8327:
8328: =back
8329:
8330: =head2 Course Infomation
8331:
8332: =over 4
8333:
8334: =item *
8335:
8336: coursedescription($courseid) : returns a hash of information about the
8337: specified course id, including all environment settings for the
8338: course, the description of the course will be in the hash under the
8339: key 'description'
8340:
8341: =item *
8342:
8343: resdata($name,$domain,$type,@which) : request for current parameter
8344: setting for a specific $type, where $type is either 'course' or 'user',
8345: @what should be a list of parameters to ask about. This routine caches
8346: answers for 5 minutes.
8347:
8348: =back
8349:
8350: =head2 Course Modification
8351:
8352: =over 4
8353:
8354: =item *
8355:
8356: writecoursepref($courseid,%prefs) : write preferences (environment
8357: database) for a course
8358:
8359: =item *
8360:
8361: createcourse($udom,$description,$url) : make/modify course
8362:
8363: =back
8364:
8365: =head2 Resource Subroutines
8366:
8367: =over 4
8368:
8369: =item *
8370:
8371: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
8372:
8373: =item *
8374:
8375: repcopy($filename) : subscribes to the requested file, and attempts to
8376: replicate from the owning library server, Might return
8377: 'unavailable', 'not_found', 'forbidden', 'ok', or
8378: 'bad_request', also attempts to grab the metadata for the
8379: resource. Expects the local filesystem pathname
8380: (/home/httpd/html/res/....)
8381:
8382: =back
8383:
8384: =head2 Resource Information
8385:
8386: =over 4
8387:
8388: =item *
8389:
8390: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8391: a vairety of different possible values, $varname should be a request
8392: string, and the other parameters can be used to specify who and what
8393: one is asking about.
8394:
8395: Possible values for $varname are environment.lastname (or other item
8396: from the envirnment hash), user.name (or someother aspect about the
8397: user), resource.0.maxtries (or some other part and parameter of a
8398: resource)
8399:
8400: =item *
8401:
8402: directcondval($number) : get current value of a condition; reads from a state
8403: string
8404:
8405: =item *
8406:
8407: condval($condidx) : value of condition index based on state
8408:
8409: =item *
8410:
8411: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8412: resource's metadata, $what should be either a specific key, or either
8413: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8414: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8415:
8416: this function automatically caches all requests
8417:
8418: =item *
8419:
8420: metadata_query($query,$custom,$customshow) : make a metadata query against the
8421: network of library servers; returns file handle of where SQL and regex results
8422: will be stored for query
8423:
8424: =item *
8425:
8426: symbread($filename) : return symbolic list entry (filename argument optional);
8427: returns the data handle
8428:
8429: =item *
8430:
8431: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
8432: a possible symb for the URL in $thisfn, and if is an encryypted
8433: resource that the user accessed using /enc/ returns a 1 on success, 0
8434: on failure, user must be in a course, as it assumes the existance of
8435: the course initial hash, and uses $env('request.course.id'}
8436:
8437:
8438: =item *
8439:
8440: symbclean($symb) : removes versions numbers from a symb, returns the
8441: cleaned symb
8442:
8443: =item *
8444:
8445: is_on_map($uri) : checks if the $uri is somewhere on the current
8446: course map, user must be in a course for it to work.
8447:
8448: =item *
8449:
8450: numval($salt) : return random seed value (addend for rndseed)
8451:
8452: =item *
8453:
8454: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8455: a random seed, all arguments are optional, if they aren't sent it uses the
8456: environment to derive them. Note: if symb isn't sent and it can't get one
8457: from &symbread it will use the current time as its return value
8458:
8459: =item *
8460:
8461: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8462: unfakeable, receipt
8463:
8464: =item *
8465:
8466: receipt() : API to ireceipt working off of env values; given out to users
8467:
8468: =item *
8469:
8470: countacc($url) : count the number of accesses to a given URL
8471:
8472: =item *
8473:
8474: 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
8475:
8476: =item *
8477:
8478: 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)
8479:
8480: =item *
8481:
8482: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
8483:
8484: =item *
8485:
8486: devalidate($symb) : devalidate temporary spreadsheet calculations,
8487: forcing spreadsheet to reevaluate the resource scores next time.
8488:
8489: =back
8490:
8491: =head2 Storing/Retreiving Data
8492:
8493: =over 4
8494:
8495: =item *
8496:
8497: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8498: for this url; hashref needs to be given and should be a \%hashname; the
8499: remaining args aren't required and if they aren't passed or are '' they will
8500: be derived from the env
8501:
8502: =item *
8503:
8504: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8505: uses critical subroutine
8506:
8507: =item *
8508:
8509: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8510: all args are optional
8511:
8512: =item *
8513:
8514: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8515: dumps the complete (or key matching regexp) namespace into a hash
8516: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8517: normally &store()ed into
8518:
8519: $range should be either an integer '100' (give me the first 100
8520: matching records)
8521: or be two integers sperated by a - with no spaces
8522: '30-50' (give me the 30th through the 50th matching
8523: records)
8524:
8525:
8526: =item *
8527:
8528: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8529: replaces a &store() version of data with a replacement set of data
8530: for a particular resource in a namespace passed in the $storehash hash
8531: reference
8532:
8533: =item *
8534:
8535: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8536: works very similar to store/cstore, but all data is stored in a
8537: temporary location and can be reset using tmpreset, $storehash should
8538: be a hash reference, returns nothing on success
8539:
8540: =item *
8541:
8542: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8543: similar to restore, but all data is stored in a temporary location and
8544: can be reset using tmpreset. Returns a hash of values on success,
8545: error string otherwise.
8546:
8547: =item *
8548:
8549: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8550: deltes all keys for $symb form the temporary storage hash.
8551:
8552: =item *
8553:
8554: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8555: reference filled in from namesp ($udom and $uname are optional)
8556:
8557: =item *
8558:
8559: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8560: namesp ($udom and $uname are optional)
8561:
8562: =item *
8563:
8564: dump($namespace,$udom,$uname,$regexp,$range) :
8565: dumps the complete (or key matching regexp) namespace into a hash
8566: ($udom, $uname, $regexp, $range are optional)
8567:
8568: $range should be either an integer '100' (give me the first 100
8569: matching records)
8570: or be two integers sperated by a - with no spaces
8571: '30-50' (give me the 30th through the 50th matching
8572: records)
8573: =item *
8574:
8575: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8576: $store can be a scalar, an array reference, or if the amount to be
8577: incremented is > 1, a hash reference.
8578:
8579: ($udom and $uname are optional)
8580:
8581: =item *
8582:
8583: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8584: ($udom and $uname are optional)
8585:
8586: =item *
8587:
8588: cput($namespace,$storehash,$udom,$uname) : critical put
8589: ($udom and $uname are optional)
8590:
8591: =item *
8592:
8593: newput($namespace,$storehash,$udom,$uname) :
8594:
8595: Attempts to store the items in the $storehash, but only if they don't
8596: currently exist, if this succeeds you can be certain that you have
8597: successfully created a new key value pair in the $namespace db.
8598:
8599:
8600: Args:
8601: $namespace: name of database to store values to
8602: $storehash: hashref to store to the db
8603: $udom: (optional) domain of user containing the db
8604: $uname: (optional) name of user caontaining the db
8605:
8606: Returns:
8607: 'ok' -> succeeded in storing all keys of $storehash
8608: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8609: least <key> already existed in the db (other
8610: requested keys may also already exist)
8611: 'error: <msg>' -> unable to tie the DB or other erorr occured
8612: 'con_lost' -> unable to contact request server
8613: 'refused' -> action was not allowed by remote machine
8614:
8615:
8616: =item *
8617:
8618: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8619: reference filled in from namesp (encrypts the return communication)
8620: ($udom and $uname are optional)
8621:
8622: =item *
8623:
8624: log($udom,$name,$home,$message) : write to permanent log for user; use
8625: critical subroutine
8626:
8627: =item *
8628:
8629: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
8630: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
8631:
8632: =item *
8633:
8634: put_dom($namespace,$storehash,$udomain) : stores hash in namespace at domain level on primary domain server ($udomain is optional)
8635:
8636: =back
8637:
8638: =head2 Network Status Functions
8639:
8640: =over 4
8641:
8642: =item *
8643:
8644: dirlist($uri) : return directory list based on URI
8645:
8646: =item *
8647:
8648: spareserver() : find server with least workload from spare.tab
8649:
8650: =back
8651:
8652: =head2 Apache Request
8653:
8654: =over 4
8655:
8656: =item *
8657:
8658: ssi($url,%hash) : server side include, does a complete request cycle on url to
8659: localhost, posts hash
8660:
8661: =back
8662:
8663: =head2 Data to String to Data
8664:
8665: =over 4
8666:
8667: =item *
8668:
8669: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8670: and '&' separators, supports elements that are arrayrefs and hashrefs
8671:
8672: =item *
8673:
8674: hashref2str($hashref) : convert a hashref into a string complete with
8675: escaping and '=' and '&' separators, supports elements that are
8676: arrayrefs and hashrefs
8677:
8678: =item *
8679:
8680: arrayref2str($arrayref) : convert an arrayref into a string complete
8681: with escaping and '&' separators, supports elements that are arrayrefs
8682: and hashrefs
8683:
8684: =item *
8685:
8686: str2hash($string) : convert string to hash using unescaping and
8687: splitting on '=' and '&', supports elements that are arrayrefs and
8688: hashrefs
8689:
8690: =item *
8691:
8692: str2array($string) : convert string to hash using unescaping and
8693: splitting on '&', supports elements that are arrayrefs and hashrefs
8694:
8695: =back
8696:
8697: =head2 Logging Routines
8698:
8699: =over 4
8700:
8701: These routines allow one to make log messages in the lonnet.log and
8702: lonnet.perm logfiles.
8703:
8704: =item *
8705:
8706: logtouch() : make sure the logfile, lonnet.log, exists
8707:
8708: =item *
8709:
8710: logthis() : append message to the normal lonnet.log file, it gets
8711: preiodically rolled over and deleted.
8712:
8713: =item *
8714:
8715: logperm() : append a permanent message to lonnet.perm.log, this log
8716: file never gets deleted by any automated portion of the system, only
8717: messages of critical importance should go in here.
8718:
8719: =back
8720:
8721: =head2 General File Helper Routines
8722:
8723: =over 4
8724:
8725: =item *
8726:
8727: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8728: (a) files in /uploaded
8729: (i) If a local copy of the file exists -
8730: compares modification date of local copy with last-modified date for
8731: definitive version stored on home server for course. If local copy is
8732: stale, requests a new version from the home server and stores it.
8733: If the original has been removed from the home server, then local copy
8734: is unlinked.
8735: (ii) If local copy does not exist -
8736: requests the file from the home server and stores it.
8737:
8738: If $caller is 'uploadrep':
8739: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8740: for request for files originally uploaded via DOCS.
8741: - returns 'ok' if fresh local copy now available, -1 otherwise.
8742:
8743: Otherwise:
8744: This indicates a call from the content generation phase of the request.
8745: - returns the entire contents of the file or -1.
8746:
8747: (b) files in /res
8748: - returns the entire contents of a file or -1;
8749: it properly subscribes to and replicates the file if neccessary.
8750:
8751:
8752: =item *
8753:
8754: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8755: reference
8756:
8757: returns either a stat() list of data about the file or an empty list
8758: if the file doesn't exist or couldn't find out about it (connection
8759: problems or user unknown)
8760:
8761: =item *
8762:
8763: filelocation($dir,$file) : returns file system location of a file
8764: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8765: directory that relative $file lookups are to looked in ($dir of /a/dir
8766: and a file of ../bob will become /a/bob)
8767:
8768: =item *
8769:
8770: hreflocation($dir,$file) : returns file system location or a URL; same as
8771: filelocation except for hrefs
8772:
8773: =item *
8774:
8775: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8776:
8777: =back
8778:
8779: =head2 Usererfile file routines (/uploaded*)
8780:
8781: =over 4
8782:
8783: =item *
8784:
8785: userfileupload(): main rotine for putting a file in a user or course's
8786: filespace, arguments are,
8787:
8788: formname - required - this is the name of the element in $env where the
8789: filename, and the contents of the file to create/modifed exist
8790: the filename is in $env{'form.'.$formname.'.filename'} and the
8791: contents of the file is located in $env{'form.'.$formname}
8792: coursedoc - if true, store the file in the course of the active role
8793: of the current user
8794: subdir - required - subdirectory to put the file in under ../userfiles/
8795: if undefined, it will be placed in "unknown"
8796:
8797: (This routine calls clean_filename() to remove any dangerous
8798: characters from the filename, and then calls finuserfileupload() to
8799: complete the transaction)
8800:
8801: returns either the url of the uploaded file (/uploaded/....) if successful
8802: and /adm/notfound.html if unsuccessful
8803:
8804: =item *
8805:
8806: clean_filename(): routine for cleaing a filename up for storage in
8807: userfile space, argument is:
8808:
8809: filename - proposed filename
8810:
8811: returns: the new clean filename
8812:
8813: =item *
8814:
8815: finishuserfileupload(): routine that creaes and sends the file to
8816: userspace, probably shouldn't be called directly
8817:
8818: docuname: username or courseid of destination for the file
8819: docudom: domain of user/course of destination for the file
8820: formname: same as for userfileupload()
8821: fname: filename (inculding subdirectories) for the file
8822:
8823: returns either the url of the uploaded file (/uploaded/....) if successful
8824: and /adm/notfound.html if unsuccessful
8825:
8826: =item *
8827:
8828: renameuserfile(): renames an existing userfile to a new name
8829:
8830: Args:
8831: docuname: username or courseid of destination for the file
8832: docudom: domain of user/course of destination for the file
8833: old: current file name (including any subdirs under userfiles)
8834: new: desired file name (including any subdirs under userfiles)
8835:
8836: =item *
8837:
8838: mkdiruserfile(): creates a directory is a userfiles dir
8839:
8840: Args:
8841: docuname: username or courseid of destination for the file
8842: docudom: domain of user/course of destination for the file
8843: dir: dir to create (including any subdirs under userfiles)
8844:
8845: =item *
8846:
8847: removeuserfile(): removes a file that exists in userfiles
8848:
8849: Args:
8850: docuname: username or courseid of destination for the file
8851: docudom: domain of user/course of destination for the file
8852: fname: filname to delete (including any subdirs under userfiles)
8853:
8854: =item *
8855:
8856: removeuploadedurl(): convience function for removeuserfile()
8857:
8858: Args:
8859: url: a full /uploaded/... url to delete
8860:
8861: =item *
8862:
8863: get_portfile_permissions():
8864: Args:
8865: domain: domain of user or course contain the portfolio files
8866: user: name of user or num of course contain the portfolio files
8867: Returns:
8868: hashref of a dump of the proper file_permissions.db
8869:
8870:
8871: =item *
8872:
8873: get_access_controls():
8874:
8875: Args:
8876: current_permissions: the hash ref returned from get_portfile_permissions()
8877: group: (optional) the group you want the files associated with
8878: file: (optional) the file you want access info on
8879:
8880: Returns:
8881: a hash (keys are file names) of hashes containing
8882: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8883: values are XML containing access control settings (see below)
8884:
8885: Internal notes:
8886:
8887: access controls are stored in file_permissions.db as key=value pairs.
8888: key -> path to file/file_name\0uniqueID:scope_end_start
8889: where scope -> public,guest,course,group,domains or users.
8890: end -> UNIX time for end of access (0 -> no end date)
8891: start -> UNIX time for start of access
8892:
8893: value -> XML description of access control
8894: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8895: <start></start>
8896: <end></end>
8897:
8898: <password></password> for scope type = guest
8899:
8900: <domain></domain> for scope type = course or group
8901: <number></number>
8902: <roles id="">
8903: <role></role>
8904: <access></access>
8905: <section></section>
8906: <group></group>
8907: </roles>
8908:
8909: <dom></dom> for scope type = domains
8910:
8911: <users> for scope type = users
8912: <user>
8913: <uname></uname>
8914: <udom></udom>
8915: </user>
8916: </users>
8917: </scope>
8918:
8919: Access data is also aggregated for each file in an additional key=value pair:
8920: key -> path to file/file_name\0accesscontrol
8921: value -> reference to hash
8922: hash contains key = value pairs
8923: where key = uniqueID:scope_end_start
8924: value = UNIX time record was last updated
8925:
8926: Used to improve speed of look-ups of access controls for each file.
8927:
8928: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8929:
8930: modify_access_controls():
8931:
8932: Modifies access controls for a portfolio file
8933: Args
8934: 1. file name
8935: 2. reference to hash of required changes,
8936: 3. domain
8937: 4. username
8938: where domain,username are the domain of the portfolio owner
8939: (either a user or a course)
8940:
8941: Returns:
8942: 1. result of additions or updates ('ok' or 'error', with error message).
8943: 2. result of deletions ('ok' or 'error', with error message).
8944: 3. reference to hash of any new or updated access controls.
8945: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8946: key = integer (inbound ID)
8947: value = uniqueID
8948:
8949: =back
8950:
8951: =head2 HTTP Helper Routines
8952:
8953: =over 4
8954:
8955: =item *
8956:
8957: escape() : unpack non-word characters into CGI-compatible hex codes
8958:
8959: =item *
8960:
8961: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8962:
8963: =back
8964:
8965: =head1 PRIVATE SUBROUTINES
8966:
8967: =head2 Underlying communication routines (Shouldn't call)
8968:
8969: =over 4
8970:
8971: =item *
8972:
8973: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8974:
8975: =item *
8976:
8977: reply() : uses subreply to send a message to remote machine, logs all failures
8978:
8979: =item *
8980:
8981: critical() : passes a critical message to another server; if cannot
8982: get through then place message in connection buffer directory and
8983: returns con_delayed, if incapable of saving message, returns
8984: con_failed
8985:
8986: =item *
8987:
8988: reconlonc() : tries to reconnect lonc client processes.
8989:
8990: =back
8991:
8992: =head2 Resource Access Logging
8993:
8994: =over 4
8995:
8996: =item *
8997:
8998: flushcourselogs() : flush (save) buffer logs and access logs
8999:
9000: =item *
9001:
9002: courselog($what) : save message for course in hash
9003:
9004: =item *
9005:
9006: courseacclog($what) : save message for course using &courselog(). Perform
9007: special processing for specific resource types (problems, exams, quizzes, etc).
9008:
9009: =item *
9010:
9011: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9012: as a PerlChildExitHandler
9013:
9014: =back
9015:
9016: =head2 Other
9017:
9018: =over 4
9019:
9020: =item *
9021:
9022: symblist($mapname,%newhash) : update symbolic storage links
9023:
9024: =back
9025:
9026: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>