File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.814:
download - view:
text,
annotated -
select for diffs
Mon Dec 11 14:06:05 2006 UTC (17 years, 7 months ago) by
raeburn
Branches:
MAIN
CVS tags:
version_2_2_99_1,
version_2_2_99_0,
HEAD
Add response code of 'B' to lonnet::allowed() to indicate access to a file is currently subject to a block, because the file owner is part of a course with active communications blocking, and file viewer does not have 'evb' privilege in the course to nullify the block.
Used to block access to portfolio files. Response of 'B' triggers blockedaccess.pm which displays information about blocking conditions.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.814 2006/12/11 14:06:05 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 %hostname %badServerCache %iphost %spareid %hostdom
39: %libserv %pr %prp $memcache %packagetab
40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
42: %domaindescription %domain_auth_def %domain_auth_arg_def
43: %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
44: $tmpdir $_64bit %env);
45:
46: use IO::Socket;
47: use GDBM_File;
48: use HTML::LCParser;
49: use HTML::Parser;
50: use Fcntl qw(:flock);
51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
52: use Time::HiRes qw( gettimeofday tv_interval );
53: use Cache::Memcached;
54: use Digest::MD5;
55: use Math::Random;
56: use lib '/home/httpd/lib/perl';
57: use LONCAPA qw(:DEFAULT :match);
58: use LONCAPA::Configuration;
59:
60: my $readit;
61: my $max_connection_retries = 10; # Or some such value.
62:
63: require Exporter;
64:
65: our @ISA = qw (Exporter);
66: our @EXPORT = qw(%env);
67:
68: =pod
69:
70: =head1 Package Variables
71:
72: These are largely undocumented, so if you decipher one please note it here.
73:
74: =over 4
75:
76: =item $processmarker
77:
78: Contains the time this process was started and this servers host id.
79:
80: =item $dumpcount
81:
82: Counts the number of times a message log flush has been attempted (regardless
83: of success) by this process. Used as part of the filename when messages are
84: delayed.
85:
86: =back
87:
88: =cut
89:
90:
91: # --------------------------------------------------------------------- Logging
92: {
93: my $logid;
94: sub instructor_log {
95: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
96: $logid++;
97: my $id=time().'00000'.$$.'00000'.$logid;
98: return &Apache::lonnet::put('nohist_'.$hash_name,
99: { $id => {
100: 'exe_uname' => $env{'user.name'},
101: 'exe_udom' => $env{'user.domain'},
102: 'exe_time' => time(),
103: 'exe_ip' => $ENV{'REMOTE_ADDR'},
104: 'delflag' => $delflag,
105: 'logentry' => $storehash,
106: 'uname' => $uname,
107: 'udom' => $udom,
108: }
109: },
110: $env{'course.'.$env{'request.course.id'}.'.domain'},
111: $env{'course.'.$env{'request.course.id'}.'.num'}
112: );
113: }
114: }
115:
116: sub logtouch {
117: my $execdir=$perlvar{'lonDaemons'};
118: unless (-e "$execdir/logs/lonnet.log") {
119: open(my $fh,">>$execdir/logs/lonnet.log");
120: close $fh;
121: }
122: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
123: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
124: }
125:
126: sub logthis {
127: my $message=shift;
128: my $execdir=$perlvar{'lonDaemons'};
129: my $now=time;
130: my $local=localtime($now);
131: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
132: print $fh "$local ($$): $message\n";
133: close($fh);
134: }
135: return 1;
136: }
137:
138: sub logperm {
139: my $message=shift;
140: my $execdir=$perlvar{'lonDaemons'};
141: my $now=time;
142: my $local=localtime($now);
143: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
144: print $fh "$now:$message:$local\n";
145: close($fh);
146: }
147: return 1;
148: }
149:
150: # -------------------------------------------------- Non-critical communication
151: sub subreply {
152: my ($cmd,$server)=@_;
153: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
154: #
155: # With loncnew process trimming, there's a timing hole between lonc server
156: # process exit and the master server picking up the listen on the AF_UNIX
157: # socket. In that time interval, a lock file will exist:
158:
159: my $lockfile=$peerfile.".lock";
160: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
161: sleep(1);
162: }
163: # At this point, either a loncnew parent is listening or an old lonc
164: # or loncnew child is listening so we can connect or everything's dead.
165: #
166: # We'll give the connection a few tries before abandoning it. If
167: # connection is not possible, we'll con_lost back to the client.
168: #
169: my $client;
170: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
171: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
172: Type => SOCK_STREAM,
173: Timeout => 10);
174: if($client) {
175: last; # Connected!
176: }
177: sleep(1); # Try again later if failed connection.
178: }
179: my $answer;
180: if ($client) {
181: print $client "sethost:$server:$cmd\n";
182: $answer=<$client>;
183: if (!$answer) { $answer="con_lost"; }
184: chomp($answer);
185: } else {
186: $answer = 'con_lost'; # Failed connection.
187: }
188: return $answer;
189: }
190:
191: sub reply {
192: my ($cmd,$server)=@_;
193: unless (defined($hostname{$server})) { return 'no_such_host'; }
194: my $answer=subreply($cmd,$server);
195: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
196: &logthis("<font color=\"blue\">WARNING:".
197: " $cmd to $server returned $answer</font>");
198: }
199: return $answer;
200: }
201:
202: # ----------------------------------------------------------- Send USR1 to lonc
203:
204: sub reconlonc {
205: my $peerfile=shift;
206: &logthis("Trying to reconnect for $peerfile");
207: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
208: if (open(my $fh,"<$loncfile")) {
209: my $loncpid=<$fh>;
210: chomp($loncpid);
211: if (kill 0 => $loncpid) {
212: &logthis("lonc at pid $loncpid responding, sending USR1");
213: kill USR1 => $loncpid;
214: sleep 1;
215: if (-e "$peerfile") { return; }
216: &logthis("$peerfile still not there, give it another try");
217: sleep 5;
218: if (-e "$peerfile") { return; }
219: &logthis(
220: "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
221: } else {
222: &logthis(
223: "<font color=\"blue\">WARNING:".
224: " lonc at pid $loncpid not responding, giving up</font>");
225: }
226: } else {
227: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
228: }
229: }
230:
231: # ------------------------------------------------------ Critical communication
232:
233: sub critical {
234: my ($cmd,$server)=@_;
235: unless ($hostname{$server}) {
236: &logthis("<font color=\"blue\">WARNING:".
237: " Critical message to unknown server ($server)</font>");
238: return 'no_such_host';
239: }
240: my $answer=reply($cmd,$server);
241: if ($answer eq 'con_lost') {
242: &reconlonc("$perlvar{'lonSockDir'}/$server");
243: my $answer=reply($cmd,$server);
244: if ($answer eq 'con_lost') {
245: my $now=time;
246: my $middlename=$cmd;
247: $middlename=substr($middlename,0,16);
248: $middlename=~s/\W//g;
249: my $dfilename=
250: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
251: $dumpcount++;
252: {
253: my $dfh;
254: if (open($dfh,">$dfilename")) {
255: print $dfh "$cmd\n";
256: close($dfh);
257: }
258: }
259: sleep 2;
260: my $wcmd='';
261: {
262: my $dfh;
263: if (open($dfh,"<$dfilename")) {
264: $wcmd=<$dfh>;
265: close($dfh);
266: }
267: }
268: chomp($wcmd);
269: if ($wcmd eq $cmd) {
270: &logthis("<font color=\"blue\">WARNING: ".
271: "Connection buffer $dfilename: $cmd</font>");
272: &logperm("D:$server:$cmd");
273: return 'con_delayed';
274: } else {
275: &logthis("<font color=\"red\">CRITICAL:"
276: ." Critical connection failed: $server $cmd</font>");
277: &logperm("F:$server:$cmd");
278: return 'con_failed';
279: }
280: }
281: }
282: return $answer;
283: }
284:
285: # ------------------------------------------- check if return value is an error
286:
287: sub error {
288: my ($result) = @_;
289: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
290: if ($2 == 2) { return undef; }
291: return $1;
292: }
293: return undef;
294: }
295:
296: sub convert_and_load_session_env {
297: my ($lonidsdir,$handle)=@_;
298: my @profile;
299: {
300: open(my $idf,"$lonidsdir/$handle.id");
301: flock($idf,LOCK_SH);
302: @profile=<$idf>;
303: close($idf);
304: }
305: my %temp_env;
306: foreach my $line (@profile) {
307: if ($line !~ m/=/) {
308: return 0;
309: }
310: chomp($line);
311: my ($envname,$envvalue)=split(/=/,$line,2);
312: $temp_env{&unescape($envname)} = &unescape($envvalue);
313: }
314: unlink("$lonidsdir/$handle.id");
315: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
316: 0640)) {
317: %disk_env = %temp_env;
318: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
319: untie(%disk_env);
320: }
321: return 1;
322: }
323:
324: # ------------------------------------------- Transfer profile into environment
325: my $env_loaded;
326: sub transfer_profile_to_env {
327: my ($lonidsdir,$handle,$force_transfer) = @_;
328: if (!$force_transfer && $env_loaded) { return; }
329:
330: if (!defined($lonidsdir)) {
331: $lonidsdir = $perlvar{'lonIDsDir'};
332: }
333: if (!defined($handle)) {
334: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
335: }
336:
337: my $convert;
338: {
339: open(my $idf,"$lonidsdir/$handle.id");
340: flock($idf,LOCK_SH);
341: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
342: &GDBM_READER(),0640)) {
343: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
344: untie(%disk_env);
345: } else {
346: $convert = 1;
347: }
348: }
349: if ($convert) {
350: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
351: &logthis("Failed to load session, or convert session.");
352: }
353: }
354:
355: my %remove;
356: while ( my $envname = each(%env) ) {
357: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
358: if ($time < time-300) {
359: $remove{$key}++;
360: }
361: }
362: }
363:
364: $env{'user.environment'} = "$lonidsdir/$handle.id";
365: $env_loaded=1;
366: foreach my $expired_key (keys(%remove)) {
367: &delenv($expired_key);
368: }
369: }
370:
371: # ---------------------------------------------------------- Append Environment
372:
373: sub appenv {
374: my %newenv=@_;
375: foreach my $key (keys(%newenv)) {
376: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
377: &logthis("<font color=\"blue\">WARNING: ".
378: "Attempt to modify environment ".$key." to ".$newenv{$key}
379: .'</font>');
380: delete($newenv{$key});
381: } else {
382: $env{$key}=$newenv{$key};
383: }
384: }
385: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
386: 0640)) {
387: while (my ($key,$value) = each(%newenv)) {
388: $disk_env{$key} = $value;
389: }
390: untie(%disk_env);
391: }
392: return 'ok';
393: }
394: # ----------------------------------------------------- Delete from Environment
395:
396: sub delenv {
397: my $delthis=shift;
398: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
399: &logthis("<font color=\"blue\">WARNING: ".
400: "Attempt to delete from environment ".$delthis);
401: return 'error';
402: }
403: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
404: 0640)) {
405: foreach my $key (keys(%disk_env)) {
406: if ($key=~/^$delthis/) {
407: delete($env{$key});
408: delete($disk_env{$key});
409: }
410: }
411: untie(%disk_env);
412: }
413: return 'ok';
414: }
415:
416: sub get_env_multiple {
417: my ($name) = @_;
418: my @values;
419: if (defined($env{$name})) {
420: # exists is it an array
421: if (ref($env{$name})) {
422: @values=@{ $env{$name} };
423: } else {
424: $values[0]=$env{$name};
425: }
426: }
427: return(@values);
428: }
429:
430: # ------------------------------------------ Find out current server userload
431: # there is a copy in lond
432: sub userload {
433: my $numusers=0;
434: {
435: opendir(LONIDS,$perlvar{'lonIDsDir'});
436: my $filename;
437: my $curtime=time;
438: while ($filename=readdir(LONIDS)) {
439: if ($filename eq '.' || $filename eq '..') {next;}
440: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
441: if ($curtime-$mtime < 1800) { $numusers++; }
442: }
443: closedir(LONIDS);
444: }
445: my $userloadpercent=0;
446: my $maxuserload=$perlvar{'lonUserLoadLim'};
447: if ($maxuserload) {
448: $userloadpercent=100*$numusers/$maxuserload;
449: }
450: $userloadpercent=sprintf("%.2f",$userloadpercent);
451: return $userloadpercent;
452: }
453:
454: # ------------------------------------------ Fight off request when overloaded
455:
456: sub overloaderror {
457: my ($r,$checkserver)=@_;
458: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
459: my $loadavg;
460: if ($checkserver eq $perlvar{'lonHostID'}) {
461: open(my $loadfile,'/proc/loadavg');
462: $loadavg=<$loadfile>;
463: $loadavg =~ s/\s.*//g;
464: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
465: close($loadfile);
466: } else {
467: $loadavg=&reply('load',$checkserver);
468: }
469: my $overload=$loadavg-100;
470: if ($overload>0) {
471: $r->err_headers_out->{'Retry-After'}=$overload;
472: $r->log_error('Overload of '.$overload.' on '.$checkserver);
473: return 413;
474: }
475: return '';
476: }
477:
478: # ------------------------------ Find server with least workload from spare.tab
479:
480: sub spareserver {
481: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
482: my $spare_server;
483: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
484: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
485: : $userloadpercent;
486:
487: foreach my $try_server (@{ $spareid{'primary'} }) {
488: ($spare_server, $lowest_load) =
489: &compare_server_load($try_server, $spare_server, $lowest_load);
490: }
491:
492: my $found_server = ($spare_server ne '' && $lowest_load < 100);
493:
494: if (!$found_server) {
495: foreach my $try_server (@{ $spareid{'default'} }) {
496: ($spare_server, $lowest_load) =
497: &compare_server_load($try_server, $spare_server, $lowest_load);
498: }
499: }
500:
501: if (!$want_server_name) {
502: $spare_server="http://$hostname{$spare_server}";
503: }
504: return $spare_server;
505: }
506:
507: sub compare_server_load {
508: my ($try_server, $spare_server, $lowest_load) = @_;
509:
510: my $loadans = &reply('load', $try_server);
511: my $userloadans = &reply('userload',$try_server);
512:
513: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
514: next; #didn't get a number from the server
515: }
516:
517: my $load;
518: if ($loadans =~ /\d/) {
519: if ($userloadans =~ /\d/) {
520: #both are numbers, pick the bigger one
521: $load = ($loadans > $userloadans) ? $loadans
522: : $userloadans;
523: } else {
524: $load = $loadans;
525: }
526: } else {
527: $load = $userloadans;
528: }
529:
530: if (($load =~ /\d/) && ($load < $lowest_load)) {
531: $spare_server = $try_server;
532: $lowest_load = $load;
533: }
534: return ($spare_server,$lowest_load);
535: }
536: # --------------------------------------------- Try to change a user's password
537:
538: sub changepass {
539: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
540: $currentpass = &escape($currentpass);
541: $newpass = &escape($newpass);
542: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
543: $server);
544: if (! $answer) {
545: &logthis("No reply on password change request to $server ".
546: "by $uname in domain $udom.");
547: } elsif ($answer =~ "^ok") {
548: &logthis("$uname in $udom successfully changed their password ".
549: "on $server.");
550: } elsif ($answer =~ "^pwchange_failure") {
551: &logthis("$uname in $udom was unable to change their password ".
552: "on $server. The action was blocked by either lcpasswd ".
553: "or pwchange");
554: } elsif ($answer =~ "^non_authorized") {
555: &logthis("$uname in $udom did not get their password correct when ".
556: "attempting to change it on $server.");
557: } elsif ($answer =~ "^auth_mode_error") {
558: &logthis("$uname in $udom attempted to change their password despite ".
559: "not being locally or internally authenticated on $server.");
560: } elsif ($answer =~ "^unknown_user") {
561: &logthis("$uname in $udom attempted to change their password ".
562: "on $server but were unable to because $server is not ".
563: "their home server.");
564: } elsif ($answer =~ "^refused") {
565: &logthis("$server refused to change $uname in $udom password because ".
566: "it was sent an unencrypted request to change the password.");
567: }
568: return $answer;
569: }
570:
571: # ----------------------- Try to determine user's current authentication scheme
572:
573: sub queryauthenticate {
574: my ($uname,$udom)=@_;
575: my $uhome=&homeserver($uname,$udom);
576: if (!$uhome) {
577: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
578: return 'no_host';
579: }
580: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
581: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
582: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
583: }
584: return $answer;
585: }
586:
587: # --------- Try to authenticate user from domain's lib servers (first this one)
588:
589: sub authenticate {
590: my ($uname,$upass,$udom)=@_;
591: $upass=&escape($upass);
592: $uname= &LONCAPA::clean_username($uname);
593: my $uhome=&homeserver($uname,$udom);
594: if (!$uhome) {
595: &logthis("User $uname at $udom is unknown in authenticate");
596: return 'no_host';
597: }
598: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
599: if ($answer eq 'authorized') {
600: &logthis("User $uname at $udom authorized by $uhome");
601: return $uhome;
602: }
603: if ($answer eq 'non_authorized') {
604: &logthis("User $uname at $udom rejected by $uhome");
605: return 'no_host';
606: }
607: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
608: return 'no_host';
609: }
610:
611: # ---------------------- Find the homebase for a user from domain's lib servers
612:
613: my %homecache;
614: sub homeserver {
615: my ($uname,$udom,$ignoreBadCache)=@_;
616: my $index="$uname:$udom";
617:
618: if (exists($homecache{$index})) { return $homecache{$index}; }
619: my $tryserver;
620: foreach $tryserver (keys %libserv) {
621: next if ($ignoreBadCache ne 'true' &&
622: exists($badServerCache{$tryserver}));
623: if ($hostdom{$tryserver} eq $udom) {
624: my $answer=reply("home:$udom:$uname",$tryserver);
625: if ($answer eq 'found') {
626: return $homecache{$index}=$tryserver;
627: } elsif ($answer eq 'no_host') {
628: $badServerCache{$tryserver}=1;
629: }
630: }
631: }
632: return 'no_host';
633: }
634:
635: # ------------------------------------- Find the usernames behind a list of IDs
636:
637: sub idget {
638: my ($udom,@ids)=@_;
639: my %returnhash=();
640:
641: my $tryserver;
642: foreach $tryserver (keys %libserv) {
643: if ($hostdom{$tryserver} eq $udom) {
644: my $idlist=join('&',@ids);
645: $idlist=~tr/A-Z/a-z/;
646: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
647: my @answer=();
648: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
649: @answer=split(/\&/,$reply);
650: } ;
651: my $i;
652: for ($i=0;$i<=$#ids;$i++) {
653: if ($answer[$i]) {
654: $returnhash{$ids[$i]}=$answer[$i];
655: }
656: }
657: }
658: }
659: return %returnhash;
660: }
661:
662: # ------------------------------------- Find the IDs behind a list of usernames
663:
664: sub idrget {
665: my ($udom,@unames)=@_;
666: my %returnhash=();
667: foreach my $uname (@unames) {
668: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
669: }
670: return %returnhash;
671: }
672:
673: # ------------------------------- Store away a list of names and associated IDs
674:
675: sub idput {
676: my ($udom,%ids)=@_;
677: my %servers=();
678: foreach my $uname (keys(%ids)) {
679: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
680: my $uhom=&homeserver($uname,$udom);
681: if ($uhom ne 'no_host') {
682: my $id=&escape($ids{$uname});
683: $id=~tr/A-Z/a-z/;
684: my $esc_unam=&escape($uname);
685: if ($servers{$uhom}) {
686: $servers{$uhom}.='&'.$id.'='.$esc_unam;
687: } else {
688: $servers{$uhom}=$id.'='.$esc_unam;
689: }
690: }
691: }
692: foreach my $server (keys(%servers)) {
693: &critical('idput:'.$udom.':'.$servers{$server},$server);
694: }
695: }
696:
697: # ------------------------------------------- get items from domain db files
698:
699: sub get_dom {
700: my ($namespace,$storearr,$udom)=@_;
701: my $items='';
702: foreach my $item (@$storearr) {
703: $items.=&escape($item).'&';
704: }
705: $items=~s/\&$//;
706: if (!$udom) { $udom=$env{'user.domain'}; }
707: if (exists($domain_primary{$udom})) {
708: my $uhome=$domain_primary{$udom};
709: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
710: my @pairs=split(/\&/,$rep);
711: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
712: return @pairs;
713: }
714: my %returnhash=();
715: my $i=0;
716: foreach my $item (@$storearr) {
717: $returnhash{$item}=&thaw_unescape($pairs[$i]);
718: $i++;
719: }
720: return %returnhash;
721: } else {
722: &logthis("get_dom failed - no primary domain server for $udom");
723: }
724: }
725:
726: # -------------------------------------------- put items in domain db files
727:
728: sub put_dom {
729: my ($namespace,$storehash,$udom)=@_;
730: if (!$udom) { $udom=$env{'user.domain'}; }
731: if (exists($domain_primary{$udom})) {
732: my $uhome=$domain_primary{$udom};
733: my $items='';
734: foreach my $item (keys(%$storehash)) {
735: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
736: }
737: $items=~s/\&$//;
738: return &reply("putdom:$udom:$namespace:$items",$uhome);
739: } else {
740: &logthis("put_dom failed - no primary domain server for $udom");
741: }
742: }
743:
744: # --------------------------------------------------- Assign a key to a student
745:
746: sub assign_access_key {
747: #
748: # a valid key looks like uname:udom#comments
749: # comments are being appended
750: #
751: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
752: $kdom=
753: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
754: $knum=
755: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
756: $cdom=
757: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
758: $cnum=
759: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
760: $udom=$env{'user.name'} unless (defined($udom));
761: $uname=$env{'user.domain'} unless (defined($uname));
762: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
763: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
764: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
765: # assigned to this person
766: # - this should not happen,
767: # unless something went wrong
768: # the first time around
769: # ready to assign
770: $logentry=$1.'; '.$logentry;
771: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
772: $kdom,$knum) eq 'ok') {
773: # key now belongs to user
774: my $envkey='key.'.$cdom.'_'.$cnum;
775: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
776: &appenv('environment.'.$envkey => $ckey);
777: return 'ok';
778: } else {
779: return
780: 'error: Count not permanently assign key, will need to be re-entered later.';
781: }
782: } else {
783: return 'error: Could not assign key, try again later.';
784: }
785: } elsif (!$existing{$ckey}) {
786: # the key does not exist
787: return 'error: The key does not exist';
788: } else {
789: # the key is somebody else's
790: return 'error: The key is already in use';
791: }
792: }
793:
794: # ------------------------------------------ put an additional comment on a key
795:
796: sub comment_access_key {
797: #
798: # a valid key looks like uname:udom#comments
799: # comments are being appended
800: #
801: my ($ckey,$cdom,$cnum,$logentry)=@_;
802: $cdom=
803: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
804: $cnum=
805: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
806: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
807: if ($existing{$ckey}) {
808: $existing{$ckey}.='; '.$logentry;
809: # ready to assign
810: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
811: $cdom,$cnum) eq 'ok') {
812: return 'ok';
813: } else {
814: return 'error: Count not store comment.';
815: }
816: } else {
817: # the key does not exist
818: return 'error: The key does not exist';
819: }
820: }
821:
822: # ------------------------------------------------------ Generate a set of keys
823:
824: sub generate_access_keys {
825: my ($number,$cdom,$cnum,$logentry)=@_;
826: $cdom=
827: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
828: $cnum=
829: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
830: unless (&allowed('mky',$cdom)) { return 0; }
831: unless (($cdom) && ($cnum)) { return 0; }
832: if ($number>10000) { return 0; }
833: sleep(2); # make sure don't get same seed twice
834: srand(time()^($$+($$<<15))); # from "Programming Perl"
835: my $total=0;
836: for (my $i=1;$i<=$number;$i++) {
837: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
838: sprintf("%lx",int(100000*rand)).'-'.
839: sprintf("%lx",int(100000*rand));
840: $newkey=~s/1/g/g; # folks mix up 1 and l
841: $newkey=~s/0/h/g; # and also 0 and O
842: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
843: if ($existing{$newkey}) {
844: $i--;
845: } else {
846: if (&put('accesskeys',
847: { $newkey => '# generated '.localtime().
848: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
849: '; '.$logentry },
850: $cdom,$cnum) eq 'ok') {
851: $total++;
852: }
853: }
854: }
855: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
856: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
857: return $total;
858: }
859:
860: # ------------------------------------------------------- Validate an accesskey
861:
862: sub validate_access_key {
863: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
864: $cdom=
865: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
866: $cnum=
867: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
868: $udom=$env{'user.domain'} unless (defined($udom));
869: $uname=$env{'user.name'} unless (defined($uname));
870: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
871: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
872: }
873:
874: # ------------------------------------- Find the section of student in a course
875: sub devalidate_getsection_cache {
876: my ($udom,$unam,$courseid)=@_;
877: my $hashid="$udom:$unam:$courseid";
878: &devalidate_cache_new('getsection',$hashid);
879: }
880:
881: sub getsection {
882: my ($udom,$unam,$courseid)=@_;
883: my $cachetime=1800;
884:
885: my $hashid="$udom:$unam:$courseid";
886: my ($result,$cached)=&is_cached_new('getsection',$hashid);
887: if (defined($cached)) { return $result; }
888:
889: my %Pending;
890: my %Expired;
891: #
892: # Each role can either have not started yet (pending), be active,
893: # or have expired.
894: #
895: # If there is an active role, we are done.
896: #
897: # If there is more than one role which has not started yet,
898: # choose the one which will start sooner
899: # If there is one role which has not started yet, return it.
900: #
901: # If there is more than one expired role, choose the one which ended last.
902: # If there is a role which has expired, return it.
903: #
904: foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
905: &homeserver($unam,$udom)))) {
906: my ($key,$value)=split(/\=/,$line,2);
907: $key=&unescape($key);
908: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
909: my $section=$1;
910: if ($key eq $courseid.'_st') { $section=''; }
911: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
912: my $now=time;
913: if (defined($end) && $end && ($now > $end)) {
914: $Expired{$end}=$section;
915: next;
916: }
917: if (defined($start) && $start && ($now < $start)) {
918: $Pending{$start}=$section;
919: next;
920: }
921: return &do_cache_new('getsection',$hashid,$section,$cachetime);
922: }
923: #
924: # Presumedly there will be few matching roles from the above
925: # loop and the sorting time will be negligible.
926: if (scalar(keys(%Pending))) {
927: my ($time) = sort {$a <=> $b} keys(%Pending);
928: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
929: }
930: if (scalar(keys(%Expired))) {
931: my @sorted = sort {$a <=> $b} keys(%Expired);
932: my $time = pop(@sorted);
933: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
934: }
935: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
936: }
937:
938: sub save_cache {
939: &purge_remembered();
940: #&Apache::loncommon::validate_page();
941: undef(%env);
942: undef($env_loaded);
943: }
944:
945: my $to_remember=-1;
946: my %remembered;
947: my %accessed;
948: my $kicks=0;
949: my $hits=0;
950: sub devalidate_cache_new {
951: my ($name,$id,$debug) = @_;
952: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
953: $id=&escape($name.':'.$id);
954: $memcache->delete($id);
955: delete($remembered{$id});
956: delete($accessed{$id});
957: }
958:
959: sub is_cached_new {
960: my ($name,$id,$debug) = @_;
961: $id=&escape($name.':'.$id);
962: if (exists($remembered{$id})) {
963: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
964: $accessed{$id}=[&gettimeofday()];
965: $hits++;
966: return ($remembered{$id},1);
967: }
968: my $value = $memcache->get($id);
969: if (!(defined($value))) {
970: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
971: return (undef,undef);
972: }
973: if ($value eq '__undef__') {
974: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
975: $value=undef;
976: }
977: &make_room($id,$value,$debug);
978: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
979: return ($value,1);
980: }
981:
982: sub do_cache_new {
983: my ($name,$id,$value,$time,$debug) = @_;
984: $id=&escape($name.':'.$id);
985: my $setvalue=$value;
986: if (!defined($setvalue)) {
987: $setvalue='__undef__';
988: }
989: if (!defined($time) ) {
990: $time=600;
991: }
992: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
993: $memcache->set($id,$setvalue,$time);
994: # need to make a copy of $value
995: #&make_room($id,$value,$debug);
996: return $value;
997: }
998:
999: sub make_room {
1000: my ($id,$value,$debug)=@_;
1001: $remembered{$id}=$value;
1002: if ($to_remember<0) { return; }
1003: $accessed{$id}=[&gettimeofday()];
1004: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1005: my $to_kick;
1006: my $max_time=0;
1007: foreach my $other (keys(%accessed)) {
1008: if (&tv_interval($accessed{$other}) > $max_time) {
1009: $to_kick=$other;
1010: $max_time=&tv_interval($accessed{$other});
1011: }
1012: }
1013: delete($remembered{$to_kick});
1014: delete($accessed{$to_kick});
1015: $kicks++;
1016: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1017: return;
1018: }
1019:
1020: sub purge_remembered {
1021: #&logthis("Tossing ".scalar(keys(%remembered)));
1022: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1023: undef(%remembered);
1024: undef(%accessed);
1025: }
1026: # ------------------------------------- Read an entry from a user's environment
1027:
1028: sub userenvironment {
1029: my ($udom,$unam,@what)=@_;
1030: my %returnhash=();
1031: my @answer=split(/\&/,
1032: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1033: &homeserver($unam,$udom)));
1034: my $i;
1035: for ($i=0;$i<=$#what;$i++) {
1036: $returnhash{$what[$i]}=&unescape($answer[$i]);
1037: }
1038: return %returnhash;
1039: }
1040:
1041: # ---------------------------------------------------------- Get a studentphoto
1042: sub studentphoto {
1043: my ($udom,$unam,$ext) = @_;
1044: my $home=&Apache::lonnet::homeserver($unam,$udom);
1045: if (defined($env{'request.course.id'})) {
1046: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1047: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1048: return(&retrievestudentphoto($udom,$unam,$ext));
1049: } else {
1050: my ($result,$perm_reqd)=
1051: &Apache::lonnet::auto_photo_permission($unam,$udom);
1052: if ($result eq 'ok') {
1053: if (!($perm_reqd eq 'yes')) {
1054: return(&retrievestudentphoto($udom,$unam,$ext));
1055: }
1056: }
1057: }
1058: }
1059: } else {
1060: my ($result,$perm_reqd) =
1061: &Apache::lonnet::auto_photo_permission($unam,$udom);
1062: if ($result eq 'ok') {
1063: if (!($perm_reqd eq 'yes')) {
1064: return(&retrievestudentphoto($udom,$unam,$ext));
1065: }
1066: }
1067: }
1068: return '/adm/lonKaputt/lonlogo_broken.gif';
1069: }
1070:
1071: sub retrievestudentphoto {
1072: my ($udom,$unam,$ext,$type) = @_;
1073: my $home=&Apache::lonnet::homeserver($unam,$udom);
1074: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1075: if ($ret eq 'ok') {
1076: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1077: if ($type eq 'thumbnail') {
1078: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1079: }
1080: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1081: return $tokenurl;
1082: } else {
1083: if ($type eq 'thumbnail') {
1084: return '/adm/lonKaputt/genericstudent_tn.gif';
1085: } else {
1086: return '/adm/lonKaputt/lonlogo_broken.gif';
1087: }
1088: }
1089: }
1090:
1091: # -------------------------------------------------------------------- New chat
1092:
1093: sub chatsend {
1094: my ($newentry,$anon,$group)=@_;
1095: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1096: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1097: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1098: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1099: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1100: &escape($newentry)).':'.$group,$chome);
1101: }
1102:
1103: # ------------------------------------------ Find current version of a resource
1104:
1105: sub getversion {
1106: my $fname=&clutter(shift);
1107: unless ($fname=~/^\/res\//) { return -1; }
1108: return ¤tversion(&filelocation('',$fname));
1109: }
1110:
1111: sub currentversion {
1112: my $fname=shift;
1113: my ($result,$cached)=&is_cached_new('resversion',$fname);
1114: if (defined($cached)) { return $result; }
1115: my $author=$fname;
1116: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1117: my ($udom,$uname)=split(/\//,$author);
1118: my $home=homeserver($uname,$udom);
1119: if ($home eq 'no_host') {
1120: return -1;
1121: }
1122: my $answer=reply("currentversion:$fname",$home);
1123: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1124: return -1;
1125: }
1126: return &do_cache_new('resversion',$fname,$answer,600);
1127: }
1128:
1129: # ----------------------------- Subscribe to a resource, return URL if possible
1130:
1131: sub subscribe {
1132: my $fname=shift;
1133: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1134: $fname=~s/[\n\r]//g;
1135: my $author=$fname;
1136: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1137: my ($udom,$uname)=split(/\//,$author);
1138: my $home=homeserver($uname,$udom);
1139: if ($home eq 'no_host') {
1140: return 'not_found';
1141: }
1142: my $answer=reply("sub:$fname",$home);
1143: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1144: $answer.=' by '.$home;
1145: }
1146: return $answer;
1147: }
1148:
1149: # -------------------------------------------------------------- Replicate file
1150:
1151: sub repcopy {
1152: my $filename=shift;
1153: $filename=~s/\/+/\//g;
1154: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1155: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1156: if ($filename=~m|^/home/httpd/html/userfiles/| or
1157: $filename=~m -^/*(uploaded|editupload)/-) {
1158: return &repcopy_userfile($filename);
1159: }
1160: $filename=~s/[\n\r]//g;
1161: my $transname="$filename.in.transfer";
1162: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1163: my $remoteurl=subscribe($filename);
1164: if ($remoteurl =~ /^con_lost by/) {
1165: &logthis("Subscribe returned $remoteurl: $filename");
1166: return 'unavailable';
1167: } elsif ($remoteurl eq 'not_found') {
1168: #&logthis("Subscribe returned not_found: $filename");
1169: return 'not_found';
1170: } elsif ($remoteurl =~ /^rejected by/) {
1171: &logthis("Subscribe returned $remoteurl: $filename");
1172: return 'forbidden';
1173: } elsif ($remoteurl eq 'directory') {
1174: return 'ok';
1175: } else {
1176: my $author=$filename;
1177: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1178: my ($udom,$uname)=split(/\//,$author);
1179: my $home=homeserver($uname,$udom);
1180: unless ($home eq $perlvar{'lonHostID'}) {
1181: my @parts=split(/\//,$filename);
1182: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1183: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1184: &logthis("Malconfiguration for replication: $filename");
1185: return 'bad_request';
1186: }
1187: my $count;
1188: for ($count=5;$count<$#parts;$count++) {
1189: $path.="/$parts[$count]";
1190: if ((-e $path)!=1) {
1191: mkdir($path,0777);
1192: }
1193: }
1194: my $ua=new LWP::UserAgent;
1195: my $request=new HTTP::Request('GET',"$remoteurl");
1196: my $response=$ua->request($request,$transname);
1197: if ($response->is_error()) {
1198: unlink($transname);
1199: my $message=$response->status_line;
1200: &logthis("<font color=\"blue\">WARNING:"
1201: ." LWP get: $message: $filename</font>");
1202: return 'unavailable';
1203: } else {
1204: if ($remoteurl!~/\.meta$/) {
1205: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1206: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1207: if ($mresponse->is_error()) {
1208: unlink($filename.'.meta');
1209: &logthis(
1210: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1211: }
1212: }
1213: rename($transname,$filename);
1214: return 'ok';
1215: }
1216: }
1217: }
1218: }
1219:
1220: # ------------------------------------------------ Get server side include body
1221: sub ssi_body {
1222: my ($filelink,%form)=@_;
1223: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1224: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1225: }
1226: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1227: &ssi($filelink,%form));
1228: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1229: $output=~s/^.*?\<body[^\>]*\>//si;
1230: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1231: return $output;
1232: }
1233:
1234: # --------------------------------------------------------- Server Side Include
1235:
1236: sub absolute_url {
1237: my ($host_name) = @_;
1238: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1239: if ($host_name eq '') {
1240: $host_name = $ENV{'SERVER_NAME'};
1241: }
1242: return $protocol.$host_name;
1243: }
1244:
1245: sub ssi {
1246:
1247: my ($fn,%form)=@_;
1248:
1249: my $ua=new LWP::UserAgent;
1250:
1251: my $request;
1252:
1253: $form{'no_update_last_known'}=1;
1254:
1255: if (%form) {
1256: $request=new HTTP::Request('POST',&absolute_url().$fn);
1257: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1258: } else {
1259: $request=new HTTP::Request('GET',&absolute_url().$fn);
1260: }
1261:
1262: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1263: my $response=$ua->request($request);
1264:
1265: return $response->content;
1266: }
1267:
1268: sub externalssi {
1269: my ($url)=@_;
1270: my $ua=new LWP::UserAgent;
1271: my $request=new HTTP::Request('GET',$url);
1272: my $response=$ua->request($request);
1273: return $response->content;
1274: }
1275:
1276: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1277:
1278: sub allowuploaded {
1279: my ($srcurl,$url)=@_;
1280: $url=&clutter(&declutter($url));
1281: my $dir=$url;
1282: $dir=~s/\/[^\/]+$//;
1283: my %httpref=();
1284: my $httpurl=&hreflocation('',$url);
1285: $httpref{'httpref.'.$httpurl}=$srcurl;
1286: &Apache::lonnet::appenv(%httpref);
1287: }
1288:
1289: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1290: # input: action, courseID, current domain, intended
1291: # path to file, source of file, instruction to parse file for objects,
1292: # ref to hash for embedded objects,
1293: # ref to hash for codebase of java objects.
1294: #
1295: # output: url to file (if action was uploaddoc),
1296: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1297: #
1298: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1299: # course.
1300: #
1301: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1302: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1303: # course's home server.
1304: #
1305: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1306: # be copied from $source (current location) to
1307: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1308: # and will then be copied to
1309: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1310: # course's home server.
1311: #
1312: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1313: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1314: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1315: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1316: # in course's home server.
1317: #
1318:
1319: sub process_coursefile {
1320: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1321: my $fetchresult;
1322: my $home=&homeserver($docuname,$docudom);
1323: if ($action eq 'propagate') {
1324: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1325: $home);
1326: } else {
1327: my $fpath = '';
1328: my $fname = $file;
1329: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1330: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1331: my $filepath = &build_filepath($fpath);
1332: if ($action eq 'copy') {
1333: if ($source eq '') {
1334: $fetchresult = 'no source file';
1335: return $fetchresult;
1336: } else {
1337: my $destination = $filepath.'/'.$fname;
1338: rename($source,$destination);
1339: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1340: $home);
1341: }
1342: } elsif ($action eq 'uploaddoc') {
1343: open(my $fh,'>'.$filepath.'/'.$fname);
1344: print $fh $env{'form.'.$source};
1345: close($fh);
1346: if ($parser eq 'parse') {
1347: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1348: unless ($parse_result eq 'ok') {
1349: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1350: }
1351: }
1352: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1353: $home);
1354: if ($fetchresult eq 'ok') {
1355: return '/uploaded/'.$fpath.'/'.$fname;
1356: } else {
1357: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1358: ' to host '.$home.': '.$fetchresult);
1359: return '/adm/notfound.html';
1360: }
1361: }
1362: }
1363: unless ( $fetchresult eq 'ok') {
1364: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1365: ' to host '.$home.': '.$fetchresult);
1366: }
1367: return $fetchresult;
1368: }
1369:
1370: sub build_filepath {
1371: my ($fpath) = @_;
1372: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1373: unless ($fpath eq '') {
1374: my @parts=split('/',$fpath);
1375: foreach my $part (@parts) {
1376: $filepath.= '/'.$part;
1377: if ((-e $filepath)!=1) {
1378: mkdir($filepath,0777);
1379: }
1380: }
1381: }
1382: return $filepath;
1383: }
1384:
1385: sub store_edited_file {
1386: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1387: my $file = $primary_url;
1388: $file =~ s#^/uploaded/$docudom/$docuname/##;
1389: my $fpath = '';
1390: my $fname = $file;
1391: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1392: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1393: my $filepath = &build_filepath($fpath);
1394: open(my $fh,'>'.$filepath.'/'.$fname);
1395: print $fh $content;
1396: close($fh);
1397: my $home=&homeserver($docuname,$docudom);
1398: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1399: $home);
1400: if ($$fetchresult eq 'ok') {
1401: return '/uploaded/'.$fpath.'/'.$fname;
1402: } else {
1403: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1404: ' to host '.$home.': '.$$fetchresult);
1405: return '/adm/notfound.html';
1406: }
1407: }
1408:
1409: sub clean_filename {
1410: my ($fname)=@_;
1411: # Replace Windows backslashes by forward slashes
1412: $fname=~s/\\/\//g;
1413: # Get rid of everything but the actual filename
1414: $fname=~s/^.*\/([^\/]+)$/$1/;
1415: # Replace spaces by underscores
1416: $fname=~s/\s+/\_/g;
1417: # Replace all other weird characters by nothing
1418: $fname=~s/[^\w\.\-]//g;
1419: # Replace all .\d. sequences with _\d. so they no longer look like version
1420: # numbers
1421: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1422: return $fname;
1423: }
1424:
1425: # --------------- Take an uploaded file and put it into the userfiles directory
1426: # input: $formname - the contents of the file are in $env{"form.$formname"}
1427: # the desired filenam is in $env{"form.$formname.filename"}
1428: # $coursedoc - if true up to the current course
1429: # if false
1430: # $subdir - directory in userfile to store the file into
1431: # $parser, $allfiles, $codebase - unknown
1432: #
1433: # output: url of file in userspace, or error: <message>
1434: # or /adm/notfound.html if failure to upload occurse
1435:
1436:
1437: sub userfileupload {
1438: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1439: if (!defined($subdir)) { $subdir='unknown'; }
1440: my $fname=$env{'form.'.$formname.'.filename'};
1441: $fname=&clean_filename($fname);
1442: # See if there is anything left
1443: unless ($fname) { return 'error: no uploaded file'; }
1444: chop($env{'form.'.$formname});
1445: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1446: my $now = time;
1447: my $filepath = 'tmp/helprequests/'.$now;
1448: my @parts=split(/\//,$filepath);
1449: my $fullpath = $perlvar{'lonDaemons'};
1450: for (my $i=0;$i<@parts;$i++) {
1451: $fullpath .= '/'.$parts[$i];
1452: if ((-e $fullpath)!=1) {
1453: mkdir($fullpath,0777);
1454: }
1455: }
1456: open(my $fh,'>'.$fullpath.'/'.$fname);
1457: print $fh $env{'form.'.$formname};
1458: close($fh);
1459: return $fullpath.'/'.$fname;
1460: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1461: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1462: '_'.$env{'user.domain'}.'/pending';
1463: my @parts=split(/\//,$filepath);
1464: my $fullpath = $perlvar{'lonDaemons'};
1465: for (my $i=0;$i<@parts;$i++) {
1466: $fullpath .= '/'.$parts[$i];
1467: if ((-e $fullpath)!=1) {
1468: mkdir($fullpath,0777);
1469: }
1470: }
1471: open(my $fh,'>'.$fullpath.'/'.$fname);
1472: print $fh $env{'form.'.$formname};
1473: close($fh);
1474: return $fullpath.'/'.$fname;
1475: }
1476:
1477: # Create the directory if not present
1478: $fname="$subdir/$fname";
1479: if ($coursedoc) {
1480: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1481: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1482: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1483: return &finishuserfileupload($docuname,$docudom,
1484: $formname,$fname,$parser,$allfiles,
1485: $codebase);
1486: } else {
1487: $fname=$env{'form.folder'}.'/'.$fname;
1488: return &process_coursefile('uploaddoc',$docuname,$docudom,
1489: $fname,$formname,$parser,
1490: $allfiles,$codebase);
1491: }
1492: } elsif (defined($destuname)) {
1493: my $docuname=$destuname;
1494: my $docudom=$destudom;
1495: return &finishuserfileupload($docuname,$docudom,$formname,
1496: $fname,$parser,$allfiles,$codebase);
1497:
1498: } else {
1499: my $docuname=$env{'user.name'};
1500: my $docudom=$env{'user.domain'};
1501: if (exists($env{'form.group'})) {
1502: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1503: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1504: }
1505: return &finishuserfileupload($docuname,$docudom,$formname,
1506: $fname,$parser,$allfiles,$codebase);
1507: }
1508: }
1509:
1510: sub finishuserfileupload {
1511: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1512: my $path=$docudom.'/'.$docuname.'/';
1513: my $filepath=$perlvar{'lonDocRoot'};
1514: my ($fnamepath,$file);
1515: $file=$fname;
1516: if ($fname=~m|/|) {
1517: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1518: $path.=$fnamepath.'/';
1519: }
1520: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1521: my $count;
1522: for ($count=4;$count<=$#parts;$count++) {
1523: $filepath.="/$parts[$count]";
1524: if ((-e $filepath)!=1) {
1525: mkdir($filepath,0777);
1526: }
1527: }
1528: # Save the file
1529: {
1530: if (!open(FH,'>'.$filepath.'/'.$file)) {
1531: &logthis('Failed to create '.$filepath.'/'.$file);
1532: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1533: return '/adm/notfound.html';
1534: }
1535: if (!print FH ($env{'form.'.$formname})) {
1536: &logthis('Failed to write to '.$filepath.'/'.$file);
1537: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1538: return '/adm/notfound.html';
1539: }
1540: close(FH);
1541: }
1542: if ($parser eq 'parse') {
1543: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1544: $codebase);
1545: unless ($parse_result eq 'ok') {
1546: &logthis('Failed to parse '.$filepath.$file.
1547: ' for embedded media: '.$parse_result);
1548: }
1549: }
1550: # Notify homeserver to grep it
1551: #
1552: my $docuhome=&homeserver($docuname,$docudom);
1553: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1554: if ($fetchresult eq 'ok') {
1555: #
1556: # Return the URL to it
1557: return '/uploaded/'.$path.$file;
1558: } else {
1559: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1560: ': '.$fetchresult);
1561: return '/adm/notfound.html';
1562: }
1563: }
1564:
1565: sub extract_embedded_items {
1566: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1567: my @state = ();
1568: my %javafiles = (
1569: codebase => '',
1570: code => '',
1571: archive => ''
1572: );
1573: my %mediafiles = (
1574: src => '',
1575: movie => '',
1576: );
1577: my $p;
1578: if ($content) {
1579: $p = HTML::LCParser->new($content);
1580: } else {
1581: $p = HTML::LCParser->new($filepath.'/'.$file);
1582: }
1583: while (my $t=$p->get_token()) {
1584: if ($t->[0] eq 'S') {
1585: my ($tagname, $attr) = ($t->[1],$t->[2]);
1586: push (@state, $tagname);
1587: if (lc($tagname) eq 'allow') {
1588: &add_filetype($allfiles,$attr->{'src'},'src');
1589: }
1590: if (lc($tagname) eq 'img') {
1591: &add_filetype($allfiles,$attr->{'src'},'src');
1592: }
1593: if (lc($tagname) eq 'script') {
1594: if ($attr->{'archive'} =~ /\.jar$/i) {
1595: &add_filetype($allfiles,$attr->{'archive'},'archive');
1596: } else {
1597: &add_filetype($allfiles,$attr->{'src'},'src');
1598: }
1599: }
1600: if (lc($tagname) eq 'link') {
1601: if (lc($attr->{'rel'}) eq 'stylesheet') {
1602: &add_filetype($allfiles,$attr->{'href'},'href');
1603: }
1604: }
1605: if (lc($tagname) eq 'object' ||
1606: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1607: foreach my $item (keys(%javafiles)) {
1608: $javafiles{$item} = '';
1609: }
1610: }
1611: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1612: my $name = lc($attr->{'name'});
1613: foreach my $item (keys(%javafiles)) {
1614: if ($name eq $item) {
1615: $javafiles{$item} = $attr->{'value'};
1616: last;
1617: }
1618: }
1619: foreach my $item (keys(%mediafiles)) {
1620: if ($name eq $item) {
1621: &add_filetype($allfiles, $attr->{'value'}, 'value');
1622: last;
1623: }
1624: }
1625: }
1626: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1627: foreach my $item (keys(%javafiles)) {
1628: if ($attr->{$item}) {
1629: $javafiles{$item} = $attr->{$item};
1630: last;
1631: }
1632: }
1633: foreach my $item (keys(%mediafiles)) {
1634: if ($attr->{$item}) {
1635: &add_filetype($allfiles,$attr->{$item},$item);
1636: last;
1637: }
1638: }
1639: }
1640: } elsif ($t->[0] eq 'E') {
1641: my ($tagname) = ($t->[1]);
1642: if ($javafiles{'codebase'} ne '') {
1643: $javafiles{'codebase'} .= '/';
1644: }
1645: if (lc($tagname) eq 'applet' ||
1646: lc($tagname) eq 'object' ||
1647: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1648: ) {
1649: foreach my $item (keys(%javafiles)) {
1650: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1651: my $file=$javafiles{'codebase'}.$javafiles{$item};
1652: &add_filetype($allfiles,$file,$item);
1653: }
1654: }
1655: }
1656: pop @state;
1657: }
1658: }
1659: return 'ok';
1660: }
1661:
1662: sub add_filetype {
1663: my ($allfiles,$file,$type)=@_;
1664: if (exists($allfiles->{$file})) {
1665: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1666: push(@{$allfiles->{$file}}, &escape($type));
1667: }
1668: } else {
1669: @{$allfiles->{$file}} = (&escape($type));
1670: }
1671: }
1672:
1673: sub removeuploadedurl {
1674: my ($url)=@_;
1675: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1676: return &removeuserfile($uname,$udom,$fname);
1677: }
1678:
1679: sub removeuserfile {
1680: my ($docuname,$docudom,$fname)=@_;
1681: my $home=&homeserver($docuname,$docudom);
1682: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1683: if ($result eq 'ok') {
1684: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1685: my $metafile = $fname.'.meta';
1686: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1687: }
1688: }
1689: return $result;
1690: }
1691:
1692: sub mkdiruserfile {
1693: my ($docuname,$docudom,$dir)=@_;
1694: my $home=&homeserver($docuname,$docudom);
1695: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1696: }
1697:
1698: sub renameuserfile {
1699: my ($docuname,$docudom,$old,$new)=@_;
1700: my $home=&homeserver($docuname,$docudom);
1701: my $result = &reply("renameuserfile:$docudom:$docuname:".
1702: &escape("$old").':'.&escape("$new"),$home);
1703: if ($result eq 'ok') {
1704: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1705: my $oldmeta = $old.'.meta';
1706: my $newmeta = $new.'.meta';
1707: my $metaresult =
1708: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1709: }
1710: }
1711: return $result;
1712: }
1713:
1714: # ------------------------------------------------------------------------- Log
1715:
1716: sub log {
1717: my ($dom,$nam,$hom,$what)=@_;
1718: return critical("log:$dom:$nam:$what",$hom);
1719: }
1720:
1721: # ------------------------------------------------------------------ Course Log
1722: #
1723: # This routine flushes several buffers of non-mission-critical nature
1724: #
1725:
1726: sub flushcourselogs {
1727: &logthis('Flushing log buffers');
1728: #
1729: # course logs
1730: # This is a log of all transactions in a course, which can be used
1731: # for data mining purposes
1732: #
1733: # It also collects the courseid database, which lists last transaction
1734: # times and course titles for all courseids
1735: #
1736: my %courseidbuffer=();
1737: foreach my $crsid (keys %courselogs) {
1738: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1739: &escape($courselogs{$crsid}),
1740: $coursehombuf{$crsid}) eq 'ok') {
1741: delete $courselogs{$crsid};
1742: } else {
1743: &logthis('Failed to flush log buffer for '.$crsid);
1744: if (length($courselogs{$crsid})>40000) {
1745: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1746: " exceeded maximum size, deleting.</font>");
1747: delete $courselogs{$crsid};
1748: }
1749: }
1750: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1751: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1752: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1753: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1754: } else {
1755: $courseidbuffer{$coursehombuf{$crsid}}=
1756: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1757: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1758: }
1759: }
1760: #
1761: # Write course id database (reverse lookup) to homeserver of courses
1762: # Is used in pickcourse
1763: #
1764: foreach my $crsid (keys(%courseidbuffer)) {
1765: &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1766: }
1767: #
1768: # File accesses
1769: # Writes to the dynamic metadata of resources to get hit counts, etc.
1770: #
1771: foreach my $entry (keys(%accesshash)) {
1772: if ($entry =~ /___count$/) {
1773: my ($dom,$name);
1774: ($dom,$name,undef)=
1775: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1776: if (! defined($dom) || $dom eq '' ||
1777: ! defined($name) || $name eq '') {
1778: my $cid = $env{'request.course.id'};
1779: $dom = $env{'request.'.$cid.'.domain'};
1780: $name = $env{'request.'.$cid.'.num'};
1781: }
1782: my $value = $accesshash{$entry};
1783: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1784: my %temphash=($url => $value);
1785: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1786: if ($result eq 'ok') {
1787: delete $accesshash{$entry};
1788: } elsif ($result eq 'unknown_cmd') {
1789: # Target server has old code running on it.
1790: my %temphash=($entry => $value);
1791: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1792: delete $accesshash{$entry};
1793: }
1794: }
1795: } else {
1796: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1797: my %temphash=($entry => $accesshash{$entry});
1798: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1799: delete $accesshash{$entry};
1800: }
1801: }
1802: }
1803: #
1804: # Roles
1805: # Reverse lookup of user roles for course faculty/staff and co-authorship
1806: #
1807: foreach my $entry (keys(%userrolehash)) {
1808: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1809: split(/\:/,$entry);
1810: if (&Apache::lonnet::put('nohist_userroles',
1811: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1812: $rudom,$runame) eq 'ok') {
1813: delete $userrolehash{$entry};
1814: }
1815: }
1816: #
1817: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1818: #
1819: my %domrolebuffer = ();
1820: foreach my $entry (keys %domainrolehash) {
1821: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1822: if ($domrolebuffer{$rudom}) {
1823: $domrolebuffer{$rudom}.='&'.&escape($entry).
1824: '='.&escape($domainrolehash{$entry});
1825: } else {
1826: $domrolebuffer{$rudom}.=&escape($entry).
1827: '='.&escape($domainrolehash{$entry});
1828: }
1829: delete $domainrolehash{$entry};
1830: }
1831: foreach my $dom (keys(%domrolebuffer)) {
1832: foreach my $tryserver (keys %libserv) {
1833: if ($hostdom{$tryserver} eq $dom) {
1834: unless (&reply('domroleput:'.$dom.':'.
1835: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1836: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1837: }
1838: }
1839: }
1840: }
1841: $dumpcount++;
1842: }
1843:
1844: sub courselog {
1845: my $what=shift;
1846: $what=time.':'.$what;
1847: unless ($env{'request.course.id'}) { return ''; }
1848: $coursedombuf{$env{'request.course.id'}}=
1849: $env{'course.'.$env{'request.course.id'}.'.domain'};
1850: $coursenumbuf{$env{'request.course.id'}}=
1851: $env{'course.'.$env{'request.course.id'}.'.num'};
1852: $coursehombuf{$env{'request.course.id'}}=
1853: $env{'course.'.$env{'request.course.id'}.'.home'};
1854: $coursedescrbuf{$env{'request.course.id'}}=
1855: $env{'course.'.$env{'request.course.id'}.'.description'};
1856: $courseinstcodebuf{$env{'request.course.id'}}=
1857: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1858: $courseownerbuf{$env{'request.course.id'}}=
1859: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1860: $coursetypebuf{$env{'request.course.id'}}=
1861: $env{'course.'.$env{'request.course.id'}.'.type'};
1862: if (defined $courselogs{$env{'request.course.id'}}) {
1863: $courselogs{$env{'request.course.id'}}.='&'.$what;
1864: } else {
1865: $courselogs{$env{'request.course.id'}}.=$what;
1866: }
1867: if (length($courselogs{$env{'request.course.id'}})>4048) {
1868: &flushcourselogs();
1869: }
1870: }
1871:
1872: sub courseacclog {
1873: my $fnsymb=shift;
1874: unless ($env{'request.course.id'}) { return ''; }
1875: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1876: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1877: $what.=':POST';
1878: # FIXME: Probably ought to escape things....
1879: foreach my $key (keys(%env)) {
1880: if ($key=~/^form\.(.*)/) {
1881: $what.=':'.$1.'='.$env{$key};
1882: }
1883: }
1884: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1885: # FIXME: We should not be depending on a form parameter that someone
1886: # editing lonsearchcat.pm might change in the future.
1887: if ($env{'form.phase'} eq 'course_search') {
1888: $what.= ':POST';
1889: # FIXME: Probably ought to escape things....
1890: foreach my $element ('courseexp','crsfulltext','crsrelated',
1891: 'crsdiscuss') {
1892: $what.=':'.$element.'='.$env{'form.'.$element};
1893: }
1894: }
1895: }
1896: &courselog($what);
1897: }
1898:
1899: sub countacc {
1900: my $url=&declutter(shift);
1901: return if (! defined($url) || $url eq '');
1902: unless ($env{'request.course.id'}) { return ''; }
1903: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1904: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1905: $accesshash{$key}++;
1906: }
1907:
1908: sub linklog {
1909: my ($from,$to)=@_;
1910: $from=&declutter($from);
1911: $to=&declutter($to);
1912: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1913: $accesshash{$to.'___'.$from.'___goto'}=1;
1914: }
1915:
1916: sub userrolelog {
1917: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1918: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1919: ($trole=~/^in/) || ($trole=~/^cc/) ||
1920: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1921: ($trole=~/^ta/)) {
1922: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1923: $userrolehash
1924: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1925: =$tend.':'.$tstart;
1926: }
1927: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
1928: ($trole=~/^li/) || ($trole=~/^li/) ||
1929: ($trole=~/^au/) || ($trole=~/^dg/) ||
1930: ($trole=~/^sc/)) {
1931: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1932: $domainrolehash
1933: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1934: = $tend.':'.$tstart;
1935: }
1936: }
1937:
1938: sub get_course_adv_roles {
1939: my $cid=shift;
1940: $cid=$env{'request.course.id'} unless (defined($cid));
1941: my %coursehash=&coursedescription($cid);
1942: my %nothide=();
1943: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1944: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1945: }
1946: my %returnhash=();
1947: my %dumphash=
1948: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1949: my $now=time;
1950: foreach my $entry (keys %dumphash) {
1951: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1952: if (($tstart) && ($tstart<0)) { next; }
1953: if (($tend) && ($tend<$now)) { next; }
1954: if (($tstart) && ($now<$tstart)) { next; }
1955: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1956: if ($username eq '' || $domain eq '') { next; }
1957: if ((&privileged($username,$domain)) &&
1958: (!$nothide{$username.':'.$domain})) { next; }
1959: if ($role eq 'cr') { next; }
1960: my $key=&plaintext($role);
1961: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1962: if ($returnhash{$key}) {
1963: $returnhash{$key}.=','.$username.':'.$domain;
1964: } else {
1965: $returnhash{$key}=$username.':'.$domain;
1966: }
1967: }
1968: return %returnhash;
1969: }
1970:
1971: sub get_my_roles {
1972: my ($uname,$udom)=@_;
1973: unless (defined($uname)) { $uname=$env{'user.name'}; }
1974: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1975: my %dumphash=
1976: &dump('nohist_userroles',$udom,$uname);
1977: my %returnhash=();
1978: my $now=time;
1979: foreach my $entry (keys(%dumphash)) {
1980: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1981: if (($tstart) && ($tstart<0)) { next; }
1982: if (($tend) && ($tend<$now)) { next; }
1983: if (($tstart) && ($now<$tstart)) { next; }
1984: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1985: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1986: }
1987: return %returnhash;
1988: }
1989:
1990: # ----------------------------------------------------- Frontpage Announcements
1991: #
1992: #
1993:
1994: sub postannounce {
1995: my ($server,$text)=@_;
1996: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1997: unless ($text=~/\w/) { $text=''; }
1998: return &reply('setannounce:'.&escape($text),$server);
1999: }
2000:
2001: sub getannounce {
2002:
2003: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2004: my $announcement='';
2005: while (my $line = <$fh>) { $announcement .= $line; }
2006: close($fh);
2007: if ($announcement=~/\w/) {
2008: return
2009: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2010: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2011: } else {
2012: return '';
2013: }
2014: } else {
2015: return '';
2016: }
2017: }
2018:
2019: # ---------------------------------------------------------- Course ID routines
2020: # Deal with domain's nohist_courseid.db files
2021: #
2022:
2023: sub courseidput {
2024: my ($domain,$what,$coursehome)=@_;
2025: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2026: }
2027:
2028: sub courseiddump {
2029: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
2030: my %returnhash=();
2031: unless ($domfilter) { $domfilter=''; }
2032: foreach my $tryserver (keys %libserv) {
2033: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
2034: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
2035: foreach my $line (
2036: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
2037: $sincefilter.':'.&escape($descfilter).':'.
2038: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
2039: $tryserver))) {
2040: my ($key,$value)=split(/\=/,$line,2);
2041: if (($key) && ($value)) {
2042: $returnhash{&unescape($key)}=$value;
2043: }
2044: }
2045: }
2046: }
2047: }
2048: return %returnhash;
2049: }
2050:
2051: # ---------------------------------------------------------- DC e-mail
2052:
2053: sub dcmailput {
2054: my ($domain,$msgid,$message,$server)=@_;
2055: my $status = &Apache::lonnet::critical(
2056: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2057: &escape($message),$server);
2058: return $status;
2059: }
2060:
2061: sub dcmaildump {
2062: my ($dom,$startdate,$enddate,$senders) = @_;
2063: my %returnhash=();
2064: if (exists($domain_primary{$dom})) {
2065: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2066: &escape($enddate).':';
2067: my @esc_senders=map { &escape($_)} @$senders;
2068: $cmd.=&escape(join('&',@esc_senders));
2069: foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
2070: my ($key,$value) = split(/\=/,$line,2);
2071: if (($key) && ($value)) {
2072: $returnhash{&unescape($key)} = &unescape($value);
2073: }
2074: }
2075: }
2076: return %returnhash;
2077: }
2078: # ---------------------------------------------------------- Domain roles
2079:
2080: sub get_domain_roles {
2081: my ($dom,$roles,$startdate,$enddate)=@_;
2082: if (undef($startdate) || $startdate eq '') {
2083: $startdate = '.';
2084: }
2085: if (undef($enddate) || $enddate eq '') {
2086: $enddate = '.';
2087: }
2088: my $rolelist = join(':',@{$roles});
2089: my %personnel = ();
2090: foreach my $tryserver (keys(%libserv)) {
2091: if ($hostdom{$tryserver} eq $dom) {
2092: %{$personnel{$tryserver}}=();
2093: foreach my $line (
2094: split(/\&/,&reply('domrolesdump:'.$dom.':'.
2095: &escape($startdate).':'.&escape($enddate).':'.
2096: &escape($rolelist), $tryserver))) {
2097: my ($key,$value) = split(/\=/,$line,2);
2098: if (($key) && ($value)) {
2099: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2100: }
2101: }
2102: }
2103: }
2104: return %personnel;
2105: }
2106:
2107: # ----------------------------------------------------------- Check out an item
2108:
2109: sub get_first_access {
2110: my ($type,$argsymb)=@_;
2111: my ($symb,$courseid,$udom,$uname)=&whichuser();
2112: if ($argsymb) { $symb=$argsymb; }
2113: my ($map,$id,$res)=&decode_symb($symb);
2114: if ($type eq 'map') {
2115: $res=&symbread($map);
2116: } else {
2117: $res=$symb;
2118: }
2119: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2120: return $times{"$courseid\0$res"};
2121: }
2122:
2123: sub set_first_access {
2124: my ($type)=@_;
2125: my ($symb,$courseid,$udom,$uname)=&whichuser();
2126: my ($map,$id,$res)=&decode_symb($symb);
2127: if ($type eq 'map') {
2128: $res=&symbread($map);
2129: } else {
2130: $res=$symb;
2131: }
2132: my $firstaccess=&get_first_access($type,$symb);
2133: if (!$firstaccess) {
2134: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2135: }
2136: return 'already_set';
2137: }
2138:
2139: sub checkout {
2140: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2141: my $now=time;
2142: my $lonhost=$perlvar{'lonHostID'};
2143: my $infostr=&escape(
2144: 'CHECKOUTTOKEN&'.
2145: $tuname.'&'.
2146: $tudom.'&'.
2147: $tcrsid.'&'.
2148: $symb.'&'.
2149: $now.'&'.$ENV{'REMOTE_ADDR'});
2150: my $token=&reply('tmpput:'.$infostr,$lonhost);
2151: if ($token=~/^error\:/) {
2152: &logthis("<font color=\"blue\">WARNING: ".
2153: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2154: "</font>");
2155: return '';
2156: }
2157:
2158: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2159: $token=~tr/a-z/A-Z/;
2160:
2161: my %infohash=('resource.0.outtoken' => $token,
2162: 'resource.0.checkouttime' => $now,
2163: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2164:
2165: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2166: return '';
2167: } else {
2168: &logthis("<font color=\"blue\">WARNING: ".
2169: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2170: "</font>");
2171: }
2172:
2173: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2174: &escape('Checkout '.$infostr.' - '.
2175: $token)) ne 'ok') {
2176: return '';
2177: } else {
2178: &logthis("<font color=\"blue\">WARNING: ".
2179: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2180: "</font>");
2181: }
2182: return $token;
2183: }
2184:
2185: # ------------------------------------------------------------ Check in an item
2186:
2187: sub checkin {
2188: my $token=shift;
2189: my $now=time;
2190: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2191: $lonhost=~tr/A-Z/a-z/;
2192: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
2193: $dtoken=~s/\W/\_/g;
2194: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2195: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2196:
2197: unless (($tuname) && ($tudom)) {
2198: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2199: return '';
2200: }
2201:
2202: unless (&allowed('mgr',$tcrsid)) {
2203: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
2204: $env{'user.name'}.' - '.$env{'user.domain'});
2205: return '';
2206: }
2207:
2208: my %infohash=('resource.0.intoken' => $token,
2209: 'resource.0.checkintime' => $now,
2210: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
2211:
2212: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2213: return '';
2214: }
2215:
2216: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2217: &escape('Checkin - '.$token)) ne 'ok') {
2218: return '';
2219: }
2220:
2221: return ($symb,$tuname,$tudom,$tcrsid);
2222: }
2223:
2224: # --------------------------------------------- Set Expire Date for Spreadsheet
2225:
2226: sub expirespread {
2227: my ($uname,$udom,$stype,$usymb)=@_;
2228: my $cid=$env{'request.course.id'};
2229: if ($cid) {
2230: my $now=time;
2231: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2232: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2233: $env{'course.'.$cid.'.num'}.
2234: ':nohist_expirationdates:'.
2235: &escape($key).'='.$now,
2236: $env{'course.'.$cid.'.home'})
2237: }
2238: return 'ok';
2239: }
2240:
2241: # ----------------------------------------------------- Devalidate Spreadsheets
2242:
2243: sub devalidate {
2244: my ($symb,$uname,$udom)=@_;
2245: my $cid=$env{'request.course.id'};
2246: if ($cid) {
2247: # delete the stored spreadsheets for
2248: # - the student level sheet of this user in course's homespace
2249: # - the assessment level sheet for this resource
2250: # for this user in user's homespace
2251: # - current conditional state info
2252: my $key=$uname.':'.$udom.':';
2253: my $status=
2254: &del('nohist_calculatedsheets',
2255: [$key.'studentcalc:'],
2256: $env{'course.'.$cid.'.domain'},
2257: $env{'course.'.$cid.'.num'})
2258: .' '.
2259: &del('nohist_calculatedsheets_'.$cid,
2260: [$key.'assesscalc:'.$symb],$udom,$uname);
2261: unless ($status eq 'ok ok') {
2262: &logthis('Could not devalidate spreadsheet '.
2263: $uname.' at '.$udom.' for '.
2264: $symb.': '.$status);
2265: }
2266: &delenv('user.state.'.$cid);
2267: }
2268: }
2269:
2270: sub get_scalar {
2271: my ($string,$end) = @_;
2272: my $value;
2273: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2274: $value = $1;
2275: } elsif ($$string =~ s/^([^&]*?)&//) {
2276: $value = $1;
2277: }
2278: return &unescape($value);
2279: }
2280:
2281: sub array2str {
2282: my (@array) = @_;
2283: my $result=&arrayref2str(\@array);
2284: $result=~s/^__ARRAY_REF__//;
2285: $result=~s/__END_ARRAY_REF__$//;
2286: return $result;
2287: }
2288:
2289: sub arrayref2str {
2290: my ($arrayref) = @_;
2291: my $result='__ARRAY_REF__';
2292: foreach my $elem (@$arrayref) {
2293: if(ref($elem) eq 'ARRAY') {
2294: $result.=&arrayref2str($elem).'&';
2295: } elsif(ref($elem) eq 'HASH') {
2296: $result.=&hashref2str($elem).'&';
2297: } elsif(ref($elem)) {
2298: #print("Got a ref of ".(ref($elem))." skipping.");
2299: } else {
2300: $result.=&escape($elem).'&';
2301: }
2302: }
2303: $result=~s/\&$//;
2304: $result .= '__END_ARRAY_REF__';
2305: return $result;
2306: }
2307:
2308: sub hash2str {
2309: my (%hash) = @_;
2310: my $result=&hashref2str(\%hash);
2311: $result=~s/^__HASH_REF__//;
2312: $result=~s/__END_HASH_REF__$//;
2313: return $result;
2314: }
2315:
2316: sub hashref2str {
2317: my ($hashref)=@_;
2318: my $result='__HASH_REF__';
2319: foreach my $key (sort(keys(%$hashref))) {
2320: if (ref($key) eq 'ARRAY') {
2321: $result.=&arrayref2str($key).'=';
2322: } elsif (ref($key) eq 'HASH') {
2323: $result.=&hashref2str($key).'=';
2324: } elsif (ref($key)) {
2325: $result.='=';
2326: #print("Got a ref of ".(ref($key))." skipping.");
2327: } else {
2328: if ($key) {$result.=&escape($key).'=';} else { last; }
2329: }
2330:
2331: if(ref($hashref->{$key}) eq 'ARRAY') {
2332: $result.=&arrayref2str($hashref->{$key}).'&';
2333: } elsif(ref($hashref->{$key}) eq 'HASH') {
2334: $result.=&hashref2str($hashref->{$key}).'&';
2335: } elsif(ref($hashref->{$key})) {
2336: $result.='&';
2337: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
2338: } else {
2339: $result.=&escape($hashref->{$key}).'&';
2340: }
2341: }
2342: $result=~s/\&$//;
2343: $result .= '__END_HASH_REF__';
2344: return $result;
2345: }
2346:
2347: sub str2hash {
2348: my ($string)=@_;
2349: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2350: return %$hash;
2351: }
2352:
2353: sub str2hashref {
2354: my ($string) = @_;
2355:
2356: my %hash;
2357:
2358: if($string !~ /^__HASH_REF__/) {
2359: if (! ($string eq '' || !defined($string))) {
2360: $hash{'error'}='Not hash reference';
2361: }
2362: return (\%hash, $string);
2363: }
2364:
2365: $string =~ s/^__HASH_REF__//;
2366:
2367: while($string !~ /^__END_HASH_REF__/) {
2368: #key
2369: my $key='';
2370: if($string =~ /^__HASH_REF__/) {
2371: ($key, $string)=&str2hashref($string);
2372: if(defined($key->{'error'})) {
2373: $hash{'error'}='Bad data';
2374: return (\%hash, $string);
2375: }
2376: } elsif($string =~ /^__ARRAY_REF__/) {
2377: ($key, $string)=&str2arrayref($string);
2378: if($key->[0] eq 'Array reference error') {
2379: $hash{'error'}='Bad data';
2380: return (\%hash, $string);
2381: }
2382: } else {
2383: $string =~ s/^(.*?)=//;
2384: $key=&unescape($1);
2385: }
2386: $string =~ s/^=//;
2387:
2388: #value
2389: my $value='';
2390: if($string =~ /^__HASH_REF__/) {
2391: ($value, $string)=&str2hashref($string);
2392: if(defined($value->{'error'})) {
2393: $hash{'error'}='Bad data';
2394: return (\%hash, $string);
2395: }
2396: } elsif($string =~ /^__ARRAY_REF__/) {
2397: ($value, $string)=&str2arrayref($string);
2398: if($value->[0] eq 'Array reference error') {
2399: $hash{'error'}='Bad data';
2400: return (\%hash, $string);
2401: }
2402: } else {
2403: $value=&get_scalar(\$string,'__END_HASH_REF__');
2404: }
2405: $string =~ s/^&//;
2406:
2407: $hash{$key}=$value;
2408: }
2409:
2410: $string =~ s/^__END_HASH_REF__//;
2411:
2412: return (\%hash, $string);
2413: }
2414:
2415: sub str2array {
2416: my ($string)=@_;
2417: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2418: return @$array;
2419: }
2420:
2421: sub str2arrayref {
2422: my ($string) = @_;
2423: my @array;
2424:
2425: if($string !~ /^__ARRAY_REF__/) {
2426: if (! ($string eq '' || !defined($string))) {
2427: $array[0]='Array reference error';
2428: }
2429: return (\@array, $string);
2430: }
2431:
2432: $string =~ s/^__ARRAY_REF__//;
2433:
2434: while($string !~ /^__END_ARRAY_REF__/) {
2435: my $value='';
2436: if($string =~ /^__HASH_REF__/) {
2437: ($value, $string)=&str2hashref($string);
2438: if(defined($value->{'error'})) {
2439: $array[0] ='Array reference error';
2440: return (\@array, $string);
2441: }
2442: } elsif($string =~ /^__ARRAY_REF__/) {
2443: ($value, $string)=&str2arrayref($string);
2444: if($value->[0] eq 'Array reference error') {
2445: $array[0] ='Array reference error';
2446: return (\@array, $string);
2447: }
2448: } else {
2449: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2450: }
2451: $string =~ s/^&//;
2452:
2453: push(@array, $value);
2454: }
2455:
2456: $string =~ s/^__END_ARRAY_REF__//;
2457:
2458: return (\@array, $string);
2459: }
2460:
2461: # -------------------------------------------------------------------Temp Store
2462:
2463: sub tmpreset {
2464: my ($symb,$namespace,$domain,$stuname) = @_;
2465: if (!$symb) {
2466: $symb=&symbread();
2467: if (!$symb) { $symb= $env{'request.url'}; }
2468: }
2469: $symb=escape($symb);
2470:
2471: if (!$namespace) { $namespace=$env{'request.state'}; }
2472: $namespace=~s/\//\_/g;
2473: $namespace=~s/\W//g;
2474:
2475: if (!$domain) { $domain=$env{'user.domain'}; }
2476: if (!$stuname) { $stuname=$env{'user.name'}; }
2477: if ($domain eq 'public' && $stuname eq 'public') {
2478: $stuname=$ENV{'REMOTE_ADDR'};
2479: }
2480: my $path=$perlvar{'lonDaemons'}.'/tmp';
2481: my %hash;
2482: if (tie(%hash,'GDBM_File',
2483: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2484: &GDBM_WRCREAT(),0640)) {
2485: foreach my $key (keys %hash) {
2486: if ($key=~ /:$symb/) {
2487: delete($hash{$key});
2488: }
2489: }
2490: }
2491: }
2492:
2493: sub tmpstore {
2494: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2495:
2496: if (!$symb) {
2497: $symb=&symbread();
2498: if (!$symb) { $symb= $env{'request.url'}; }
2499: }
2500: $symb=escape($symb);
2501:
2502: if (!$namespace) {
2503: # I don't think we would ever want to store this for a course.
2504: # it seems this will only be used if we don't have a course.
2505: #$namespace=$env{'request.course.id'};
2506: #if (!$namespace) {
2507: $namespace=$env{'request.state'};
2508: #}
2509: }
2510: $namespace=~s/\//\_/g;
2511: $namespace=~s/\W//g;
2512: if (!$domain) { $domain=$env{'user.domain'}; }
2513: if (!$stuname) { $stuname=$env{'user.name'}; }
2514: if ($domain eq 'public' && $stuname eq 'public') {
2515: $stuname=$ENV{'REMOTE_ADDR'};
2516: }
2517: my $now=time;
2518: my %hash;
2519: my $path=$perlvar{'lonDaemons'}.'/tmp';
2520: if (tie(%hash,'GDBM_File',
2521: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2522: &GDBM_WRCREAT(),0640)) {
2523: $hash{"version:$symb"}++;
2524: my $version=$hash{"version:$symb"};
2525: my $allkeys='';
2526: foreach my $key (keys(%$storehash)) {
2527: $allkeys.=$key.':';
2528: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
2529: }
2530: $hash{"$version:$symb:timestamp"}=$now;
2531: $allkeys.='timestamp';
2532: $hash{"$version:keys:$symb"}=$allkeys;
2533: if (untie(%hash)) {
2534: return 'ok';
2535: } else {
2536: return "error:$!";
2537: }
2538: } else {
2539: return "error:$!";
2540: }
2541: }
2542:
2543: # -----------------------------------------------------------------Temp Restore
2544:
2545: sub tmprestore {
2546: my ($symb,$namespace,$domain,$stuname) = @_;
2547:
2548: if (!$symb) {
2549: $symb=&symbread();
2550: if (!$symb) { $symb= $env{'request.url'}; }
2551: }
2552: $symb=escape($symb);
2553:
2554: if (!$namespace) { $namespace=$env{'request.state'}; }
2555:
2556: if (!$domain) { $domain=$env{'user.domain'}; }
2557: if (!$stuname) { $stuname=$env{'user.name'}; }
2558: if ($domain eq 'public' && $stuname eq 'public') {
2559: $stuname=$ENV{'REMOTE_ADDR'};
2560: }
2561: my %returnhash;
2562: $namespace=~s/\//\_/g;
2563: $namespace=~s/\W//g;
2564: my %hash;
2565: my $path=$perlvar{'lonDaemons'}.'/tmp';
2566: if (tie(%hash,'GDBM_File',
2567: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2568: &GDBM_READER(),0640)) {
2569: my $version=$hash{"version:$symb"};
2570: $returnhash{'version'}=$version;
2571: my $scope;
2572: for ($scope=1;$scope<=$version;$scope++) {
2573: my $vkeys=$hash{"$scope:keys:$symb"};
2574: my @keys=split(/:/,$vkeys);
2575: my $key;
2576: $returnhash{"$scope:keys"}=$vkeys;
2577: foreach $key (@keys) {
2578: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2579: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2580: }
2581: }
2582: if (!(untie(%hash))) {
2583: return "error:$!";
2584: }
2585: } else {
2586: return "error:$!";
2587: }
2588: return %returnhash;
2589: }
2590:
2591: # ----------------------------------------------------------------------- Store
2592:
2593: sub store {
2594: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2595: my $home='';
2596:
2597: if ($stuname) { $home=&homeserver($stuname,$domain); }
2598:
2599: $symb=&symbclean($symb);
2600: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2601:
2602: if (!$domain) { $domain=$env{'user.domain'}; }
2603: if (!$stuname) { $stuname=$env{'user.name'}; }
2604:
2605: &devalidate($symb,$stuname,$domain);
2606:
2607: $symb=escape($symb);
2608: if (!$namespace) {
2609: unless ($namespace=$env{'request.course.id'}) {
2610: return '';
2611: }
2612: }
2613: if (!$home) { $home=$env{'user.home'}; }
2614:
2615: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2616: $$storehash{'host'}=$perlvar{'lonHostID'};
2617:
2618: my $namevalue='';
2619: foreach my $key (keys(%$storehash)) {
2620: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2621: }
2622: $namevalue=~s/\&$//;
2623: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2624: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2625: }
2626:
2627: # -------------------------------------------------------------- Critical Store
2628:
2629: sub cstore {
2630: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2631: my $home='';
2632:
2633: if ($stuname) { $home=&homeserver($stuname,$domain); }
2634:
2635: $symb=&symbclean($symb);
2636: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2637:
2638: if (!$domain) { $domain=$env{'user.domain'}; }
2639: if (!$stuname) { $stuname=$env{'user.name'}; }
2640:
2641: &devalidate($symb,$stuname,$domain);
2642:
2643: $symb=escape($symb);
2644: if (!$namespace) {
2645: unless ($namespace=$env{'request.course.id'}) {
2646: return '';
2647: }
2648: }
2649: if (!$home) { $home=$env{'user.home'}; }
2650:
2651: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2652: $$storehash{'host'}=$perlvar{'lonHostID'};
2653:
2654: my $namevalue='';
2655: foreach my $key (keys(%$storehash)) {
2656: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2657: }
2658: $namevalue=~s/\&$//;
2659: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2660: return critical
2661: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2662: }
2663:
2664: # --------------------------------------------------------------------- Restore
2665:
2666: sub restore {
2667: my ($symb,$namespace,$domain,$stuname) = @_;
2668: my $home='';
2669:
2670: if ($stuname) { $home=&homeserver($stuname,$domain); }
2671:
2672: if (!$symb) {
2673: unless ($symb=escape(&symbread())) { return ''; }
2674: } else {
2675: $symb=&escape(&symbclean($symb));
2676: }
2677: if (!$namespace) {
2678: unless ($namespace=$env{'request.course.id'}) {
2679: return '';
2680: }
2681: }
2682: if (!$domain) { $domain=$env{'user.domain'}; }
2683: if (!$stuname) { $stuname=$env{'user.name'}; }
2684: if (!$home) { $home=$env{'user.home'}; }
2685: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2686:
2687: my %returnhash=();
2688: foreach my $line (split(/\&/,$answer)) {
2689: my ($name,$value)=split(/\=/,$line);
2690: $returnhash{&unescape($name)}=&thaw_unescape($value);
2691: }
2692: my $version;
2693: for ($version=1;$version<=$returnhash{'version'};$version++) {
2694: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2695: $returnhash{$item}=$returnhash{$version.':'.$item};
2696: }
2697: }
2698: return %returnhash;
2699: }
2700:
2701: # ---------------------------------------------------------- Course Description
2702:
2703: sub coursedescription {
2704: my ($courseid,$args)=@_;
2705: $courseid=~s/^\///;
2706: $courseid=~s/\_/\//g;
2707: my ($cdomain,$cnum)=split(/\//,$courseid);
2708: my $chome=&homeserver($cnum,$cdomain);
2709: my $normalid=$cdomain.'_'.$cnum;
2710: # need to always cache even if we get errors otherwise we keep
2711: # trying and trying and trying to get the course description.
2712: my %envhash=();
2713: my %returnhash=();
2714:
2715: my $expiretime=600;
2716: if ($env{'request.course.id'} eq $normalid) {
2717: $expiretime=120;
2718: }
2719:
2720: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2721: if (!$args->{'freshen_cache'}
2722: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2723: foreach my $key (keys(%env)) {
2724: next if ($key !~ /^\Q$prefix\E(.*)/);
2725: my ($setting) = $1;
2726: $returnhash{$setting} = $env{$key};
2727: }
2728: return %returnhash;
2729: }
2730:
2731: # get the data agin
2732: if (!$args->{'one_time'}) {
2733: $envhash{'course.'.$normalid.'.last_cache'}=time;
2734: }
2735:
2736: if ($chome ne 'no_host') {
2737: %returnhash=&dump('environment',$cdomain,$cnum);
2738: if (!exists($returnhash{'con_lost'})) {
2739: $returnhash{'home'}= $chome;
2740: $returnhash{'domain'} = $cdomain;
2741: $returnhash{'num'} = $cnum;
2742: if (!defined($returnhash{'type'})) {
2743: $returnhash{'type'} = 'Course';
2744: }
2745: while (my ($name,$value) = each %returnhash) {
2746: $envhash{'course.'.$normalid.'.'.$name}=$value;
2747: }
2748: $returnhash{'url'}=&clutter($returnhash{'url'});
2749: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2750: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2751: $envhash{'course.'.$normalid.'.home'}=$chome;
2752: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2753: $envhash{'course.'.$normalid.'.num'}=$cnum;
2754: }
2755: }
2756: if (!$args->{'one_time'}) {
2757: &appenv(%envhash);
2758: }
2759: return %returnhash;
2760: }
2761:
2762: # -------------------------------------------------See if a user is privileged
2763:
2764: sub privileged {
2765: my ($username,$domain)=@_;
2766: my $rolesdump=&reply("dump:$domain:$username:roles",
2767: &homeserver($username,$domain));
2768: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2769: my $now=time;
2770: if ($rolesdump ne '') {
2771: foreach my $entry (split(/&/,$rolesdump)) {
2772: if ($entry!~/^rolesdef_/) {
2773: my ($area,$role)=split(/=/,$entry);
2774: $area=~s/\_\w\w$//;
2775: my ($trole,$tend,$tstart)=split(/_/,$role);
2776: if (($trole eq 'dc') || ($trole eq 'su')) {
2777: my $active=1;
2778: if ($tend) {
2779: if ($tend<$now) { $active=0; }
2780: }
2781: if ($tstart) {
2782: if ($tstart>$now) { $active=0; }
2783: }
2784: if ($active) { return 1; }
2785: }
2786: }
2787: }
2788: }
2789: return 0;
2790: }
2791:
2792: # -------------------------------------------------------- Get user privileges
2793:
2794: sub rolesinit {
2795: my ($domain,$username,$authhost)=@_;
2796: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
2797: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
2798: my %allroles=();
2799: my %allgroups=();
2800: my $now=time;
2801: my %userroles = ('user.login.time' => $now);
2802: my $group_privs;
2803:
2804: if ($rolesdump ne '') {
2805: foreach my $entry (split(/&/,$rolesdump)) {
2806: if ($entry!~/^rolesdef_/) {
2807: my ($area,$role)=split(/=/,$entry);
2808: $area=~s/\_\w\w$//;
2809: my ($trole,$tend,$tstart,$group_privs);
2810: if ($role=~/^cr/) {
2811: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
2812: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
2813: ($tend,$tstart)=split('_',$trest);
2814: } else {
2815: $trole=$role;
2816: }
2817: } elsif ($role =~ m|^gr/|) {
2818: ($trole,$tend,$tstart) = split(/_/,$role);
2819: ($trole,$group_privs) = split(/\//,$trole);
2820: $group_privs = &unescape($group_privs);
2821: } else {
2822: ($trole,$tend,$tstart)=split(/_/,$role);
2823: }
2824: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2825: $username);
2826: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
2827: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2828: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2829: if (($area ne '') && ($trole ne '')) {
2830: my $spec=$trole.'.'.$area;
2831: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2832: if ($trole =~ /^cr\//) {
2833: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2834: } elsif ($trole eq 'gr') {
2835: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
2836: } else {
2837: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2838: }
2839: }
2840: }
2841: }
2842: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2843: $userroles{'user.adv'} = $adv;
2844: $userroles{'user.author'} = $author;
2845: $env{'user.adv'}=$adv;
2846: }
2847: return \%userroles;
2848: }
2849:
2850: sub set_arearole {
2851: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2852: # log the associated role with the area
2853: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2854: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
2855: }
2856:
2857: sub custom_roleprivs {
2858: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2859: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2860: my $homsvr=homeserver($rauthor,$rdomain);
2861: if ($hostname{$homsvr} ne '') {
2862: my ($rdummy,$roledef)=
2863: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2864: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2865: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2866: if (defined($syspriv)) {
2867: $$allroles{'cm./'}.=':'.$syspriv;
2868: $$allroles{$spec.'./'}.=':'.$syspriv;
2869: }
2870: if ($tdomain ne '') {
2871: if (defined($dompriv)) {
2872: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2873: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2874: }
2875: if (($trest ne '') && (defined($coursepriv))) {
2876: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2877: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2878: }
2879: }
2880: }
2881: }
2882: }
2883:
2884: sub group_roleprivs {
2885: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
2886: my $access = 1;
2887: my $now = time;
2888: if (($tend!=0) && ($tend<$now)) { $access = 0; }
2889: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
2890: if ($access) {
2891: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
2892: $$allgroups{$course}{$group} .=':'.$group_privs;
2893: }
2894: }
2895:
2896: sub standard_roleprivs {
2897: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2898: if (defined($pr{$trole.':s'})) {
2899: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2900: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2901: }
2902: if ($tdomain ne '') {
2903: if (defined($pr{$trole.':d'})) {
2904: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2905: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2906: }
2907: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2908: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2909: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2910: }
2911: }
2912: }
2913:
2914: sub set_userprivs {
2915: my ($userroles,$allroles,$allgroups) = @_;
2916: my $author=0;
2917: my $adv=0;
2918: my %grouproles = ();
2919: if (keys(%{$allgroups}) > 0) {
2920: foreach my $role (keys %{$allroles}) {
2921: my ($trole,$area,$sec,$extendedarea);
2922: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
2923: $trole = $1;
2924: $area = $2;
2925: $sec = $3;
2926: $extendedarea = $area.$sec;
2927: if (exists($$allgroups{$area})) {
2928: foreach my $group (keys(%{$$allgroups{$area}})) {
2929: my $spec = $trole.'.'.$extendedarea;
2930: $grouproles{$spec.'.'.$area.'/'.$group} =
2931: $$allgroups{$area}{$group};
2932: }
2933: }
2934: }
2935: }
2936: }
2937: foreach my $group (keys(%grouproles)) {
2938: $$allroles{$group} = $grouproles{$group};
2939: }
2940: foreach my $role (keys(%{$allroles})) {
2941: my %thesepriv;
2942: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
2943: foreach my $item (split(/:/,$$allroles{$role})) {
2944: if ($item ne '') {
2945: my ($privilege,$restrictions)=split(/&/,$item);
2946: if ($restrictions eq '') {
2947: $thesepriv{$privilege}='F';
2948: } elsif ($thesepriv{$privilege} ne 'F') {
2949: $thesepriv{$privilege}.=$restrictions;
2950: }
2951: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2952: }
2953: }
2954: my $thesestr='';
2955: foreach my $priv (keys(%thesepriv)) {
2956: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
2957: }
2958: $userroles->{'user.priv.'.$role} = $thesestr;
2959: }
2960: return ($author,$adv);
2961: }
2962:
2963: # --------------------------------------------------------------- get interface
2964:
2965: sub get {
2966: my ($namespace,$storearr,$udomain,$uname)=@_;
2967: my $items='';
2968: foreach my $item (@$storearr) {
2969: $items.=&escape($item).'&';
2970: }
2971: $items=~s/\&$//;
2972: if (!$udomain) { $udomain=$env{'user.domain'}; }
2973: if (!$uname) { $uname=$env{'user.name'}; }
2974: my $uhome=&homeserver($uname,$udomain);
2975:
2976: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
2977: my @pairs=split(/\&/,$rep);
2978: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2979: return @pairs;
2980: }
2981: my %returnhash=();
2982: my $i=0;
2983: foreach my $item (@$storearr) {
2984: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2985: $i++;
2986: }
2987: return %returnhash;
2988: }
2989:
2990: # --------------------------------------------------------------- del interface
2991:
2992: sub del {
2993: my ($namespace,$storearr,$udomain,$uname)=@_;
2994: my $items='';
2995: foreach my $item (@$storearr) {
2996: $items.=&escape($item).'&';
2997: }
2998: $items=~s/\&$//;
2999: if (!$udomain) { $udomain=$env{'user.domain'}; }
3000: if (!$uname) { $uname=$env{'user.name'}; }
3001: my $uhome=&homeserver($uname,$udomain);
3002:
3003: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3004: }
3005:
3006: # -------------------------------------------------------------- dump interface
3007:
3008: sub dump {
3009: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3010: if (!$udomain) { $udomain=$env{'user.domain'}; }
3011: if (!$uname) { $uname=$env{'user.name'}; }
3012: my $uhome=&homeserver($uname,$udomain);
3013: if ($regexp) {
3014: $regexp=&escape($regexp);
3015: } else {
3016: $regexp='.';
3017: }
3018: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3019: my @pairs=split(/\&/,$rep);
3020: my %returnhash=();
3021: foreach my $item (@pairs) {
3022: my ($key,$value)=split(/=/,$item,2);
3023: $key = &unescape($key);
3024: next if ($key =~ /^error: 2 /);
3025: $returnhash{$key}=&thaw_unescape($value);
3026: }
3027: return %returnhash;
3028: }
3029:
3030: # --------------------------------------------------------- dumpstore interface
3031:
3032: sub dumpstore {
3033: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3034: return &dump($namespace,$udomain,$uname,$regexp,$range);
3035: }
3036:
3037: # -------------------------------------------------------------- keys interface
3038:
3039: sub getkeys {
3040: my ($namespace,$udomain,$uname)=@_;
3041: if (!$udomain) { $udomain=$env{'user.domain'}; }
3042: if (!$uname) { $uname=$env{'user.name'}; }
3043: my $uhome=&homeserver($uname,$udomain);
3044: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3045: my @keyarray=();
3046: foreach my $key (split(/\&/,$rep)) {
3047: next if ($key =~ /^error: 2 /);
3048: push(@keyarray,&unescape($key));
3049: }
3050: return @keyarray;
3051: }
3052:
3053: # --------------------------------------------------------------- currentdump
3054: sub currentdump {
3055: my ($courseid,$sdom,$sname)=@_;
3056: $courseid = $env{'request.course.id'} if (! defined($courseid));
3057: $sdom = $env{'user.domain'} if (! defined($sdom));
3058: $sname = $env{'user.name'} if (! defined($sname));
3059: my $uhome = &homeserver($sname,$sdom);
3060: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3061: return if ($rep =~ /^(error:|no_such_host)/);
3062: #
3063: my %returnhash=();
3064: #
3065: if ($rep eq "unknown_cmd") {
3066: # an old lond will not know currentdump
3067: # Do a dump and make it look like a currentdump
3068: my @tmp = &dump($courseid,$sdom,$sname,'.');
3069: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3070: my %hash = @tmp;
3071: @tmp=();
3072: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3073: } else {
3074: my @pairs=split(/\&/,$rep);
3075: foreach my $pair (@pairs) {
3076: my ($key,$value)=split(/=/,$pair,2);
3077: my ($symb,$param) = split(/:/,$key);
3078: $returnhash{&unescape($symb)}->{&unescape($param)} =
3079: &thaw_unescape($value);
3080: }
3081: }
3082: return %returnhash;
3083: }
3084:
3085: sub convert_dump_to_currentdump{
3086: my %hash = %{shift()};
3087: my %returnhash;
3088: # Code ripped from lond, essentially. The only difference
3089: # here is the unescaping done by lonnet::dump(). Conceivably
3090: # we might run in to problems with parameter names =~ /^v\./
3091: while (my ($key,$value) = each(%hash)) {
3092: my ($v,$symb,$param) = split(/:/,$key);
3093: next if ($v eq 'version' || $symb eq 'keys');
3094: next if (exists($returnhash{$symb}) &&
3095: exists($returnhash{$symb}->{$param}) &&
3096: $returnhash{$symb}->{'v.'.$param} > $v);
3097: $returnhash{$symb}->{$param}=$value;
3098: $returnhash{$symb}->{'v.'.$param}=$v;
3099: }
3100: #
3101: # Remove all of the keys in the hashes which keep track of
3102: # the version of the parameter.
3103: while (my ($symb,$param_hash) = each(%returnhash)) {
3104: # use a foreach because we are going to delete from the hash.
3105: foreach my $key (keys(%$param_hash)) {
3106: delete($param_hash->{$key}) if ($key =~ /^v\./);
3107: }
3108: }
3109: return \%returnhash;
3110: }
3111:
3112: # ------------------------------------------------------ critical inc interface
3113:
3114: sub cinc {
3115: return &inc(@_,'critical');
3116: }
3117:
3118: # --------------------------------------------------------------- inc interface
3119:
3120: sub inc {
3121: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3122: if (!$udomain) { $udomain=$env{'user.domain'}; }
3123: if (!$uname) { $uname=$env{'user.name'}; }
3124: my $uhome=&homeserver($uname,$udomain);
3125: my $items='';
3126: if (! ref($store)) {
3127: # got a single value, so use that instead
3128: $items = &escape($store).'=&';
3129: } elsif (ref($store) eq 'SCALAR') {
3130: $items = &escape($$store).'=&';
3131: } elsif (ref($store) eq 'ARRAY') {
3132: $items = join('=&',map {&escape($_);} @{$store});
3133: } elsif (ref($store) eq 'HASH') {
3134: while (my($key,$value) = each(%{$store})) {
3135: $items.= &escape($key).'='.&escape($value).'&';
3136: }
3137: }
3138: $items=~s/\&$//;
3139: if ($critical) {
3140: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3141: } else {
3142: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3143: }
3144: }
3145:
3146: # --------------------------------------------------------------- put interface
3147:
3148: sub put {
3149: my ($namespace,$storehash,$udomain,$uname)=@_;
3150: if (!$udomain) { $udomain=$env{'user.domain'}; }
3151: if (!$uname) { $uname=$env{'user.name'}; }
3152: my $uhome=&homeserver($uname,$udomain);
3153: my $items='';
3154: foreach my $item (keys(%$storehash)) {
3155: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3156: }
3157: $items=~s/\&$//;
3158: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3159: }
3160:
3161: # ------------------------------------------------------------ newput interface
3162:
3163: sub newput {
3164: my ($namespace,$storehash,$udomain,$uname)=@_;
3165: if (!$udomain) { $udomain=$env{'user.domain'}; }
3166: if (!$uname) { $uname=$env{'user.name'}; }
3167: my $uhome=&homeserver($uname,$udomain);
3168: my $items='';
3169: foreach my $key (keys(%$storehash)) {
3170: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3171: }
3172: $items=~s/\&$//;
3173: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3174: }
3175:
3176: # --------------------------------------------------------- putstore interface
3177:
3178: sub putstore {
3179: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3180: if (!$udomain) { $udomain=$env{'user.domain'}; }
3181: if (!$uname) { $uname=$env{'user.name'}; }
3182: my $uhome=&homeserver($uname,$udomain);
3183: my $items='';
3184: foreach my $key (keys(%$storehash)) {
3185: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3186: }
3187: $items=~s/\&$//;
3188: my $esc_symb=&escape($symb);
3189: my $esc_v=&escape($version);
3190: my $reply =
3191: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3192: $uhome);
3193: if ($reply eq 'unknown_cmd') {
3194: # gfall back to way things use to be done
3195: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3196: $uname);
3197: }
3198: return $reply;
3199: }
3200:
3201: sub old_putstore {
3202: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3203: if (!$udomain) { $udomain=$env{'user.domain'}; }
3204: if (!$uname) { $uname=$env{'user.name'}; }
3205: my $uhome=&homeserver($uname,$udomain);
3206: my %newstorehash;
3207: foreach my $item (keys(%$storehash)) {
3208: my $key = $version.':'.&escape($symb).':'.$item;
3209: $newstorehash{$key} = $storehash->{$item};
3210: }
3211: my $items='';
3212: my %allitems = ();
3213: foreach my $item (keys(%newstorehash)) {
3214: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3215: my $key = $1.':keys:'.$2;
3216: $allitems{$key} .= $3.':';
3217: }
3218: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
3219: }
3220: foreach my $item (keys(%allitems)) {
3221: $allitems{$item} =~ s/\:$//;
3222: $items.= $item.'='.$allitems{$item}.'&';
3223: }
3224: $items=~s/\&$//;
3225: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3226: }
3227:
3228: # ------------------------------------------------------ critical put interface
3229:
3230: sub cput {
3231: my ($namespace,$storehash,$udomain,$uname)=@_;
3232: if (!$udomain) { $udomain=$env{'user.domain'}; }
3233: if (!$uname) { $uname=$env{'user.name'}; }
3234: my $uhome=&homeserver($uname,$udomain);
3235: my $items='';
3236: foreach my $item (keys(%$storehash)) {
3237: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3238: }
3239: $items=~s/\&$//;
3240: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3241: }
3242:
3243: # -------------------------------------------------------------- eget interface
3244:
3245: sub eget {
3246: my ($namespace,$storearr,$udomain,$uname)=@_;
3247: my $items='';
3248: foreach my $item (@$storearr) {
3249: $items.=&escape($item).'&';
3250: }
3251: $items=~s/\&$//;
3252: if (!$udomain) { $udomain=$env{'user.domain'}; }
3253: if (!$uname) { $uname=$env{'user.name'}; }
3254: my $uhome=&homeserver($uname,$udomain);
3255: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3256: my @pairs=split(/\&/,$rep);
3257: my %returnhash=();
3258: my $i=0;
3259: foreach my $item (@$storearr) {
3260: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3261: $i++;
3262: }
3263: return %returnhash;
3264: }
3265:
3266: # ------------------------------------------------------------ tmpput interface
3267: sub tmpput {
3268: my ($storehash,$server,$context)=@_;
3269: my $items='';
3270: foreach my $item (keys(%$storehash)) {
3271: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3272: }
3273: $items=~s/\&$//;
3274: if (defined($context)) {
3275: $items .= ':'.&escape($context);
3276: }
3277: return &reply("tmpput:$items",$server);
3278: }
3279:
3280: # ------------------------------------------------------------ tmpget interface
3281: sub tmpget {
3282: my ($token,$server)=@_;
3283: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3284: my $rep=&reply("tmpget:$token",$server);
3285: my %returnhash;
3286: foreach my $item (split(/\&/,$rep)) {
3287: my ($key,$value)=split(/=/,$item);
3288: $returnhash{&unescape($key)}=&thaw_unescape($value);
3289: }
3290: return %returnhash;
3291: }
3292:
3293: # ------------------------------------------------------------ tmpget interface
3294: sub tmpdel {
3295: my ($token,$server)=@_;
3296: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3297: return &reply("tmpdel:$token",$server);
3298: }
3299:
3300: # -------------------------------------------------- portfolio access checking
3301:
3302: sub portfolio_access {
3303: my ($requrl) = @_;
3304: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3305: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3306: if ($result) {
3307: my %setters;
3308: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3309: my ($startblock,$endblock) =
3310: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3311: if ($startblock && $endblock) {
3312: return 'B';
3313: }
3314: } else {
3315: my ($startblock,$endblock) =
3316: &Apache::loncommon::blockcheck(\%setters,'port');
3317: if ($startblock && $endblock) {
3318: return 'B';
3319: }
3320: }
3321: }
3322: if ($result eq 'ok') {
3323: return 'F';
3324: } elsif ($result =~ /^[^:]+:guest_/) {
3325: return 'A';
3326: }
3327: return '';
3328: }
3329:
3330: sub get_portfolio_access {
3331: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3332:
3333: if (!ref($access_hash)) {
3334: my $current_perms = &get_portfile_permissions($udom,$unum);
3335: my %access_controls = &get_access_controls($current_perms,$group,
3336: $file_name);
3337: $access_hash = $access_controls{$file_name};
3338: }
3339:
3340: my ($public,$guest,@domains,@users,@courses,@groups);
3341: my $now = time;
3342: if (ref($access_hash) eq 'HASH') {
3343: foreach my $key (keys(%{$access_hash})) {
3344: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3345: if ($start > $now) {
3346: next;
3347: }
3348: if ($end && $end<$now) {
3349: next;
3350: }
3351: if ($scope eq 'public') {
3352: $public = $key;
3353: last;
3354: } elsif ($scope eq 'guest') {
3355: $guest = $key;
3356: } elsif ($scope eq 'domains') {
3357: push(@domains,$key);
3358: } elsif ($scope eq 'users') {
3359: push(@users,$key);
3360: } elsif ($scope eq 'course') {
3361: push(@courses,$key);
3362: } elsif ($scope eq 'group') {
3363: push(@groups,$key);
3364: }
3365: }
3366: if ($public) {
3367: return 'ok';
3368: }
3369: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3370: if ($guest) {
3371: return $guest;
3372: }
3373: } else {
3374: if (@domains > 0) {
3375: foreach my $domkey (@domains) {
3376: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3377: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3378: return 'ok';
3379: }
3380: }
3381: }
3382: }
3383: if (@users > 0) {
3384: foreach my $userkey (@users) {
3385: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3386: return 'ok';
3387: }
3388: }
3389: }
3390: my %roleshash;
3391: my @courses_and_groups = @courses;
3392: push(@courses_and_groups,@groups);
3393: if (@courses_and_groups > 0) {
3394: my (%allgroups,%allroles);
3395: my ($start,$end,$role,$sec,$group);
3396: foreach my $envkey (%env) {
3397: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
3398: my $cid = $2.'_'.$3;
3399: if ($1 eq 'gr') {
3400: $group = $4;
3401: $allgroups{$cid}{$group} = $env{$envkey};
3402: } else {
3403: if ($4 eq '') {
3404: $sec = 'none';
3405: } else {
3406: $sec = $4;
3407: }
3408: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3409: }
3410: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
3411: my $cid = $2.'_'.$3;
3412: if ($4 eq '') {
3413: $sec = 'none';
3414: } else {
3415: $sec = $4;
3416: }
3417: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3418: }
3419: }
3420: if (keys(%allroles) == 0) {
3421: return;
3422: }
3423: foreach my $key (@courses_and_groups) {
3424: my %content = %{$$access_hash{$key}};
3425: my $cnum = $content{'number'};
3426: my $cdom = $content{'domain'};
3427: my $cid = $cdom.'_'.$cnum;
3428: if (!exists($allroles{$cid})) {
3429: next;
3430: }
3431: foreach my $role_id (keys(%{$content{'roles'}})) {
3432: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3433: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3434: my @status = @{$content{'roles'}{$role_id}{'access'}};
3435: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3436: foreach my $role (keys(%{$allroles{$cid}})) {
3437: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3438: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3439: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3440: if (grep/^all$/,@sections) {
3441: return 'ok';
3442: } else {
3443: if (grep/^$sec$/,@sections) {
3444: return 'ok';
3445: }
3446: }
3447: }
3448: }
3449: if (keys(%{$allgroups{$cid}}) == 0) {
3450: if (grep/^none$/,@groups) {
3451: return 'ok';
3452: }
3453: } else {
3454: if (grep/^all$/,@groups) {
3455: return 'ok';
3456: }
3457: foreach my $group (keys(%{$allgroups{$cid}})) {
3458: if (grep/^$group$/,@groups) {
3459: return 'ok';
3460: }
3461: }
3462: }
3463: }
3464: }
3465: }
3466: }
3467: }
3468: if ($guest) {
3469: return $guest;
3470: }
3471: }
3472: }
3473: return;
3474: }
3475:
3476: sub course_group_datechecker {
3477: my ($dates,$now,$status) = @_;
3478: my ($start,$end) = split(/\./,$dates);
3479: if (!$start && !$end) {
3480: return 'ok';
3481: }
3482: if (grep/^active$/,@{$status}) {
3483: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3484: return 'ok';
3485: }
3486: }
3487: if (grep/^previous$/,@{$status}) {
3488: if ($end > $now ) {
3489: return 'ok';
3490: }
3491: }
3492: if (grep/^future$/,@{$status}) {
3493: if ($start > $now) {
3494: return 'ok';
3495: }
3496: }
3497: return;
3498: }
3499:
3500: sub parse_portfolio_url {
3501: my ($url) = @_;
3502:
3503: my ($type,$udom,$unum,$group,$file_name);
3504:
3505: if ($url =~ m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
3506: $type = 1;
3507: $udom = $1;
3508: $unum = $2;
3509: $file_name = $3;
3510: } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
3511: $type = 2;
3512: $udom = $1;
3513: $unum = $2;
3514: $group = $3;
3515: $file_name = $3.'/'.$4;
3516: }
3517: if (wantarray) {
3518: return ($type,$udom,$unum,$file_name,$group);
3519: }
3520: return $type;
3521: }
3522:
3523: sub is_portfolio_url {
3524: my ($url) = @_;
3525: return scalar(&parse_portfolio_url($url));
3526: }
3527:
3528: sub is_portfolio_file {
3529: my ($file) = @_;
3530: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w\/portfolio/)) {
3531: return 1;
3532: }
3533: return;
3534: }
3535:
3536:
3537: # ---------------------------------------------- Custom access rule evaluation
3538:
3539: sub customaccess {
3540: my ($priv,$uri)=@_;
3541: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
3542: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
3543: $udom = &LONCAPA::clean_domain($udom);
3544: $ucrs = &LONCAPA::clean_username($ucrs);
3545: my $access=0;
3546: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3547: my ($effect,$realm,$role)=split(/\:/,$right);
3548: if ($role) {
3549: if ($role ne $urole) { next; }
3550: }
3551: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3552: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
3553: if ($tdom) {
3554: if ($tdom ne $udom) { next; }
3555: }
3556: if ($tcrs) {
3557: if ($tcrs ne $ucrs) { next; }
3558: }
3559: if ($tsec) {
3560: if ($tsec ne $usec) { next; }
3561: }
3562: $access=($effect eq 'allow');
3563: last;
3564: }
3565: if ($realm eq '' && $role eq '') {
3566: $access=($effect eq 'allow');
3567: }
3568: }
3569: return $access;
3570: }
3571:
3572: # ------------------------------------------------- Check for a user privilege
3573:
3574: sub allowed {
3575: my ($priv,$uri,$symb,$role)=@_;
3576: my $ver_orguri=$uri;
3577: $uri=&deversion($uri);
3578: my $orguri=$uri;
3579: $uri=&declutter($uri);
3580:
3581: if ($priv eq 'evb') {
3582: # Evade communication block restrictions for specified role in a course
3583: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3584: return $1;
3585: } else {
3586: return;
3587: }
3588: }
3589:
3590: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3591: # Free bre access to adm and meta resources
3592: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
3593: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3594: && ($priv eq 'bre')) {
3595: return 'F';
3596: }
3597:
3598: # Free bre access to user's own portfolio contents
3599: my ($space,$domain,$name,@dir)=split('/',$uri);
3600: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3601: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
3602: my %setters;
3603: my ($startblock,$endblock) =
3604: &Apache::loncommon::blockcheck(\%setters,'port');
3605: if ($startblock && $endblock) {
3606: return 'B';
3607: } else {
3608: return 'F';
3609: }
3610: }
3611:
3612: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
3613: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3614: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3615: if (exists($env{'request.course.id'})) {
3616: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3617: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3618: if (($domain eq $cdom) && ($name eq $cnum)) {
3619: my $courseprivid=$env{'request.course.id'};
3620: $courseprivid=~s/\_/\//;
3621: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3622: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3623: return $1;
3624: } else {
3625: if ($env{'request.course.sec'}) {
3626: $courseprivid.='/'.$env{'request.course.sec'};
3627: }
3628: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3629: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3630: return $2;
3631: }
3632: }
3633: }
3634: }
3635: }
3636:
3637: # Free bre to public access
3638:
3639: if ($priv eq 'bre') {
3640: my $copyright=&metadata($uri,'copyright');
3641: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3642: return 'F';
3643: }
3644: if ($copyright eq 'priv') {
3645: $uri=~/([^\/]+)\/([^\/]+)\//;
3646: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3647: return '';
3648: }
3649: }
3650: if ($copyright eq 'domain') {
3651: $uri=~/([^\/]+)\/([^\/]+)\//;
3652: unless (($env{'user.domain'} eq $1) ||
3653: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3654: return '';
3655: }
3656: }
3657: if ($env{'request.role'}=~ /li\.\//) {
3658: # Library role, so allow browsing of resources in this domain.
3659: return 'F';
3660: }
3661: if ($copyright eq 'custom') {
3662: unless (&customaccess($priv,$uri)) { return ''; }
3663: }
3664: }
3665: # Domain coordinator is trying to create a course
3666: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3667: # uri is the requested domain in this case.
3668: # comparison to 'request.role.domain' shows if the user has selected
3669: # a role of dc for the domain in question.
3670: return 'F' if ($uri eq $env{'request.role.domain'});
3671: }
3672:
3673: my $thisallowed='';
3674: my $statecond=0;
3675: my $courseprivid='';
3676:
3677: # Course
3678:
3679: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3680: $thisallowed.=$1;
3681: }
3682:
3683: # Domain
3684:
3685: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3686: =~/\Q$priv\E\&([^\:]*)/) {
3687: $thisallowed.=$1;
3688: }
3689:
3690: # Course: uri itself is a course
3691: my $courseuri=$uri;
3692: $courseuri=~s/\_(\d)/\/$1/;
3693: $courseuri=~s/^([^\/])/\/$1/;
3694:
3695: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3696: =~/\Q$priv\E\&([^\:]*)/) {
3697: $thisallowed.=$1;
3698: }
3699:
3700: # URI is an uploaded document for this course, default permissions don't matter
3701: # not allowing 'edit' access (editupload) to uploaded course docs
3702: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3703: $thisallowed='';
3704: my ($match)=&is_on_map($uri);
3705: if ($match) {
3706: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3707: =~/\Q$priv\E\&([^\:]*)/) {
3708: $thisallowed.=$1;
3709: }
3710: } else {
3711: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3712: if ($refuri) {
3713: if ($refuri =~ m|^/adm/|) {
3714: $thisallowed='F';
3715: } else {
3716: $refuri=&declutter($refuri);
3717: my ($match) = &is_on_map($refuri);
3718: if ($match) {
3719: $thisallowed='F';
3720: }
3721: }
3722: }
3723: }
3724: }
3725:
3726: if ($priv eq 'bre'
3727: && $thisallowed ne 'F'
3728: && $thisallowed ne '2'
3729: && &is_portfolio_url($uri)) {
3730: $thisallowed = &portfolio_access($uri);
3731: }
3732:
3733: # Full access at system, domain or course-wide level? Exit.
3734:
3735: if ($thisallowed=~/F/) {
3736: return 'F';
3737: }
3738:
3739: # If this is generating or modifying users, exit with special codes
3740:
3741: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3742: if (($priv eq 'cca') || ($priv eq 'caa')) {
3743: my ($audom,$auname)=split('/',$uri);
3744: # no author name given, so this just checks on the general right to make a co-author in this domain
3745: unless ($auname) { return $thisallowed; }
3746: # an author name is given, so we are about to actually make a co-author for a certain account
3747: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3748: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3749: ($audom ne $env{'request.role.domain'}))) { return ''; }
3750: }
3751: return $thisallowed;
3752: }
3753: #
3754: # Gathered so far: system, domain and course wide privileges
3755: #
3756: # Course: See if uri or referer is an individual resource that is part of
3757: # the course
3758:
3759: if ($env{'request.course.id'}) {
3760:
3761: $courseprivid=$env{'request.course.id'};
3762: if ($env{'request.course.sec'}) {
3763: $courseprivid.='/'.$env{'request.course.sec'};
3764: }
3765: $courseprivid=~s/\_/\//;
3766: my $checkreferer=1;
3767: my ($match,$cond)=&is_on_map($uri);
3768: if ($match) {
3769: $statecond=$cond;
3770: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3771: =~/\Q$priv\E\&([^\:]*)/) {
3772: $thisallowed.=$1;
3773: $checkreferer=0;
3774: }
3775: }
3776:
3777: if ($checkreferer) {
3778: my $refuri=$env{'httpref.'.$orguri};
3779: unless ($refuri) {
3780: foreach my $key (keys(%env)) {
3781: if ($key=~/^httpref\..*\*/) {
3782: my $pattern=$key;
3783: $pattern=~s/^httpref\.\/res\///;
3784: $pattern=~s/\*/\[\^\/\]\+/g;
3785: $pattern=~s/\//\\\//g;
3786: if ($orguri=~/$pattern/) {
3787: $refuri=$env{$key};
3788: }
3789: }
3790: }
3791: }
3792:
3793: if ($refuri) {
3794: $refuri=&declutter($refuri);
3795: my ($match,$cond)=&is_on_map($refuri);
3796: if ($match) {
3797: my $refstatecond=$cond;
3798: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3799: =~/\Q$priv\E\&([^\:]*)/) {
3800: $thisallowed.=$1;
3801: $uri=$refuri;
3802: $statecond=$refstatecond;
3803: }
3804: }
3805: }
3806: }
3807: }
3808:
3809: #
3810: # Gathered now: all privileges that could apply, and condition number
3811: #
3812: #
3813: # Full or no access?
3814: #
3815:
3816: if ($thisallowed=~/F/) {
3817: return 'F';
3818: }
3819:
3820: unless ($thisallowed) {
3821: return '';
3822: }
3823:
3824: # Restrictions exist, deal with them
3825: #
3826: # C:according to course preferences
3827: # R:according to resource settings
3828: # L:unless locked
3829: # X:according to user session state
3830: #
3831:
3832: # Possibly locked functionality, check all courses
3833: # Locks might take effect only after 10 minutes cache expiration for other
3834: # courses, and 2 minutes for current course
3835:
3836: my $envkey;
3837: if ($thisallowed=~/L/) {
3838: foreach $envkey (keys %env) {
3839: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3840: my $courseid=$2;
3841: my $roleid=$1.'.'.$2;
3842: $courseid=~s/^\///;
3843: my $expiretime=600;
3844: if ($env{'request.role'} eq $roleid) {
3845: $expiretime=120;
3846: }
3847: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3848: my $prefix='course.'.$cdom.'_'.$cnum.'.';
3849: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
3850: &coursedescription($courseid,{'freshen_cache' => 1});
3851: }
3852: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3853: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3854: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3855: &log($env{'user.domain'},$env{'user.name'},
3856: $env{'user.home'},
3857: 'Locked by res: '.$priv.' for '.$uri.' due to '.
3858: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3859: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3860: return '';
3861: }
3862: }
3863: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3864: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3865: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3866: &log($env{'user.domain'},$env{'user.name'},
3867: $env{'user.home'},
3868: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
3869: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3870: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3871: return '';
3872: }
3873: }
3874: }
3875: }
3876: }
3877:
3878: #
3879: # Rest of the restrictions depend on selected course
3880: #
3881:
3882: unless ($env{'request.course.id'}) {
3883: if ($thisallowed eq 'A') {
3884: return 'A';
3885: } elsif ($thisallowed eq 'B') {
3886: return 'B';
3887: } else {
3888: return '1';
3889: }
3890: }
3891:
3892: #
3893: # Now user is definitely in a course
3894: #
3895:
3896:
3897: # Course preferences
3898:
3899: if ($thisallowed=~/C/) {
3900: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3901: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3902: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
3903: =~/\Q$rolecode\E/) {
3904: if ($priv ne 'pch') {
3905: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3906: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3907: $env{'request.course.id'});
3908: }
3909: return '';
3910: }
3911:
3912: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
3913: =~/\Q$unamedom\E/) {
3914: if ($priv ne 'pch') {
3915: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3916: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3917: $env{'request.course.id'});
3918: }
3919: return '';
3920: }
3921: }
3922:
3923: # Resource preferences
3924:
3925: if ($thisallowed=~/R/) {
3926: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3927: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
3928: if ($priv ne 'pch') {
3929: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3930: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3931: }
3932: return '';
3933: }
3934: }
3935:
3936: # Restricted by state or randomout?
3937:
3938: if ($thisallowed=~/X/) {
3939: if ($env{'acc.randomout'}) {
3940: if (!$symb) { $symb=&symbread($uri,1); }
3941: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
3942: return '';
3943: }
3944: }
3945: if (&condval($statecond)) {
3946: return '2';
3947: } else {
3948: return '';
3949: }
3950: }
3951:
3952: if ($thisallowed eq 'A') {
3953: return 'A';
3954: } elsif ($thisallowed eq 'B') {
3955: return 'B';
3956: }
3957: return 'F';
3958: }
3959:
3960: sub split_uri_for_cond {
3961: my $uri=&deversion(&declutter(shift));
3962: my @uriparts=split(/\//,$uri);
3963: my $filename=pop(@uriparts);
3964: my $pathname=join('/',@uriparts);
3965: return ($pathname,$filename);
3966: }
3967: # --------------------------------------------------- Is a resource on the map?
3968:
3969: sub is_on_map {
3970: my ($pathname,$filename) = &split_uri_for_cond(shift);
3971: #Trying to find the conditional for the file
3972: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
3973: /\&\Q$filename\E\:([\d\|]+)\&/);
3974: if ($match) {
3975: return (1,$1);
3976: } else {
3977: return (0,0);
3978: }
3979: }
3980:
3981: # --------------------------------------------------------- Get symb from alias
3982:
3983: sub get_symb_from_alias {
3984: my $symb=shift;
3985: my ($map,$resid,$url)=&decode_symb($symb);
3986: # Already is a symb
3987: if ($url) { return $symb; }
3988: # Must be an alias
3989: my $aliassymb='';
3990: my %bighash;
3991: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
3992: &GDBM_READER(),0640)) {
3993: my $rid=$bighash{'mapalias_'.$symb};
3994: if ($rid) {
3995: my ($mapid,$resid)=split(/\./,$rid);
3996: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3997: $resid,$bighash{'src_'.$rid});
3998: }
3999: untie %bighash;
4000: }
4001: return $aliassymb;
4002: }
4003:
4004: # ----------------------------------------------------------------- Define Role
4005:
4006: sub definerole {
4007: if (allowed('mcr','/')) {
4008: my ($rolename,$sysrole,$domrole,$courole)=@_;
4009: foreach my $role (split(':',$sysrole)) {
4010: my ($crole,$cqual)=split(/\&/,$role);
4011: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4012: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4013: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4014: return "refused:s:$crole&$cqual";
4015: }
4016: }
4017: }
4018: foreach my $role (split(':',$domrole)) {
4019: my ($crole,$cqual)=split(/\&/,$role);
4020: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4021: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4022: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
4023: return "refused:d:$crole&$cqual";
4024: }
4025: }
4026: }
4027: foreach my $role (split(':',$courole)) {
4028: my ($crole,$cqual)=split(/\&/,$role);
4029: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4030: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4031: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4032: return "refused:c:$crole&$cqual";
4033: }
4034: }
4035: }
4036: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4037: "$env{'user.domain'}:$env{'user.name'}:".
4038: "rolesdef_$rolename=".
4039: escape($sysrole.'_'.$domrole.'_'.$courole);
4040: return reply($command,$env{'user.home'});
4041: } else {
4042: return 'refused';
4043: }
4044: }
4045:
4046: # ---------------- Make a metadata query against the network of library servers
4047:
4048: sub metadata_query {
4049: my ($query,$custom,$customshow,$server_array)=@_;
4050: my %rhash;
4051: my @server_list = (defined($server_array) ? @$server_array
4052: : keys(%libserv) );
4053: for my $server (@server_list) {
4054: unless ($custom or $customshow) {
4055: my $reply=&reply("querysend:".&escape($query),$server);
4056: $rhash{$server}=$reply;
4057: }
4058: else {
4059: my $reply=&reply("querysend:".&escape($query).':'.
4060: &escape($custom).':'.&escape($customshow),
4061: $server);
4062: $rhash{$server}=$reply;
4063: }
4064: }
4065: return \%rhash;
4066: }
4067:
4068: # ----------------------------------------- Send log queries and wait for reply
4069:
4070: sub log_query {
4071: my ($uname,$udom,$query,%filters)=@_;
4072: my $uhome=&homeserver($uname,$udom);
4073: if ($uhome eq 'no_host') { return 'error: no_host'; }
4074: my $uhost=$hostname{$uhome};
4075: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
4076: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4077: $uhome);
4078: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
4079: return get_query_reply($queryid);
4080: }
4081:
4082: # ------- Request retrieval of institutional classlists for course(s)
4083:
4084: sub fetch_enrollment_query {
4085: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
4086: my $homeserver;
4087: my $maxtries = 1;
4088: if ($context eq 'automated') {
4089: $homeserver = $perlvar{'lonHostID'};
4090: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
4091: } else {
4092: $homeserver = &homeserver($cnum,$dom);
4093: }
4094: my $host=$hostname{$homeserver};
4095: my $cmd = '';
4096: foreach my $affiliate (keys %{$affiliatesref}) {
4097: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4098: }
4099: $cmd =~ s/%%$//;
4100: $cmd = &escape($cmd);
4101: my $query = 'fetchenrollment';
4102: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
4103: unless ($queryid=~/^\Q$host\E\_/) {
4104: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4105: return 'error: '.$queryid;
4106: }
4107: my $reply = &get_query_reply($queryid);
4108: my $tries = 1;
4109: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4110: $reply = &get_query_reply($queryid);
4111: $tries ++;
4112: }
4113: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4114: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4115: } else {
4116: my @responses = split/:/,$reply;
4117: if ($homeserver eq $perlvar{'lonHostID'}) {
4118: foreach my $line (@responses) {
4119: my ($key,$value) = split(/=/,$line,2);
4120: $$replyref{$key} = $value;
4121: }
4122: } else {
4123: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
4124: foreach my $line (@responses) {
4125: my ($key,$value) = split(/=/,$line);
4126: $$replyref{$key} = $value;
4127: if ($value > 0) {
4128: foreach my $item (@{$$affiliatesref{$key}}) {
4129: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
4130: my $destname = $pathname.'/'.$filename;
4131: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
4132: if ($xml_classlist =~ /^error/) {
4133: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4134: } else {
4135: if ( open(FILE,">$destname") ) {
4136: print FILE &unescape($xml_classlist);
4137: close(FILE);
4138: } else {
4139: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
4140: }
4141: }
4142: }
4143: }
4144: }
4145: }
4146: return 'ok';
4147: }
4148: return 'error';
4149: }
4150:
4151: sub get_query_reply {
4152: my $queryid=shift;
4153: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4154: my $reply='';
4155: for (1..100) {
4156: sleep 2;
4157: if (-e $replyfile.'.end') {
4158: if (open(my $fh,$replyfile)) {
4159: $reply.=<$fh>;
4160: close($fh);
4161: } else { return 'error: reply_file_error'; }
4162: return &unescape($reply);
4163: }
4164: }
4165: return 'timeout:'.$queryid;
4166: }
4167:
4168: sub courselog_query {
4169: #
4170: # possible filters:
4171: # url: url or symb
4172: # username
4173: # domain
4174: # action: view, submit, grade
4175: # start: timestamp
4176: # end: timestamp
4177: #
4178: my (%filters)=@_;
4179: unless ($env{'request.course.id'}) { return 'no_course'; }
4180: if ($filters{'url'}) {
4181: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4182: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4183: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4184: }
4185: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4186: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4187: return &log_query($cname,$cdom,'courselog',%filters);
4188: }
4189:
4190: sub userlog_query {
4191: my ($uname,$udom,%filters)=@_;
4192: return &log_query($uname,$udom,'userlog',%filters);
4193: }
4194:
4195: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4196:
4197: sub auto_run {
4198: my ($cnum,$cdom) = @_;
4199: my $homeserver = &homeserver($cnum,$cdom);
4200: my $response = &reply('autorun:'.$cdom,$homeserver);
4201: return $response;
4202: }
4203:
4204: sub auto_get_sections {
4205: my ($cnum,$cdom,$inst_coursecode) = @_;
4206: my $homeserver = &homeserver($cnum,$cdom);
4207: my @secs = ();
4208: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
4209: unless ($response eq 'refused') {
4210: @secs = split/:/,$response;
4211: }
4212: return @secs;
4213: }
4214:
4215: sub auto_new_course {
4216: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4217: my $homeserver = &homeserver($cnum,$cdom);
4218: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
4219: return $response;
4220: }
4221:
4222: sub auto_validate_courseID {
4223: my ($cnum,$cdom,$inst_course_id) = @_;
4224: my $homeserver = &homeserver($cnum,$cdom);
4225: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
4226: return $response;
4227: }
4228:
4229: sub auto_create_password {
4230: my ($cnum,$cdom,$authparam) = @_;
4231: my $homeserver = &homeserver($cnum,$cdom);
4232: my $create_passwd = 0;
4233: my $authchk = '';
4234: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4235: if ($response eq 'refused') {
4236: $authchk = 'refused';
4237: } else {
4238: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4239: }
4240: return ($authparam,$create_passwd,$authchk);
4241: }
4242:
4243: sub auto_photo_permission {
4244: my ($cnum,$cdom,$students) = @_;
4245: my $homeserver = &homeserver($cnum,$cdom);
4246: my ($outcome,$perm_reqd,$conditions) =
4247: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
4248: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4249: return (undef,undef);
4250: }
4251: return ($outcome,$perm_reqd,$conditions);
4252: }
4253:
4254: sub auto_checkphotos {
4255: my ($uname,$udom,$pid) = @_;
4256: my $homeserver = &homeserver($uname,$udom);
4257: my ($result,$resulttype);
4258: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
4259: &escape($uname).':'.&escape($pid),
4260: $homeserver));
4261: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4262: return (undef,undef);
4263: }
4264: if ($outcome) {
4265: ($result,$resulttype) = split(/:/,$outcome);
4266: }
4267: return ($result,$resulttype);
4268: }
4269:
4270: sub auto_photochoice {
4271: my ($cnum,$cdom) = @_;
4272: my $homeserver = &homeserver($cnum,$cdom);
4273: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
4274: &escape($cdom),
4275: $homeserver)));
4276: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4277: return (undef,undef);
4278: }
4279: return ($update,$comment);
4280: }
4281:
4282: sub auto_photoupdate {
4283: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4284: my $homeserver = &homeserver($cnum,$dom);
4285: my $host=$hostname{$homeserver};
4286: my $cmd = '';
4287: my $maxtries = 1;
4288: foreach my $affiliate (keys(%{$affiliatesref})) {
4289: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4290: }
4291: $cmd =~ s/%%$//;
4292: $cmd = &escape($cmd);
4293: my $query = 'institutionalphotos';
4294: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4295: unless ($queryid=~/^\Q$host\E\_/) {
4296: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4297: return 'error: '.$queryid;
4298: }
4299: my $reply = &get_query_reply($queryid);
4300: my $tries = 1;
4301: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4302: $reply = &get_query_reply($queryid);
4303: $tries ++;
4304: }
4305: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4306: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4307: } else {
4308: my @responses = split(/:/,$reply);
4309: my $outcome = shift(@responses);
4310: foreach my $item (@responses) {
4311: my ($key,$value) = split(/=/,$item);
4312: $$photo{$key} = $value;
4313: }
4314: return $outcome;
4315: }
4316: return 'error';
4317: }
4318:
4319: sub auto_instcode_format {
4320: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4321: $cat_order) = @_;
4322: my $courses = '';
4323: my @homeservers;
4324: if ($caller eq 'global') {
4325: foreach my $tryserver (keys(%libserv)) {
4326: if ($hostdom{$tryserver} eq $codedom) {
4327: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4328: push(@homeservers,$tryserver);
4329: }
4330: }
4331: }
4332: } else {
4333: push(@homeservers,&homeserver($caller,$codedom));
4334: }
4335: foreach my $code (keys(%{$instcodes})) {
4336: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
4337: }
4338: chop($courses);
4339: my $ok_response = 0;
4340: my $response;
4341: while (@homeservers > 0 && $ok_response == 0) {
4342: my $server = shift(@homeservers);
4343: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4344: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4345: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
4346: split/:/,$response;
4347: %{$codes} = (%{$codes},&str2hash($codes_str));
4348: push(@{$codetitles},&str2array($codetitles_str));
4349: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4350: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4351: $ok_response = 1;
4352: }
4353: }
4354: if ($ok_response) {
4355: return 'ok';
4356: } else {
4357: return $response;
4358: }
4359: }
4360:
4361: sub auto_instcode_defaults {
4362: my ($domain,$returnhash,$code_order) = @_;
4363: my @homeservers;
4364: foreach my $tryserver (keys(%libserv)) {
4365: if ($hostdom{$tryserver} eq $domain) {
4366: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4367: push(@homeservers,$tryserver);
4368: }
4369: }
4370: }
4371: my $ok_response = 0;
4372: my $response;
4373: while (@homeservers > 0 && $ok_response == 0) {
4374: my $server = shift(@homeservers);
4375: $response=&reply('autoinstcodedefaults:'.$domain,$server);
4376: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4377: foreach my $pair (split(/\&/,$response)) {
4378: my ($name,$value)=split(/\=/,$pair);
4379: if ($name eq 'code_order') {
4380: @{$code_order} = split(/\&/,&unescape($value));
4381: } else {
4382: $returnhash->{&unescape($name)}=&unescape($value);
4383: }
4384: }
4385: $ok_response = 1;
4386: }
4387: }
4388: if ($ok_response) {
4389: return 'ok';
4390: } else {
4391: return $response;
4392: }
4393: }
4394:
4395: sub auto_validate_class_sec {
4396: my ($cdom,$cnum,$owner,$inst_class) = @_;
4397: my $homeserver = &homeserver($cnum,$cdom);
4398: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
4399: &escape($owner).':'.$cdom,$homeserver);
4400: return $response;
4401: }
4402:
4403: # ------------------------------------------------------- Course Group routines
4404:
4405: sub get_coursegroups {
4406: my ($cdom,$cnum,$group,$namespace) = @_;
4407: return(&dump($namespace,$cdom,$cnum,$group));
4408: }
4409:
4410: sub modify_coursegroup {
4411: my ($cdom,$cnum,$groupsettings) = @_;
4412: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4413: }
4414:
4415: sub toggle_coursegroup_status {
4416: my ($cdom,$cnum,$group,$action) = @_;
4417: my ($from_namespace,$to_namespace);
4418: if ($action eq 'delete') {
4419: $from_namespace = 'coursegroups';
4420: $to_namespace = 'deleted_groups';
4421: } else {
4422: $from_namespace = 'deleted_groups';
4423: $to_namespace = 'coursegroups';
4424: }
4425: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
4426: if (my $tmp = &error(%curr_group)) {
4427: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4428: return ('read error',$tmp);
4429: } else {
4430: my %savedsettings = %curr_group;
4431: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
4432: my $deloutcome;
4433: if ($result eq 'ok') {
4434: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
4435: } else {
4436: return ('write error',$result);
4437: }
4438: if ($deloutcome eq 'ok') {
4439: return 'ok';
4440: } else {
4441: return ('delete error',$deloutcome);
4442: }
4443: }
4444: }
4445:
4446: sub modify_group_roles {
4447: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4448: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4449: my $role = 'gr/'.&escape($userprivs);
4450: my ($uname,$udom) = split(/:/,$user);
4451: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
4452: if ($result eq 'ok') {
4453: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4454: }
4455: return $result;
4456: }
4457:
4458: sub modify_coursegroup_membership {
4459: my ($cdom,$cnum,$membership) = @_;
4460: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4461: return $result;
4462: }
4463:
4464: sub get_active_groups {
4465: my ($udom,$uname,$cdom,$cnum) = @_;
4466: my $now = time;
4467: my %groups = ();
4468: foreach my $key (keys(%env)) {
4469: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
4470: my ($start,$end) = split(/\./,$env{$key});
4471: if (($end!=0) && ($end<$now)) { next; }
4472: if (($start!=0) && ($start>$now)) { next; }
4473: if ($1 eq $cdom && $2 eq $cnum) {
4474: $groups{$3} = $env{$key} ;
4475: }
4476: }
4477: }
4478: return %groups;
4479: }
4480:
4481: sub get_group_membership {
4482: my ($cdom,$cnum,$group) = @_;
4483: return(&dump('groupmembership',$cdom,$cnum,$group));
4484: }
4485:
4486: sub get_users_groups {
4487: my ($udom,$uname,$courseid) = @_;
4488: my @usersgroups;
4489: my $cachetime=1800;
4490:
4491: my $hashid="$udom:$uname:$courseid";
4492: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4493: if (defined($cached)) {
4494: @usersgroups = split(/:/,$grouplist);
4495: } else {
4496: $grouplist = '';
4497: my %roleshash = &dump('roles',$udom,$uname,$courseid);
4498: my ($tmp) = keys(%roleshash);
4499: if ($tmp=~/^error:/) {
4500: &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
4501: } else {
4502: my $access_end = $env{'course.'.$courseid.
4503: '.default_enrollment_end_date'};
4504: my $now = time;
4505: foreach my $key (keys(%roleshash)) {
4506: if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
4507: my $group = $1;
4508: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4509: my $start = $2;
4510: my $end = $1;
4511: if ($start == -1) { next; } # deleted from group
4512: if (($start!=0) && ($start>$now)) { next; }
4513: if (($end!=0) && ($end<$now)) {
4514: if ($access_end && $access_end < $now) {
4515: if ($access_end - $end < 86400) {
4516: push(@usersgroups,$group);
4517: }
4518: }
4519: next;
4520: }
4521: push(@usersgroups,$group);
4522: }
4523: }
4524: }
4525: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4526: $grouplist = join(':',@usersgroups);
4527: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4528: }
4529: }
4530: return @usersgroups;
4531: }
4532:
4533: sub devalidate_getgroups_cache {
4534: my ($udom,$uname,$cdom,$cnum)=@_;
4535: my $courseid = $cdom.'_'.$cnum;
4536:
4537: my $hashid="$udom:$uname:$courseid";
4538: &devalidate_cache_new('getgroups',$hashid);
4539: }
4540:
4541: # ------------------------------------------------------------------ Plain Text
4542:
4543: sub plaintext {
4544: my ($short,$type,$cid) = @_;
4545: if ($short =~ /^cr/) {
4546: return (split('/',$short))[-1];
4547: }
4548: if (!defined($cid)) {
4549: $cid = $env{'request.course.id'};
4550: }
4551: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4552: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4553: '.plaintext'});
4554: }
4555: my %rolenames = (
4556: Course => 'std',
4557: Group => 'alt1',
4558: );
4559: if (defined($type) &&
4560: defined($rolenames{$type}) &&
4561: defined($prp{$short}{$rolenames{$type}})) {
4562: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4563: } else {
4564: return &Apache::lonlocal::mt($prp{$short}{'std'});
4565: }
4566: }
4567:
4568: # ----------------------------------------------------------------- Assign Role
4569:
4570: sub assignrole {
4571: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4572: my $mrole;
4573: if ($role =~ /^cr\//) {
4574: my $cwosec=$url;
4575: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4576: unless (&allowed('ccr',$cwosec)) {
4577: &logthis('Refused custom assignrole: '.
4578: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4579: $env{'user.name'}.' at '.$env{'user.domain'});
4580: return 'refused';
4581: }
4582: $mrole='cr';
4583: } elsif ($role =~ /^gr\//) {
4584: my $cwogrp=$url;
4585: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
4586: unless (&allowed('mdg',$cwogrp)) {
4587: &logthis('Refused group assignrole: '.
4588: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4589: $env{'user.name'}.' at '.$env{'user.domain'});
4590: return 'refused';
4591: }
4592: $mrole='gr';
4593: } else {
4594: my $cwosec=$url;
4595: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4596: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4597: &logthis('Refused assignrole: '.
4598: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4599: $env{'user.name'}.' at '.$env{'user.domain'});
4600: return 'refused';
4601: }
4602: $mrole=$role;
4603: }
4604: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4605: "$udom:$uname:$url".'_'."$mrole=$role";
4606: if ($end) { $command.='_'.$end; }
4607: if ($start) {
4608: if ($end) {
4609: $command.='_'.$start;
4610: } else {
4611: $command.='_0_'.$start;
4612: }
4613: }
4614: my $origstart = $start;
4615: my $origend = $end;
4616: # actually delete
4617: if ($deleteflag) {
4618: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4619: # modify command to delete the role
4620: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4621: "$udom:$uname:$url".'_'."$mrole";
4622: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4623: # set start and finish to negative values for userrolelog
4624: $start=-1;
4625: $end=-1;
4626: }
4627: }
4628: # send command
4629: my $answer=&reply($command,&homeserver($uname,$udom));
4630: # log new user role if status is ok
4631: if ($answer eq 'ok') {
4632: &userrolelog($role,$uname,$udom,$url,$start,$end);
4633: # for course roles, perform group memberships changes triggered by role change.
4634: unless ($role =~ /^gr/) {
4635: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4636: $origstart);
4637: }
4638: }
4639: return $answer;
4640: }
4641:
4642: # -------------------------------------------------- Modify user authentication
4643: # Overrides without validation
4644:
4645: sub modifyuserauth {
4646: my ($udom,$uname,$umode,$upass)=@_;
4647: my $uhome=&homeserver($uname,$udom);
4648: unless (&allowed('mau',$udom)) { return 'refused'; }
4649: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4650: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4651: ' in domain '.$env{'request.role.domain'});
4652: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4653: &escape($upass),$uhome);
4654: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4655: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4656: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4657: &log($udom,,$uname,$uhome,
4658: 'Authentication changed by '.$env{'user.domain'}.', '.
4659: $env{'user.name'}.', '.$umode.
4660: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4661: unless ($reply eq 'ok') {
4662: &logthis('Authentication mode error: '.$reply);
4663: return 'error: '.$reply;
4664: }
4665: return 'ok';
4666: }
4667:
4668: # --------------------------------------------------------------- Modify a user
4669:
4670: sub modifyuser {
4671: my ($udom, $uname, $uid,
4672: $umode, $upass, $first,
4673: $middle, $last, $gene,
4674: $forceid, $desiredhome, $email)=@_;
4675: $udom= &LONCAPA::clean_domain($udom);
4676: $uname=&LONCAPA::clean_username($uname);
4677: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4678: $umode.', '.$first.', '.$middle.', '.
4679: $last.', '.$gene.'(forceid: '.$forceid.')'.
4680: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4681: ' desiredhome not specified').
4682: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4683: ' in domain '.$env{'request.role.domain'});
4684: my $uhome=&homeserver($uname,$udom,'true');
4685: # ----------------------------------------------------------------- Create User
4686: if (($uhome eq 'no_host') &&
4687: (($umode && $upass) || ($umode eq 'localauth'))) {
4688: my $unhome='';
4689: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
4690: $unhome = $desiredhome;
4691: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4692: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4693: } else { # load balancing routine for determining $unhome
4694: my $tryserver;
4695: my $loadm=10000000;
4696: foreach $tryserver (keys %libserv) {
4697: if ($hostdom{$tryserver} eq $udom) {
4698: my $answer=reply('load',$tryserver);
4699: if (($answer=~/\d+/) && ($answer<$loadm)) {
4700: $loadm=$answer;
4701: $unhome=$tryserver;
4702: }
4703: }
4704: }
4705: }
4706: if (($unhome eq '') || ($unhome eq 'no_host')) {
4707: return 'error: unable to find a home server for '.$uname.
4708: ' in domain '.$udom;
4709: }
4710: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4711: &escape($upass),$unhome);
4712: unless ($reply eq 'ok') {
4713: return 'error: '.$reply;
4714: }
4715: $uhome=&homeserver($uname,$udom,'true');
4716: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4717: return 'error: unable verify users home machine.';
4718: }
4719: } # End of creation of new user
4720: # ---------------------------------------------------------------------- Add ID
4721: if ($uid) {
4722: $uid=~tr/A-Z/a-z/;
4723: my %uidhash=&idrget($udom,$uname);
4724: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4725: && (!$forceid)) {
4726: unless ($uid eq $uidhash{$uname}) {
4727: return 'error: user id "'.$uid.'" does not match '.
4728: 'current user id "'.$uidhash{$uname}.'".';
4729: }
4730: } else {
4731: &idput($udom,($uname => $uid));
4732: }
4733: }
4734: # -------------------------------------------------------------- Add names, etc
4735: my @tmp=&get('environment',
4736: ['firstname','middlename','lastname','generation'],
4737: $udom,$uname);
4738: my %names;
4739: if ($tmp[0] =~ m/^error:.*/) {
4740: %names=();
4741: } else {
4742: %names = @tmp;
4743: }
4744: #
4745: # Make sure to not trash student environment if instructor does not bother
4746: # to supply name and email information
4747: #
4748: if ($first) { $names{'firstname'} = $first; }
4749: if (defined($middle)) { $names{'middlename'} = $middle; }
4750: if ($last) { $names{'lastname'} = $last; }
4751: if (defined($gene)) { $names{'generation'} = $gene; }
4752: if ($email) {
4753: $email=~s/[^\w\@\.\-\,]//gs;
4754: if ($email=~/\@/) { $names{'notification'} = $email;
4755: $names{'critnotification'} = $email;
4756: $names{'permanentemail'} = $email; }
4757: }
4758: my $reply = &put('environment', \%names, $udom,$uname);
4759: if ($reply ne 'ok') { return 'error: '.$reply; }
4760: &devalidate_cache_new('namescache',$uname.':'.$udom);
4761: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
4762: $umode.', '.$first.', '.$middle.', '.
4763: $last.', '.$gene.' by '.
4764: $env{'user.name'}.' at '.$env{'user.domain'});
4765: return 'ok';
4766: }
4767:
4768: # -------------------------------------------------------------- Modify student
4769:
4770: sub modifystudent {
4771: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
4772: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
4773: if (!$cid) {
4774: unless ($cid=$env{'request.course.id'}) {
4775: return 'not_in_class';
4776: }
4777: }
4778: # --------------------------------------------------------------- Make the user
4779: my $reply=&modifyuser
4780: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
4781: $desiredhome,$email);
4782: unless ($reply eq 'ok') { return $reply; }
4783: # This will cause &modify_student_enrollment to get the uid from the
4784: # students environment
4785: $uid = undef if (!$forceid);
4786: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
4787: $gene,$usec,$end,$start,$type,$locktype,$cid);
4788: return $reply;
4789: }
4790:
4791: sub modify_student_enrollment {
4792: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
4793: my ($cdom,$cnum,$chome);
4794: if (!$cid) {
4795: unless ($cid=$env{'request.course.id'}) {
4796: return 'not_in_class';
4797: }
4798: $cdom=$env{'course.'.$cid.'.domain'};
4799: $cnum=$env{'course.'.$cid.'.num'};
4800: } else {
4801: ($cdom,$cnum)=split(/_/,$cid);
4802: }
4803: $chome=$env{'course.'.$cid.'.home'};
4804: if (!$chome) {
4805: $chome=&homeserver($cnum,$cdom);
4806: }
4807: if (!$chome) { return 'unknown_course'; }
4808: # Make sure the user exists
4809: my $uhome=&homeserver($uname,$udom);
4810: if (($uhome eq '') || ($uhome eq 'no_host')) {
4811: return 'error: no such user';
4812: }
4813: # Get student data if we were not given enough information
4814: if (!defined($first) || $first eq '' ||
4815: !defined($last) || $last eq '' ||
4816: !defined($uid) || $uid eq '' ||
4817: !defined($middle) || $middle eq '' ||
4818: !defined($gene) || $gene eq '') {
4819: # They did not supply us with enough data to enroll the student, so
4820: # we need to pick up more information.
4821: my %tmp = &get('environment',
4822: ['firstname','middlename','lastname', 'generation','id']
4823: ,$udom,$uname);
4824:
4825: #foreach my $key (keys(%tmp)) {
4826: # &logthis("key $key = ".$tmp{$key});
4827: #}
4828: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4829: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4830: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
4831: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
4832: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4833: }
4834: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
4835: my $reply=cput('classlist',
4836: {"$uname:$udom" =>
4837: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
4838: $cdom,$cnum);
4839: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4840: return 'error: '.$reply;
4841: } else {
4842: &devalidate_getsection_cache($udom,$uname,$cid);
4843: }
4844: # Add student role to user
4845: my $uurl='/'.$cid;
4846: $uurl=~s/\_/\//g;
4847: if ($usec) {
4848: $uurl.='/'.$usec;
4849: }
4850: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
4851: }
4852:
4853: sub format_name {
4854: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
4855: my $name;
4856: if ($first ne 'lastname') {
4857: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
4858: } else {
4859: if ($lastname=~/\S/) {
4860: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
4861: $name=~s/\s+,/,/;
4862: } else {
4863: $name.= $firstname.' '.$middlename.' '.$generation;
4864: }
4865: }
4866: $name=~s/^\s+//;
4867: $name=~s/\s+$//;
4868: $name=~s/\s+/ /g;
4869: return $name;
4870: }
4871:
4872: # ------------------------------------------------- Write to course preferences
4873:
4874: sub writecoursepref {
4875: my ($courseid,%prefs)=@_;
4876: $courseid=~s/^\///;
4877: $courseid=~s/\_/\//g;
4878: my ($cdomain,$cnum)=split(/\//,$courseid);
4879: my $chome=homeserver($cnum,$cdomain);
4880: if (($chome eq '') || ($chome eq 'no_host')) {
4881: return 'error: no such course';
4882: }
4883: my $cstring='';
4884: foreach my $pref (keys(%prefs)) {
4885: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
4886: }
4887: $cstring=~s/\&$//;
4888: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
4889: }
4890:
4891: # ---------------------------------------------------------- Make/modify course
4892:
4893: sub createcourse {
4894: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
4895: $course_owner,$crstype)=@_;
4896: $url=&declutter($url);
4897: my $cid='';
4898: unless (&allowed('ccc',$udom)) {
4899: return 'refused';
4900: }
4901: # ------------------------------------------------------------------- Create ID
4902: my $uname=int(1+rand(9)).
4903: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
4904: substr($$.time,0,5).unpack("H8",pack("I32",time)).
4905: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4906: # ----------------------------------------------- Make sure that does not exist
4907: my $uhome=&homeserver($uname,$udom,'true');
4908: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4909: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
4910: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4911: $uhome=&homeserver($uname,$udom,'true');
4912: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4913: return 'error: unable to generate unique course-ID';
4914: }
4915: }
4916: # ------------------------------------------------ Check supplied server name
4917: $course_server = $env{'user.homeserver'} if (! defined($course_server));
4918: if (! exists($libserv{$course_server})) {
4919: return 'error:bad server name '.$course_server;
4920: }
4921: # ------------------------------------------------------------- Make the course
4922: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
4923: $course_server);
4924: unless ($reply eq 'ok') { return 'error: '.$reply; }
4925: $uhome=&homeserver($uname,$udom,'true');
4926: if (($uhome eq '') || ($uhome eq 'no_host')) {
4927: return 'error: no such course';
4928: }
4929: # ----------------------------------------------------------------- Course made
4930: # log existence
4931: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
4932: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
4933: &escape($crstype),$uhome);
4934: &flushcourselogs();
4935: # set toplevel url
4936: my $topurl=$url;
4937: unless ($nonstandard) {
4938: # ------------------------------------------ For standard courses, make top url
4939: my $mapurl=&clutter($url);
4940: if ($mapurl eq '/res/') { $mapurl=''; }
4941: $env{'form.initmap'}=(<<ENDINITMAP);
4942: <map>
4943: <resource id="1" type="start"></resource>
4944: <resource id="2" src="$mapurl"></resource>
4945: <resource id="3" type="finish"></resource>
4946: <link index="1" from="1" to="2"></link>
4947: <link index="2" from="2" to="3"></link>
4948: </map>
4949: ENDINITMAP
4950: $topurl=&declutter(
4951: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
4952: );
4953: }
4954: # ----------------------------------------------------------- Write preferences
4955: &writecoursepref($udom.'_'.$uname,
4956: ('description' => $description,
4957: 'url' => $topurl));
4958: return '/'.$udom.'/'.$uname;
4959: }
4960:
4961: sub is_course {
4962: my ($cdom,$cnum) = @_;
4963: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
4964: undef,'.');
4965: if (exists($courses{$cdom.'_'.$cnum})) {
4966: return 1;
4967: }
4968: return 0;
4969: }
4970:
4971: # ---------------------------------------------------------- Assign Custom Role
4972:
4973: sub assigncustomrole {
4974: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
4975: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
4976: $end,$start,$deleteflag);
4977: }
4978:
4979: # ----------------------------------------------------------------- Revoke Role
4980:
4981: sub revokerole {
4982: my ($udom,$uname,$url,$role,$deleteflag)=@_;
4983: my $now=time;
4984: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
4985: }
4986:
4987: # ---------------------------------------------------------- Revoke Custom Role
4988:
4989: sub revokecustomrole {
4990: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
4991: my $now=time;
4992: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
4993: $deleteflag);
4994: }
4995:
4996: # ------------------------------------------------------------ Disk usage
4997: sub diskusage {
4998: my ($udom,$uname,$directoryRoot)=@_;
4999: $directoryRoot =~ s/\/$//;
5000: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
5001: return $listing;
5002: }
5003:
5004: sub is_locked {
5005: my ($file_name, $domain, $user) = @_;
5006: my @check;
5007: my $is_locked;
5008: push @check, $file_name;
5009: my %locked = &get('file_permissions',\@check,
5010: $env{'user.domain'},$env{'user.name'});
5011: my ($tmp)=keys(%locked);
5012: if ($tmp=~/^error:/) { undef(%locked); }
5013:
5014: if (ref($locked{$file_name}) eq 'ARRAY') {
5015: $is_locked = 'false';
5016: foreach my $entry (@{$locked{$file_name}}) {
5017: if (ref($entry) eq 'ARRAY') {
5018: $is_locked = 'true';
5019: last;
5020: }
5021: }
5022: } else {
5023: $is_locked = 'false';
5024: }
5025: }
5026:
5027: sub declutter_portfile {
5028: my ($file) = @_;
5029: &logthis("got $file");
5030: $file =~ s-^(/portfolio/|portfolio/)-/-;
5031: &logthis("ret $file");
5032: return $file;
5033: }
5034:
5035: # ------------------------------------------------------------- Mark as Read Only
5036:
5037: sub mark_as_readonly {
5038: my ($domain,$user,$files,$what) = @_;
5039: my %current_permissions = &dump('file_permissions',$domain,$user);
5040: my ($tmp)=keys(%current_permissions);
5041: if ($tmp=~/^error:/) { undef(%current_permissions); }
5042: foreach my $file (@{$files}) {
5043: $file = &declutter_portfile($file);
5044: push(@{$current_permissions{$file}},$what);
5045: }
5046: &put('file_permissions',\%current_permissions,$domain,$user);
5047: return;
5048: }
5049:
5050: # ------------------------------------------------------------Save Selected Files
5051:
5052: sub save_selected_files {
5053: my ($user, $path, @files) = @_;
5054: my $filename = $user."savedfiles";
5055: my @other_files = &files_not_in_path($user, $path);
5056: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5057: foreach my $file (@files) {
5058: print (OUT $env{'form.currentpath'}.$file."\n");
5059: }
5060: foreach my $file (@other_files) {
5061: print (OUT $file."\n");
5062: }
5063: close (OUT);
5064: return 'ok';
5065: }
5066:
5067: sub clear_selected_files {
5068: my ($user) = @_;
5069: my $filename = $user."savedfiles";
5070: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5071: print (OUT undef);
5072: close (OUT);
5073: return ("ok");
5074: }
5075:
5076: sub files_in_path {
5077: my ($user, $path) = @_;
5078: my $filename = $user."savedfiles";
5079: my %return_files;
5080: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5081: while (my $line_in = <IN>) {
5082: chomp ($line_in);
5083: my @paths_and_file = split (m!/!, $line_in);
5084: my $file_part = pop (@paths_and_file);
5085: my $path_part = join ('/', @paths_and_file);
5086: $path_part.='/';
5087: my $path_and_file = $path_part.$file_part;
5088: if ($path_part eq $path) {
5089: $return_files{$file_part}= 'selected';
5090: }
5091: }
5092: close (IN);
5093: return (\%return_files);
5094: }
5095:
5096: # called in portfolio select mode, to show files selected NOT in current directory
5097: sub files_not_in_path {
5098: my ($user, $path) = @_;
5099: my $filename = $user."savedfiles";
5100: my @return_files;
5101: my $path_part;
5102: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5103: while (my $line = <IN>) {
5104: #ok, I know it's clunky, but I want it to work
5105: my @paths_and_file = split(m|/|, $line);
5106: my $file_part = pop(@paths_and_file);
5107: chomp($file_part);
5108: my $path_part = join('/', @paths_and_file);
5109: $path_part .= '/';
5110: my $path_and_file = $path_part.$file_part;
5111: if ($path_part ne $path) {
5112: push(@return_files, ($path_and_file));
5113: }
5114: }
5115: close(OUT);
5116: return (@return_files);
5117: }
5118:
5119: #----------------------------------------------Get portfolio file permissions
5120:
5121: sub get_portfile_permissions {
5122: my ($domain,$user) = @_;
5123: my %current_permissions = &dump('file_permissions',$domain,$user);
5124: my ($tmp)=keys(%current_permissions);
5125: if ($tmp=~/^error:/) { undef(%current_permissions); }
5126: return \%current_permissions;
5127: }
5128:
5129: #---------------------------------------------Get portfolio file access controls
5130:
5131: sub get_access_controls {
5132: my ($current_permissions,$group,$file) = @_;
5133: my %access;
5134: my $real_file = $file;
5135: $file =~ s/\.meta$//;
5136: if (defined($file)) {
5137: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5138: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
5139: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
5140: }
5141: }
5142: } else {
5143: foreach my $key (keys(%{$current_permissions})) {
5144: if ($key =~ /\0accesscontrol$/) {
5145: if (defined($group)) {
5146: if ($key !~ m-^\Q$group\E/-) {
5147: next;
5148: }
5149: }
5150: my ($fullpath) = split(/\0/,$key);
5151: if (ref($$current_permissions{$key}) eq 'HASH') {
5152: foreach my $control (keys(%{$$current_permissions{$key}})) {
5153: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5154: }
5155: }
5156: }
5157: }
5158: }
5159: return %access;
5160: }
5161:
5162: sub modify_access_controls {
5163: my ($file_name,$changes,$domain,$user)=@_;
5164: my ($outcome,$deloutcome);
5165: my %store_permissions;
5166: my %new_values;
5167: my %new_control;
5168: my %translation;
5169: my @deletions = ();
5170: my $now = time;
5171: if (exists($$changes{'activate'})) {
5172: if (ref($$changes{'activate'}) eq 'HASH') {
5173: my @newitems = sort(keys(%{$$changes{'activate'}}));
5174: my $numnew = scalar(@newitems);
5175: for (my $i=0; $i<$numnew; $i++) {
5176: my $newkey = $newitems[$i];
5177: my $newid = &Apache::loncommon::get_cgi_id();
5178: if ($newkey =~ /^\d+:/) {
5179: $newkey =~ s/^(\d+)/$newid/;
5180: $translation{$1} = $newid;
5181: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5182: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5183: $translation{$1} = $newid;
5184: }
5185: $new_values{$file_name."\0".$newkey} =
5186: $$changes{'activate'}{$newitems[$i]};
5187: $new_control{$newkey} = $now;
5188: }
5189: }
5190: }
5191: my %todelete;
5192: my %changed_items;
5193: foreach my $action ('delete','update') {
5194: if (exists($$changes{$action})) {
5195: if (ref($$changes{$action}) eq 'HASH') {
5196: foreach my $key (keys(%{$$changes{$action}})) {
5197: my ($itemnum) = ($key =~ /^([^:]+):/);
5198: if ($action eq 'delete') {
5199: $todelete{$itemnum} = 1;
5200: } else {
5201: $changed_items{$itemnum} = $key;
5202: }
5203: }
5204: }
5205: }
5206: }
5207: # get lock on access controls for file.
5208: my $lockhash = {
5209: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5210: ':'.$env{'user.domain'},
5211: };
5212: my $tries = 0;
5213: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5214:
5215: while (($gotlock ne 'ok') && $tries <3) {
5216: $tries ++;
5217: sleep 1;
5218: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5219: }
5220: if ($gotlock eq 'ok') {
5221: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5222: my ($tmp)=keys(%curr_permissions);
5223: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5224: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5225: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5226: if (ref($curr_controls) eq 'HASH') {
5227: foreach my $control_item (keys(%{$curr_controls})) {
5228: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5229: if (defined($todelete{$itemnum})) {
5230: push(@deletions,$file_name."\0".$control_item);
5231: } else {
5232: if (defined($changed_items{$itemnum})) {
5233: $new_control{$changed_items{$itemnum}} = $now;
5234: push(@deletions,$file_name."\0".$control_item);
5235: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5236: } else {
5237: $new_control{$control_item} = $$curr_controls{$control_item};
5238: }
5239: }
5240: }
5241: }
5242: }
5243: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5244: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5245: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5246: # remove lock
5247: my @del_lock = ($file_name."\0".'locked_access_records');
5248: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5249: } else {
5250: $outcome = "error: could not obtain lockfile\n";
5251: }
5252: return ($outcome,$deloutcome,\%new_values,\%translation);
5253: }
5254:
5255: #------------------------------------------------------Get Marked as Read Only
5256:
5257: sub get_marked_as_readonly {
5258: my ($domain,$user,$what,$group) = @_;
5259: my $current_permissions = &get_portfile_permissions($domain,$user);
5260: my @readonly_files;
5261: my $cmp1=$what;
5262: if (ref($what)) { $cmp1=join('',@{$what}) };
5263: while (my ($file_name,$value) = each(%{$current_permissions})) {
5264: if (defined($group)) {
5265: if ($file_name !~ m-^\Q$group\E/-) {
5266: next;
5267: }
5268: }
5269: if (ref($value) eq "ARRAY"){
5270: foreach my $stored_what (@{$value}) {
5271: my $cmp2=$stored_what;
5272: if (ref($stored_what) eq 'ARRAY') {
5273: $cmp2=join('',@{$stored_what});
5274: }
5275: if ($cmp1 eq $cmp2) {
5276: push(@readonly_files, $file_name);
5277: last;
5278: } elsif (!defined($what)) {
5279: push(@readonly_files, $file_name);
5280: last;
5281: }
5282: }
5283: }
5284: }
5285: return @readonly_files;
5286: }
5287: #-----------------------------------------------------------Get Marked as Read Only Hash
5288:
5289: sub get_marked_as_readonly_hash {
5290: my ($current_permissions,$group,$what) = @_;
5291: my %readonly_files;
5292: while (my ($file_name,$value) = each(%{$current_permissions})) {
5293: if (defined($group)) {
5294: if ($file_name !~ m-^\Q$group\E/-) {
5295: next;
5296: }
5297: }
5298: if (ref($value) eq "ARRAY"){
5299: foreach my $stored_what (@{$value}) {
5300: if (ref($stored_what) eq 'ARRAY') {
5301: foreach my $lock_descriptor(@{$stored_what}) {
5302: if ($lock_descriptor eq 'graded') {
5303: $readonly_files{$file_name} = 'graded';
5304: } elsif ($lock_descriptor eq 'handback') {
5305: $readonly_files{$file_name} = 'handback';
5306: } else {
5307: if (!exists($readonly_files{$file_name})) {
5308: $readonly_files{$file_name} = 'locked';
5309: }
5310: }
5311: }
5312: }
5313: }
5314: }
5315: }
5316: return %readonly_files;
5317: }
5318: # ------------------------------------------------------------ Unmark as Read Only
5319:
5320: sub unmark_as_readonly {
5321: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5322: # for portfolio submissions, $what contains [$symb,$crsid]
5323: my ($domain,$user,$what,$file_name,$group) = @_;
5324: $file_name = &declutter_portfile($file_name);
5325: my $symb_crs = $what;
5326: if (ref($what)) { $symb_crs=join('',@$what); }
5327: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
5328: my ($tmp)=keys(%current_permissions);
5329: if ($tmp=~/^error:/) { undef(%current_permissions); }
5330: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
5331: foreach my $file (@readonly_files) {
5332: my $clean_file = &declutter_portfile($file);
5333: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
5334: my $current_locks = $current_permissions{$file};
5335: my @new_locks;
5336: my @del_keys;
5337: if (ref($current_locks) eq "ARRAY"){
5338: foreach my $locker (@{$current_locks}) {
5339: my $compare=$locker;
5340: if (ref($locker) eq 'ARRAY') {
5341: $compare=join('',@{$locker});
5342: if ($compare ne $symb_crs) {
5343: push(@new_locks, $locker);
5344: }
5345: }
5346: }
5347: if (scalar(@new_locks) > 0) {
5348: $current_permissions{$file} = \@new_locks;
5349: } else {
5350: push(@del_keys, $file);
5351: &del('file_permissions',\@del_keys, $domain, $user);
5352: delete($current_permissions{$file});
5353: }
5354: }
5355: }
5356: &put('file_permissions',\%current_permissions,$domain,$user);
5357: return;
5358: }
5359:
5360: # ------------------------------------------------------------ Directory lister
5361:
5362: sub dirlist {
5363: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5364:
5365: $uri=~s/^\///;
5366: $uri=~s/\/$//;
5367: my ($udom, $uname);
5368: (undef,$udom,$uname)=split(/\//,$uri);
5369: if(defined($userdomain)) {
5370: $udom = $userdomain;
5371: }
5372: if(defined($username)) {
5373: $uname = $username;
5374: }
5375:
5376: my $dirRoot = $perlvar{'lonDocRoot'};
5377: if(defined($alternateDirectoryRoot)) {
5378: $dirRoot = $alternateDirectoryRoot;
5379: $dirRoot =~ s/\/$//;
5380: }
5381:
5382: if($udom) {
5383: if($uname) {
5384: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5385: &homeserver($uname,$udom));
5386: my @listing_results;
5387: if ($listing eq 'unknown_cmd') {
5388: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5389: &homeserver($uname,$udom));
5390: @listing_results = split(/:/,$listing);
5391: } else {
5392: @listing_results = map { &unescape($_); } split(/:/,$listing);
5393: }
5394: return @listing_results;
5395: } elsif(!defined($alternateDirectoryRoot)) {
5396: my %allusers;
5397: foreach my $tryserver (keys(%libserv)) {
5398: if($hostdom{$tryserver} eq $udom) {
5399: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5400: $udom, $tryserver);
5401: my @listing_results;
5402: if ($listing eq 'unknown_cmd') {
5403: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5404: $udom, $tryserver);
5405: @listing_results = split(/:/,$listing);
5406: } else {
5407: @listing_results =
5408: map { &unescape($_); } split(/:/,$listing);
5409: }
5410: if ($listing_results[0] ne 'no_such_dir' &&
5411: $listing_results[0] ne 'empty' &&
5412: $listing_results[0] ne 'con_lost') {
5413: foreach my $line (@listing_results) {
5414: my ($entry) = split(/&/,$line,2);
5415: $allusers{$entry} = 1;
5416: }
5417: }
5418: }
5419: }
5420: my $alluserstr='';
5421: foreach my $user (sort(keys(%allusers))) {
5422: $alluserstr.=$user.'&user:';
5423: }
5424: $alluserstr=~s/:$//;
5425: return split(/:/,$alluserstr);
5426: } else {
5427: return ('missing user name');
5428: }
5429: } elsif(!defined($alternateDirectoryRoot)) {
5430: my $tryserver;
5431: my %alldom=();
5432: foreach $tryserver (keys(%libserv)) {
5433: $alldom{$hostdom{$tryserver}}=1;
5434: }
5435: my $alldomstr='';
5436: foreach my $domain (sort(keys(%alldom))) {
5437: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
5438: }
5439: $alldomstr=~s/:$//;
5440: return split(/:/,$alldomstr);
5441: } else {
5442: return ('missing domain');
5443: }
5444: }
5445:
5446: # --------------------------------------------- GetFileTimestamp
5447: # This function utilizes dirlist and returns the date stamp for
5448: # when it was last modified. It will also return an error of -1
5449: # if an error occurs
5450:
5451: ##
5452: ## FIXME: This subroutine assumes its caller knows something about the
5453: ## directory structure of the home server for the student ($root).
5454: ## Not a good assumption to make. Since this is for looking up files
5455: ## in user directories, the full path should be constructed by lond, not
5456: ## whatever machine we request data from.
5457: ##
5458: sub GetFileTimestamp {
5459: my ($studentDomain,$studentName,$filename,$root)=@_;
5460: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5461: $studentName = &LONCAPA::clean_username($studentName);
5462: my $subdir=$studentName.'__';
5463: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5464: my $proname="$studentDomain/$subdir/$studentName";
5465: $proname .= '/'.$filename;
5466: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5467: $studentName, $root);
5468: my @stats = split('&', $fileStat);
5469: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5470: # @stats contains first the filename, then the stat output
5471: return $stats[10]; # so this is 10 instead of 9.
5472: } else {
5473: return -1;
5474: }
5475: }
5476:
5477: sub stat_file {
5478: my ($uri) = @_;
5479: $uri = &clutter_with_no_wrapper($uri);
5480:
5481: my ($udom,$uname,$file,$dir);
5482: if ($uri =~ m-^/(uploaded|editupload)/-) {
5483: ($udom,$uname,$file) =
5484: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
5485: $file = 'userfiles/'.$file;
5486: $dir = &propath($udom,$uname);
5487: }
5488: if ($uri =~ m-^/res/-) {
5489: ($udom,$uname) =
5490: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
5491: $file = $uri;
5492: }
5493:
5494: if (!$udom || !$uname || !$file) {
5495: # unable to handle the uri
5496: return ();
5497: }
5498:
5499: my ($result) = &dirlist($file,$udom,$uname,$dir);
5500: my @stats = split('&', $result);
5501:
5502: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5503: shift(@stats); #filename is first
5504: return @stats;
5505: }
5506: return ();
5507: }
5508:
5509: # -------------------------------------------------------- Value of a Condition
5510:
5511: # gets the value of a specific preevaluated condition
5512: # stored in the string $env{user.state.<cid>}
5513: # or looks up a condition reference in the bighash and if if hasn't
5514: # already been evaluated recurses into docondval to get the value of
5515: # the condition, then memoizing it to
5516: # $env{user.state.<cid>.<condition>}
5517: sub directcondval {
5518: my $number=shift;
5519: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5520: &Apache::lonuserstate::evalstate();
5521: }
5522: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5523: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5524: } elsif ($number =~ /^_/) {
5525: my $sub_condition;
5526: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5527: &GDBM_READER(),0640)) {
5528: $sub_condition=$bighash{'conditions'.$number};
5529: untie(%bighash);
5530: }
5531: my $value = &docondval($sub_condition);
5532: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5533: return $value;
5534: }
5535: if ($env{'user.state.'.$env{'request.course.id'}}) {
5536: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5537: } else {
5538: return 2;
5539: }
5540: }
5541:
5542: # get the collection of conditions for this resource
5543: sub condval {
5544: my $condidx=shift;
5545: my $allpathcond='';
5546: foreach my $cond (split(/\|/,$condidx)) {
5547: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5548: $allpathcond.=
5549: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5550: }
5551: }
5552: $allpathcond=~s/\|$//;
5553: return &docondval($allpathcond);
5554: }
5555:
5556: #evaluates an expression of conditions
5557: sub docondval {
5558: my ($allpathcond) = @_;
5559: my $result=0;
5560: if ($env{'request.course.id'}
5561: && defined($allpathcond)) {
5562: my $operand='|';
5563: my @stack;
5564: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5565: if ($chunk eq '(') {
5566: push @stack,($operand,$result);
5567: } elsif ($chunk eq ')') {
5568: my $before=pop @stack;
5569: if (pop @stack eq '&') {
5570: $result=$result>$before?$before:$result;
5571: } else {
5572: $result=$result>$before?$result:$before;
5573: }
5574: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5575: $operand=$chunk;
5576: } else {
5577: my $new=directcondval($chunk);
5578: if ($operand eq '&') {
5579: $result=$result>$new?$new:$result;
5580: } else {
5581: $result=$result>$new?$result:$new;
5582: }
5583: }
5584: }
5585: }
5586: return $result;
5587: }
5588:
5589: # ---------------------------------------------------- Devalidate courseresdata
5590:
5591: sub devalidatecourseresdata {
5592: my ($coursenum,$coursedomain)=@_;
5593: my $hashid=$coursenum.':'.$coursedomain;
5594: &devalidate_cache_new('courseres',$hashid);
5595: }
5596:
5597:
5598: # --------------------------------------------------- Course Resourcedata Query
5599:
5600: sub get_courseresdata {
5601: my ($coursenum,$coursedomain)=@_;
5602: my $coursehom=&homeserver($coursenum,$coursedomain);
5603: my $hashid=$coursenum.':'.$coursedomain;
5604: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5605: my %dumpreply;
5606: unless (defined($cached)) {
5607: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5608: $result=\%dumpreply;
5609: my ($tmp) = keys(%dumpreply);
5610: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5611: &do_cache_new('courseres',$hashid,$result,600);
5612: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5613: return $tmp;
5614: } elsif ($tmp =~ /^(error)/) {
5615: $result=undef;
5616: &do_cache_new('courseres',$hashid,$result,600);
5617: }
5618: }
5619: return $result;
5620: }
5621:
5622: sub devalidateuserresdata {
5623: my ($uname,$udom)=@_;
5624: my $hashid="$udom:$uname";
5625: &devalidate_cache_new('userres',$hashid);
5626: }
5627:
5628: sub get_userresdata {
5629: my ($uname,$udom)=@_;
5630: #most student don\'t have any data set, check if there is some data
5631: if (&EXT_cache_status($udom,$uname)) { return undef; }
5632:
5633: my $hashid="$udom:$uname";
5634: my ($result,$cached)=&is_cached_new('userres',$hashid);
5635: if (!defined($cached)) {
5636: my %resourcedata=&dump('resourcedata',$udom,$uname);
5637: $result=\%resourcedata;
5638: &do_cache_new('userres',$hashid,$result,600);
5639: }
5640: my ($tmp)=keys(%$result);
5641: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5642: return $result;
5643: }
5644: #error 2 occurs when the .db doesn't exist
5645: if ($tmp!~/error: 2 /) {
5646: &logthis("<font color=\"blue\">WARNING:".
5647: " Trying to get resource data for ".
5648: $uname." at ".$udom.": ".
5649: $tmp."</font>");
5650: } elsif ($tmp=~/error: 2 /) {
5651: #&EXT_cache_set($udom,$uname);
5652: &do_cache_new('userres',$hashid,undef,600);
5653: undef($tmp); # not really an error so don't send it back
5654: }
5655: return $tmp;
5656: }
5657:
5658: sub resdata {
5659: my ($name,$domain,$type,@which)=@_;
5660: my $result;
5661: if ($type eq 'course') {
5662: $result=&get_courseresdata($name,$domain);
5663: } elsif ($type eq 'user') {
5664: $result=&get_userresdata($name,$domain);
5665: }
5666: if (!ref($result)) { return $result; }
5667: foreach my $item (@which) {
5668: if (defined($result->{$item})) {
5669: return $result->{$item};
5670: }
5671: }
5672: return undef;
5673: }
5674:
5675: #
5676: # EXT resource caching routines
5677: #
5678:
5679: sub clear_EXT_cache_status {
5680: &delenv('cache.EXT.');
5681: }
5682:
5683: sub EXT_cache_status {
5684: my ($target_domain,$target_user) = @_;
5685: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5686: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
5687: # We know already the user has no data
5688: return 1;
5689: } else {
5690: return 0;
5691: }
5692: }
5693:
5694: sub EXT_cache_set {
5695: my ($target_domain,$target_user) = @_;
5696: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5697: #&appenv($cachename => time);
5698: }
5699:
5700: # --------------------------------------------------------- Value of a Variable
5701: sub EXT {
5702:
5703: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5704: unless ($varname) { return ''; }
5705: #get real user name/domain, courseid and symb
5706: my $courseid;
5707: my $publicuser;
5708: if ($symbparm) {
5709: $symbparm=&get_symb_from_alias($symbparm);
5710: }
5711: if (!($uname && $udom)) {
5712: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
5713: if (!$symbparm) { $symbparm=$cursymb; }
5714: } else {
5715: $courseid=$env{'request.course.id'};
5716: }
5717: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5718: my $rest;
5719: if (defined($therest[0])) {
5720: $rest=join('.',@therest);
5721: } else {
5722: $rest='';
5723: }
5724:
5725: my $qualifierrest=$qualifier;
5726: if ($rest) { $qualifierrest.='.'.$rest; }
5727: my $spacequalifierrest=$space;
5728: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
5729: if ($realm eq 'user') {
5730: # --------------------------------------------------------------- user.resource
5731: if ($space eq 'resource') {
5732: if ( (defined($Apache::lonhomework::parsing_a_problem)
5733: || defined($Apache::lonhomework::parsing_a_task))
5734: &&
5735: ($symbparm eq &symbread()) ) {
5736: # if we are in the middle of processing the resource the
5737: # get the value we are planning on committing
5738: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5739: return $Apache::lonhomework::results{$qualifierrest};
5740: } else {
5741: return $Apache::lonhomework::history{$qualifierrest};
5742: }
5743: } else {
5744: my %restored;
5745: if ($publicuser || $env{'request.state'} eq 'construct') {
5746: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5747: } else {
5748: %restored=&restore($symbparm,$courseid,$udom,$uname);
5749: }
5750: return $restored{$qualifierrest};
5751: }
5752: # ----------------------------------------------------------------- user.access
5753: } elsif ($space eq 'access') {
5754: # FIXME - not supporting calls for a specific user
5755: return &allowed($qualifier,$rest);
5756: # ------------------------------------------ user.preferences, user.environment
5757: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
5758: if (($uname eq $env{'user.name'}) &&
5759: ($udom eq $env{'user.domain'})) {
5760: return $env{join('.',('environment',$qualifierrest))};
5761: } else {
5762: my %returnhash;
5763: if (!$publicuser) {
5764: %returnhash=&userenvironment($udom,$uname,
5765: $qualifierrest);
5766: }
5767: return $returnhash{$qualifierrest};
5768: }
5769: # ----------------------------------------------------------------- user.course
5770: } elsif ($space eq 'course') {
5771: # FIXME - not supporting calls for a specific user
5772: return $env{join('.',('request.course',$qualifier))};
5773: # ------------------------------------------------------------------- user.role
5774: } elsif ($space eq 'role') {
5775: # FIXME - not supporting calls for a specific user
5776: my ($role,$where)=split(/\./,$env{'request.role'});
5777: if ($qualifier eq 'value') {
5778: return $role;
5779: } elsif ($qualifier eq 'extent') {
5780: return $where;
5781: }
5782: # ----------------------------------------------------------------- user.domain
5783: } elsif ($space eq 'domain') {
5784: return $udom;
5785: # ------------------------------------------------------------------- user.name
5786: } elsif ($space eq 'name') {
5787: return $uname;
5788: # ---------------------------------------------------- Any other user namespace
5789: } else {
5790: my %reply;
5791: if (!$publicuser) {
5792: %reply=&get($space,[$qualifierrest],$udom,$uname);
5793: }
5794: return $reply{$qualifierrest};
5795: }
5796: } elsif ($realm eq 'query') {
5797: # ---------------------------------------------- pull stuff out of query string
5798: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5799: [$spacequalifierrest]);
5800: return $env{'form.'.$spacequalifierrest};
5801: } elsif ($realm eq 'request') {
5802: # ------------------------------------------------------------- request.browser
5803: if ($space eq 'browser') {
5804: if ($qualifier eq 'textremote') {
5805: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
5806: return 1;
5807: } else {
5808: return 0;
5809: }
5810: } else {
5811: return $env{'browser.'.$qualifier};
5812: }
5813: # ------------------------------------------------------------ request.filename
5814: } else {
5815: return $env{'request.'.$spacequalifierrest};
5816: }
5817: } elsif ($realm eq 'course') {
5818: # ---------------------------------------------------------- course.description
5819: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
5820: } elsif ($realm eq 'resource') {
5821:
5822: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
5823: if (!$symbparm) { $symbparm=&symbread(); }
5824: }
5825:
5826: if ($space eq 'title') {
5827: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
5828: return &gettitle($symbparm);
5829: }
5830:
5831: if ($space eq 'map') {
5832: my ($map) = &decode_symb($symbparm);
5833: return &symbread($map);
5834: }
5835:
5836: my ($section, $group, @groups);
5837: my ($courselevelm,$courselevel);
5838: if ($symbparm && defined($courseid) &&
5839: $courseid eq $env{'request.course.id'}) {
5840:
5841: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
5842:
5843: # ----------------------------------------------------- Cascading lookup scheme
5844: my $symbp=$symbparm;
5845: my $mapp=&deversion((&decode_symb($symbp))[0]);
5846:
5847: my $symbparm=$symbp.'.'.$spacequalifierrest;
5848: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
5849:
5850: if (($env{'user.name'} eq $uname) &&
5851: ($env{'user.domain'} eq $udom)) {
5852: $section=$env{'request.course.sec'};
5853: @groups = split(/:/,$env{'request.course.groups'});
5854: @groups=&sort_course_groups($courseid,@groups);
5855: } else {
5856: if (! defined($usection)) {
5857: $section=&getsection($udom,$uname,$courseid);
5858: } else {
5859: $section = $usection;
5860: }
5861: @groups = &get_users_groups($udom,$uname,$courseid);
5862: }
5863:
5864: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
5865: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
5866: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
5867:
5868: $courselevel=$courseid.'.'.$spacequalifierrest;
5869: my $courselevelr=$courseid.'.'.$symbparm;
5870: $courselevelm=$courseid.'.'.$mapparm;
5871:
5872: # ----------------------------------------------------------- first, check user
5873:
5874: my $userreply=&resdata($uname,$udom,'user',
5875: ($courselevelr,$courselevelm,
5876: $courselevel));
5877: if (defined($userreply)) { return $userreply; }
5878:
5879: # ------------------------------------------------ second, check some of course
5880: my $coursereply;
5881: if (@groups > 0) {
5882: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
5883: $mapparm,$spacequalifierrest);
5884: if (defined($coursereply)) { return $coursereply; }
5885: }
5886:
5887: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5888: $env{'course.'.$courseid.'.domain'},
5889: 'course',
5890: ($seclevelr,$seclevelm,$seclevel,
5891: $courselevelr));
5892: if (defined($coursereply)) { return $coursereply; }
5893:
5894: # ------------------------------------------------------ third, check map parms
5895: my %parmhash=();
5896: my $thisparm='';
5897: if (tie(%parmhash,'GDBM_File',
5898: $env{'request.course.fn'}.'_parms.db',
5899: &GDBM_READER(),0640)) {
5900: $thisparm=$parmhash{$symbparm};
5901: untie(%parmhash);
5902: }
5903: if ($thisparm) { return $thisparm; }
5904: }
5905: # ------------------------------------------ fourth, look in resource metadata
5906:
5907: $spacequalifierrest=~s/\./\_/;
5908: my $filename;
5909: if (!$symbparm) { $symbparm=&symbread(); }
5910: if ($symbparm) {
5911: $filename=(&decode_symb($symbparm))[2];
5912: } else {
5913: $filename=$env{'request.filename'};
5914: }
5915: my $metadata=&metadata($filename,$spacequalifierrest);
5916: if (defined($metadata)) { return $metadata; }
5917: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
5918: if (defined($metadata)) { return $metadata; }
5919:
5920: # ---------------------------------------------- fourth, look in rest pf course
5921: if ($symbparm && defined($courseid) &&
5922: $courseid eq $env{'request.course.id'}) {
5923: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5924: $env{'course.'.$courseid.'.domain'},
5925: 'course',
5926: ($courselevelm,$courselevel));
5927: if (defined($coursereply)) { return $coursereply; }
5928: }
5929: # ------------------------------------------------------------------ Cascade up
5930: unless ($space eq '0') {
5931: my @parts=split(/_/,$space);
5932: my $id=pop(@parts);
5933: my $part=join('_',@parts);
5934: if ($part eq '') { $part='0'; }
5935: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
5936: $symbparm,$udom,$uname,$section,1);
5937: if (defined($partgeneral)) { return $partgeneral; }
5938: }
5939: if ($recurse) { return undef; }
5940: my $pack_def=&packages_tab_default($filename,$varname);
5941: if (defined($pack_def)) { return $pack_def; }
5942:
5943: # ---------------------------------------------------- Any other user namespace
5944: } elsif ($realm eq 'environment') {
5945: # ----------------------------------------------------------------- environment
5946: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
5947: return $env{'environment.'.$spacequalifierrest};
5948: } else {
5949: if ($uname eq 'anonymous' && $udom eq '') {
5950: return '';
5951: }
5952: my %returnhash=&userenvironment($udom,$uname,
5953: $spacequalifierrest);
5954: return $returnhash{$spacequalifierrest};
5955: }
5956: } elsif ($realm eq 'system') {
5957: # ----------------------------------------------------------------- system.time
5958: if ($space eq 'time') {
5959: return time;
5960: }
5961: } elsif ($realm eq 'server') {
5962: # ----------------------------------------------------------------- system.time
5963: if ($space eq 'name') {
5964: return $ENV{'SERVER_NAME'};
5965: }
5966: }
5967: return '';
5968: }
5969:
5970: sub check_group_parms {
5971: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
5972: my @groupitems = ();
5973: my $resultitem;
5974: my @levels = ($symbparm,$mapparm,$what);
5975: foreach my $group (@{$groups}) {
5976: foreach my $level (@levels) {
5977: my $item = $courseid.'.['.$group.'].'.$level;
5978: push(@groupitems,$item);
5979: }
5980: }
5981: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
5982: $env{'course.'.$courseid.'.domain'},
5983: 'course',@groupitems);
5984: return $coursereply;
5985: }
5986:
5987: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
5988: my ($courseid,@groups) = @_;
5989: @groups = sort(@groups);
5990: return @groups;
5991: }
5992:
5993: sub packages_tab_default {
5994: my ($uri,$varname)=@_;
5995: my (undef,$part,$name)=split(/\./,$varname);
5996:
5997: my (@extension,@specifics,$do_default);
5998: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
5999: my ($pack_type,$pack_part)=split(/_/,$package,2);
6000: if ($pack_type eq 'default') {
6001: $do_default=1;
6002: } elsif ($pack_type eq 'extension') {
6003: push(@extension,[$package,$pack_type,$pack_part]);
6004: } else {
6005: push(@specifics,[$package,$pack_type,$pack_part]);
6006: }
6007: }
6008: # first look for a package that matches the requested part id
6009: foreach my $package (@specifics) {
6010: my (undef,$pack_type,$pack_part)=@{$package};
6011: next if ($pack_part ne $part);
6012: if (defined($packagetab{"$pack_type&$name&default"})) {
6013: return $packagetab{"$pack_type&$name&default"};
6014: }
6015: }
6016: # look for any possible matching non extension_ package
6017: foreach my $package (@specifics) {
6018: my (undef,$pack_type,$pack_part)=@{$package};
6019: if (defined($packagetab{"$pack_type&$name&default"})) {
6020: return $packagetab{"$pack_type&$name&default"};
6021: }
6022: if ($pack_type eq 'part') { $pack_part='0'; }
6023: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6024: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
6025: }
6026: }
6027: # look for any posible extension_ match
6028: foreach my $package (@extension) {
6029: my ($package,$pack_type)=@{$package};
6030: if (defined($packagetab{"$pack_type&$name&default"})) {
6031: return $packagetab{"$pack_type&$name&default"};
6032: }
6033: if (defined($packagetab{$package."&$name&default"})) {
6034: return $packagetab{$package."&$name&default"};
6035: }
6036: }
6037: # look for a global default setting
6038: if ($do_default && defined($packagetab{"default&$name&default"})) {
6039: return $packagetab{"default&$name&default"};
6040: }
6041: return undef;
6042: }
6043:
6044: sub add_prefix_and_part {
6045: my ($prefix,$part)=@_;
6046: my $keyroot;
6047: if (defined($prefix) && $prefix !~ /^__/) {
6048: # prefix that has a part already
6049: $keyroot=$prefix;
6050: } elsif (defined($prefix)) {
6051: # prefix that is missing a part
6052: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6053: } else {
6054: # no prefix at all
6055: if (defined($part)) { $keyroot='_'.$part; }
6056: }
6057: return $keyroot;
6058: }
6059:
6060: # ---------------------------------------------------------------- Get metadata
6061:
6062: my %metaentry;
6063: sub metadata {
6064: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
6065: $uri=&declutter($uri);
6066: # if it is a non metadata possible uri return quickly
6067: if (($uri eq '') ||
6068: (($uri =~ m|^/*adm/|) &&
6069: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
6070: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
6071: ($uri =~ m|home/$match_username/public_html/|)) {
6072: return undef;
6073: }
6074: my $filename=$uri;
6075: $uri=~s/\.meta$//;
6076: #
6077: # Is the metadata already cached?
6078: # Look at timestamp of caching
6079: # Everything is cached by the main uri, libraries are never directly cached
6080: #
6081: if (!defined($liburi)) {
6082: my ($result,$cached)=&is_cached_new('meta',$uri);
6083: if (defined($cached)) { return $result->{':'.$what}; }
6084: }
6085: {
6086: #
6087: # Is this a recursive call for a library?
6088: #
6089: # if (! exists($metacache{$uri})) {
6090: # $metacache{$uri}={};
6091: # }
6092: if ($liburi) {
6093: $liburi=&declutter($liburi);
6094: $filename=$liburi;
6095: } else {
6096: &devalidate_cache_new('meta',$uri);
6097: undef(%metaentry);
6098: }
6099: my %metathesekeys=();
6100: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
6101: my $metastring;
6102: if ($uri !~ m -^(editupload)/-) {
6103: my $file=&filelocation('',&clutter($filename));
6104: #push(@{$metaentry{$uri.'.file'}},$file);
6105: $metastring=&getfile($file);
6106: }
6107: my $parser=HTML::LCParser->new(\$metastring);
6108: my $token;
6109: undef %metathesekeys;
6110: while ($token=$parser->get_token) {
6111: if ($token->[0] eq 'S') {
6112: if (defined($token->[2]->{'package'})) {
6113: #
6114: # This is a package - get package info
6115: #
6116: my $package=$token->[2]->{'package'};
6117: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6118: if (defined($token->[2]->{'id'})) {
6119: $keyroot.='_'.$token->[2]->{'id'};
6120: }
6121: if ($metaentry{':packages'}) {
6122: $metaentry{':packages'}.=','.$package.$keyroot;
6123: } else {
6124: $metaentry{':packages'}=$package.$keyroot;
6125: }
6126: foreach my $pack_entry (keys(%packagetab)) {
6127: my $part=$keyroot;
6128: $part=~s/^\_//;
6129: if ($pack_entry=~/^\Q$package\E\&/ ||
6130: $pack_entry=~/^\Q$package\E_0\&/) {
6131: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
6132: # ignore package.tab specified default values
6133: # here &package_tab_default() will fetch those
6134: if ($subp eq 'default') { next; }
6135: my $value=$packagetab{$pack_entry};
6136: my $unikey;
6137: if ($pack =~ /_0$/) {
6138: $unikey='parameter_0_'.$name;
6139: $part=0;
6140: } else {
6141: $unikey='parameter'.$keyroot.'_'.$name;
6142: }
6143: if ($subp eq 'display') {
6144: $value.=' [Part: '.$part.']';
6145: }
6146: $metaentry{':'.$unikey.'.part'}=$part;
6147: $metathesekeys{$unikey}=1;
6148: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6149: $metaentry{':'.$unikey.'.'.$subp}=$value;
6150: }
6151: if (defined($metaentry{':'.$unikey.'.default'})) {
6152: $metaentry{':'.$unikey}=
6153: $metaentry{':'.$unikey.'.default'};
6154: }
6155: }
6156: }
6157: } else {
6158: #
6159: # This is not a package - some other kind of start tag
6160: #
6161: my $entry=$token->[1];
6162: my $unikey;
6163: if ($entry eq 'import') {
6164: $unikey='';
6165: } else {
6166: $unikey=$entry;
6167: }
6168: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6169:
6170: if (defined($token->[2]->{'id'})) {
6171: $unikey.='_'.$token->[2]->{'id'};
6172: }
6173:
6174: if ($entry eq 'import') {
6175: #
6176: # Importing a library here
6177: #
6178: if ($depthcount<20) {
6179: my $location=$parser->get_text('/import');
6180: my $dir=$filename;
6181: $dir=~s|[^/]*$||;
6182: $location=&filelocation($dir,$location);
6183: my $metadata =
6184: &metadata($uri,'keys', $location,$unikey,
6185: $depthcount+1);
6186: foreach my $meta (split(',',$metadata)) {
6187: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6188: $metathesekeys{$meta}=1;
6189: }
6190: }
6191: } else {
6192:
6193: if (defined($token->[2]->{'name'})) {
6194: $unikey.='_'.$token->[2]->{'name'};
6195: }
6196: $metathesekeys{$unikey}=1;
6197: foreach my $param (@{$token->[3]}) {
6198: $metaentry{':'.$unikey.'.'.$param} =
6199: $token->[2]->{$param};
6200: }
6201: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
6202: my $default=$metaentry{':'.$unikey.'.default'};
6203: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6204: # only ws inside the tag, and not in default, so use default
6205: # as value
6206: $metaentry{':'.$unikey}=$default;
6207: } else {
6208: # either something interesting inside the tag or default
6209: # uninteresting
6210: $metaentry{':'.$unikey}=$internaltext;
6211: }
6212: # end of not-a-package not-a-library import
6213: }
6214: # end of not-a-package start tag
6215: }
6216: # the next is the end of "start tag"
6217: }
6218: }
6219: my ($extension) = ($uri =~ /\.(\w+)$/);
6220: foreach my $key (keys(%packagetab)) {
6221: #no specific packages #how's our extension
6222: if ($key!~/^extension_\Q$extension\E&/) { next; }
6223: &metadata_create_package_def($uri,$key,'extension_'.$extension,
6224: \%metathesekeys);
6225: }
6226: if (!exists($metaentry{':packages'})) {
6227: foreach my $key (keys(%packagetab)) {
6228: #no specific packages well let's get default then
6229: if ($key!~/^default&/) { next; }
6230: &metadata_create_package_def($uri,$key,'default',
6231: \%metathesekeys);
6232: }
6233: }
6234: # are there custom rights to evaluate
6235: if ($metaentry{':copyright'} eq 'custom') {
6236:
6237: #
6238: # Importing a rights file here
6239: #
6240: unless ($depthcount) {
6241: my $location=$metaentry{':customdistributionfile'};
6242: my $dir=$filename;
6243: $dir=~s|[^/]*$||;
6244: $location=&filelocation($dir,$location);
6245: my $rights_metadata =
6246: &metadata($uri,'keys',$location,'_rights',
6247: $depthcount+1);
6248: foreach my $rights (split(',',$rights_metadata)) {
6249: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6250: $metathesekeys{$rights}=1;
6251: }
6252: }
6253: }
6254: # uniqifiy package listing
6255: my %seen;
6256: my @uniq_packages =
6257: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6258: $metaentry{':packages'} = join(',',@uniq_packages);
6259:
6260: $metaentry{':keys'} = join(',',keys(%metathesekeys));
6261: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6262: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
6263: &do_cache_new('meta',$uri,\%metaentry,60*60);
6264: # this is the end of "was not already recently cached
6265: }
6266: return $metaentry{':'.$what};
6267: }
6268:
6269: sub metadata_create_package_def {
6270: my ($uri,$key,$package,$metathesekeys)=@_;
6271: my ($pack,$name,$subp)=split(/\&/,$key);
6272: if ($subp eq 'default') { next; }
6273:
6274: if (defined($metaentry{':packages'})) {
6275: $metaentry{':packages'}.=','.$package;
6276: } else {
6277: $metaentry{':packages'}=$package;
6278: }
6279: my $value=$packagetab{$key};
6280: my $unikey;
6281: $unikey='parameter_0_'.$name;
6282: $metaentry{':'.$unikey.'.part'}=0;
6283: $$metathesekeys{$unikey}=1;
6284: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6285: $metaentry{':'.$unikey.'.'.$subp}=$value;
6286: }
6287: if (defined($metaentry{':'.$unikey.'.default'})) {
6288: $metaentry{':'.$unikey}=
6289: $metaentry{':'.$unikey.'.default'};
6290: }
6291: }
6292:
6293: sub metadata_generate_part0 {
6294: my ($metadata,$metacache,$uri) = @_;
6295: my %allnames;
6296: foreach my $metakey (keys(%$metadata)) {
6297: if ($metakey=~/^parameter\_(.*)/) {
6298: my $part=$$metacache{':'.$metakey.'.part'};
6299: my $name=$$metacache{':'.$metakey.'.name'};
6300: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
6301: $allnames{$name}=$part;
6302: }
6303: }
6304: }
6305: foreach my $name (keys(%allnames)) {
6306: $$metadata{"parameter_0_$name"}=1;
6307: my $key=":parameter_0_$name";
6308: $$metacache{"$key.part"}='0';
6309: $$metacache{"$key.name"}=$name;
6310: $$metacache{"$key.type"}=$$metacache{':parameter_'.
6311: $allnames{$name}.'_'.$name.
6312: '.type'};
6313: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
6314: '.display'};
6315: my $expr='[Part: '.$allnames{$name}.']';
6316: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
6317: $$metacache{"$key.display"}=$olddis;
6318: }
6319: }
6320:
6321: # ------------------------------------------------------ Devalidate title cache
6322:
6323: sub devalidate_title_cache {
6324: my ($url)=@_;
6325: if (!$env{'request.course.id'}) { return; }
6326: my $symb=&symbread($url);
6327: if (!$symb) { return; }
6328: my $key=$env{'request.course.id'}."\0".$symb;
6329: &devalidate_cache_new('title',$key);
6330: }
6331:
6332: # ------------------------------------------------- Get the title of a resource
6333:
6334: sub gettitle {
6335: my $urlsymb=shift;
6336: my $symb=&symbread($urlsymb);
6337: if ($symb) {
6338: my $key=$env{'request.course.id'}."\0".$symb;
6339: my ($result,$cached)=&is_cached_new('title',$key);
6340: if (defined($cached)) {
6341: return $result;
6342: }
6343: my ($map,$resid,$url)=&decode_symb($symb);
6344: my $title='';
6345: my %bighash;
6346: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6347: &GDBM_READER(),0640)) {
6348: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6349: $title=$bighash{'title_'.$mapid.'.'.$resid};
6350: untie %bighash;
6351: }
6352: $title=~s/\&colon\;/\:/gs;
6353: if ($title) {
6354: return &do_cache_new('title',$key,$title,600);
6355: }
6356: $urlsymb=$url;
6357: }
6358: my $title=&metadata($urlsymb,'title');
6359: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6360: return $title;
6361: }
6362:
6363: sub get_slot {
6364: my ($which,$cnum,$cdom)=@_;
6365: if (!$cnum || !$cdom) {
6366: (undef,my $courseid)=&whichuser();
6367: $cdom=$env{'course.'.$courseid.'.domain'};
6368: $cnum=$env{'course.'.$courseid.'.num'};
6369: }
6370: my $key=join("\0",'slots',$cdom,$cnum,$which);
6371: my %slotinfo;
6372: if (exists($remembered{$key})) {
6373: $slotinfo{$which} = $remembered{$key};
6374: } else {
6375: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6376: &Apache::lonhomework::showhash(%slotinfo);
6377: my ($tmp)=keys(%slotinfo);
6378: if ($tmp=~/^error:/) { return (); }
6379: $remembered{$key} = $slotinfo{$which};
6380: }
6381: if (ref($slotinfo{$which}) eq 'HASH') {
6382: return %{$slotinfo{$which}};
6383: }
6384: return $slotinfo{$which};
6385: }
6386: # ------------------------------------------------- Update symbolic store links
6387:
6388: sub symblist {
6389: my ($mapname,%newhash)=@_;
6390: $mapname=&deversion(&declutter($mapname));
6391: my %hash;
6392: if (($env{'request.course.fn'}) && (%newhash)) {
6393: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6394: &GDBM_WRCREAT(),0640)) {
6395: foreach my $url (keys %newhash) {
6396: next if ($url eq 'last_known'
6397: && $env{'form.no_update_last_known'});
6398: $hash{declutter($url)}=&encode_symb($mapname,
6399: $newhash{$url}->[1],
6400: $newhash{$url}->[0]);
6401: }
6402: if (untie(%hash)) {
6403: return 'ok';
6404: }
6405: }
6406: }
6407: return 'error';
6408: }
6409:
6410: # --------------------------------------------------------------- Verify a symb
6411:
6412: sub symbverify {
6413: my ($symb,$thisurl)=@_;
6414: my $thisfn=$thisurl;
6415: $thisfn=&declutter($thisfn);
6416: # direct jump to resource in page or to a sequence - will construct own symbs
6417: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6418: # check URL part
6419: my ($map,$resid,$url)=&decode_symb($symb);
6420:
6421: unless ($url eq $thisfn) { return 0; }
6422:
6423: $symb=&symbclean($symb);
6424: $thisurl=&deversion($thisurl);
6425: $thisfn=&deversion($thisfn);
6426:
6427: my %bighash;
6428: my $okay=0;
6429:
6430: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6431: &GDBM_READER(),0640)) {
6432: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6433: unless ($ids) {
6434: $ids=$bighash{'ids_/'.$thisurl};
6435: }
6436: if ($ids) {
6437: # ------------------------------------------------------------------- Has ID(s)
6438: foreach my $id (split(/\,/,$ids)) {
6439: my ($mapid,$resid)=split(/\./,$id);
6440: if (
6441: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6442: eq $symb) {
6443: if (($env{'request.role.adv'}) ||
6444: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
6445: $okay=1;
6446: }
6447: }
6448: }
6449: }
6450: untie(%bighash);
6451: }
6452: return $okay;
6453: }
6454:
6455: # --------------------------------------------------------------- Clean-up symb
6456:
6457: sub symbclean {
6458: my $symb=shift;
6459: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6460: # remove version from map
6461: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6462:
6463: # remove version from URL
6464: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6465:
6466: # remove wrapper
6467:
6468: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6469: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6470: return $symb;
6471: }
6472:
6473: # ---------------------------------------------- Split symb to find map and url
6474:
6475: sub encode_symb {
6476: my ($map,$resid,$url)=@_;
6477: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6478: }
6479:
6480: sub decode_symb {
6481: my $symb=shift;
6482: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6483: my ($map,$resid,$url)=split(/___/,$symb);
6484: return (&fixversion($map),$resid,&fixversion($url));
6485: }
6486:
6487: sub fixversion {
6488: my $fn=shift;
6489: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6490: my %bighash;
6491: my $uri=&clutter($fn);
6492: my $key=$env{'request.course.id'}.'_'.$uri;
6493: # is this cached?
6494: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6495: if (defined($cached)) { return $result; }
6496: # unfortunately not cached, or expired
6497: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6498: &GDBM_READER(),0640)) {
6499: if ($bighash{'version_'.$uri}) {
6500: my $version=$bighash{'version_'.$uri};
6501: unless (($version eq 'mostrecent') ||
6502: ($version==&getversion($uri))) {
6503: $uri=~s/\.(\w+)$/\.$version\.$1/;
6504: }
6505: }
6506: untie %bighash;
6507: }
6508: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6509: }
6510:
6511: sub deversion {
6512: my $url=shift;
6513: $url=~s/\.\d+\.(\w+)$/\.$1/;
6514: return $url;
6515: }
6516:
6517: # ------------------------------------------------------ Return symb list entry
6518:
6519: sub symbread {
6520: my ($thisfn,$donotrecurse)=@_;
6521: my $cache_str='request.symbread.cached.'.$thisfn;
6522: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6523: # no filename provided? try from environment
6524: unless ($thisfn) {
6525: if ($env{'request.symb'}) {
6526: return $env{$cache_str}=&symbclean($env{'request.symb'});
6527: }
6528: $thisfn=$env{'request.filename'};
6529: }
6530: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6531: # is that filename actually a symb? Verify, clean, and return
6532: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6533: if (&symbverify($thisfn,$1)) {
6534: return $env{$cache_str}=&symbclean($thisfn);
6535: }
6536: }
6537: $thisfn=declutter($thisfn);
6538: my %hash;
6539: my %bighash;
6540: my $syval='';
6541: if (($env{'request.course.fn'}) && ($thisfn)) {
6542: my $targetfn = $thisfn;
6543: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6544: $targetfn = 'adm/wrapper/'.$thisfn;
6545: }
6546: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6547: $targetfn=$1;
6548: }
6549: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6550: &GDBM_READER(),0640)) {
6551: $syval=$hash{$targetfn};
6552: untie(%hash);
6553: }
6554: # ---------------------------------------------------------- There was an entry
6555: if ($syval) {
6556: #unless ($syval=~/\_\d+$/) {
6557: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6558: #&appenv('request.ambiguous' => $thisfn);
6559: #return $env{$cache_str}='';
6560: #}
6561: #$syval.=$1;
6562: #}
6563: } else {
6564: # ------------------------------------------------------- Was not in symb table
6565: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6566: &GDBM_READER(),0640)) {
6567: # ---------------------------------------------- Get ID(s) for current resource
6568: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6569: unless ($ids) {
6570: $ids=$bighash{'ids_/'.$thisfn};
6571: }
6572: unless ($ids) {
6573: # alias?
6574: $ids=$bighash{'mapalias_'.$thisfn};
6575: }
6576: if ($ids) {
6577: # ------------------------------------------------------------------- Has ID(s)
6578: my @possibilities=split(/\,/,$ids);
6579: if ($#possibilities==0) {
6580: # ----------------------------------------------- There is only one possibility
6581: my ($mapid,$resid)=split(/\./,$ids);
6582: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6583: $resid,$thisfn);
6584: } elsif (!$donotrecurse) {
6585: # ------------------------------------------ There is more than one possibility
6586: my $realpossible=0;
6587: foreach my $id (@possibilities) {
6588: my $file=$bighash{'src_'.$id};
6589: if (&allowed('bre',$file)) {
6590: my ($mapid,$resid)=split(/\./,$id);
6591: if ($bighash{'map_type_'.$mapid} ne 'page') {
6592: $realpossible++;
6593: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6594: $resid,$thisfn);
6595: }
6596: }
6597: }
6598: if ($realpossible!=1) { $syval=''; }
6599: } else {
6600: $syval='';
6601: }
6602: }
6603: untie(%bighash)
6604: }
6605: }
6606: if ($syval) {
6607: return $env{$cache_str}=$syval;
6608: }
6609: }
6610: &appenv('request.ambiguous' => $thisfn);
6611: return $env{$cache_str}='';
6612: }
6613:
6614: # ---------------------------------------------------------- Return random seed
6615:
6616: sub numval {
6617: my $txt=shift;
6618: $txt=~tr/A-J/0-9/;
6619: $txt=~tr/a-j/0-9/;
6620: $txt=~tr/K-T/0-9/;
6621: $txt=~tr/k-t/0-9/;
6622: $txt=~tr/U-Z/0-5/;
6623: $txt=~tr/u-z/0-5/;
6624: $txt=~s/\D//g;
6625: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6626: return int($txt);
6627: }
6628:
6629: sub numval2 {
6630: my $txt=shift;
6631: $txt=~tr/A-J/0-9/;
6632: $txt=~tr/a-j/0-9/;
6633: $txt=~tr/K-T/0-9/;
6634: $txt=~tr/k-t/0-9/;
6635: $txt=~tr/U-Z/0-5/;
6636: $txt=~tr/u-z/0-5/;
6637: $txt=~s/\D//g;
6638: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6639: my $total;
6640: foreach my $val (@txts) { $total+=$val; }
6641: if ($_64bit) { if ($total > 2**32) { return -1; } }
6642: return int($total);
6643: }
6644:
6645: sub numval3 {
6646: use integer;
6647: my $txt=shift;
6648: $txt=~tr/A-J/0-9/;
6649: $txt=~tr/a-j/0-9/;
6650: $txt=~tr/K-T/0-9/;
6651: $txt=~tr/k-t/0-9/;
6652: $txt=~tr/U-Z/0-5/;
6653: $txt=~tr/u-z/0-5/;
6654: $txt=~s/\D//g;
6655: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6656: my $total;
6657: foreach my $val (@txts) { $total+=$val; }
6658: if ($_64bit) { $total=(($total<<32)>>32); }
6659: return $total;
6660: }
6661:
6662: sub digest {
6663: my ($data)=@_;
6664: my $digest=&Digest::MD5::md5($data);
6665: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6666: my ($e,$f);
6667: {
6668: use integer;
6669: $e=($a+$b);
6670: $f=($c+$d);
6671: if ($_64bit) {
6672: $e=(($e<<32)>>32);
6673: $f=(($f<<32)>>32);
6674: }
6675: }
6676: if (wantarray) {
6677: return ($e,$f);
6678: } else {
6679: my $g;
6680: {
6681: use integer;
6682: $g=($e+$f);
6683: if ($_64bit) {
6684: $g=(($g<<32)>>32);
6685: }
6686: }
6687: return $g;
6688: }
6689: }
6690:
6691: sub latest_rnd_algorithm_id {
6692: return '64bit5';
6693: }
6694:
6695: sub get_rand_alg {
6696: my ($courseid)=@_;
6697: if (!$courseid) { $courseid=(&whichuser())[1]; }
6698: if ($courseid) {
6699: return $env{"course.$courseid.rndseed"};
6700: }
6701: return &latest_rnd_algorithm_id();
6702: }
6703:
6704: sub validCODE {
6705: my ($CODE)=@_;
6706: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6707: return 0;
6708: }
6709:
6710: sub getCODE {
6711: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
6712: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6713: defined($Apache::lonhomework::parsing_a_task) ) &&
6714: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
6715: return $Apache::lonhomework::history{'resource.CODE'};
6716: }
6717: return undef;
6718: }
6719:
6720: sub rndseed {
6721: my ($symb,$courseid,$domain,$username)=@_;
6722:
6723: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
6724: if (!$symb) {
6725: unless ($symb=$wsymb) { return time; }
6726: }
6727: if (!$courseid) { $courseid=$wcourseid; }
6728: if (!$domain) { $domain=$wdomain; }
6729: if (!$username) { $username=$wusername }
6730: my $which=&get_rand_alg();
6731:
6732: if (defined(&getCODE())) {
6733: if ($which eq '64bit5') {
6734: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6735: } elsif ($which eq '64bit4') {
6736: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6737: } else {
6738: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6739: }
6740: } elsif ($which eq '64bit5') {
6741: return &rndseed_64bit5($symb,$courseid,$domain,$username);
6742: } elsif ($which eq '64bit4') {
6743: return &rndseed_64bit4($symb,$courseid,$domain,$username);
6744: } elsif ($which eq '64bit3') {
6745: return &rndseed_64bit3($symb,$courseid,$domain,$username);
6746: } elsif ($which eq '64bit2') {
6747: return &rndseed_64bit2($symb,$courseid,$domain,$username);
6748: } elsif ($which eq '64bit') {
6749: return &rndseed_64bit($symb,$courseid,$domain,$username);
6750: }
6751: return &rndseed_32bit($symb,$courseid,$domain,$username);
6752: }
6753:
6754: sub rndseed_32bit {
6755: my ($symb,$courseid,$domain,$username)=@_;
6756: {
6757: use integer;
6758: my $symbchck=unpack("%32C*",$symb) << 27;
6759: my $symbseed=numval($symb) << 22;
6760: my $namechck=unpack("%32C*",$username) << 17;
6761: my $nameseed=numval($username) << 12;
6762: my $domainseed=unpack("%32C*",$domain) << 7;
6763: my $courseseed=unpack("%32C*",$courseid);
6764: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6765: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6766: #&logthis("rndseed :$num:$symb");
6767: if ($_64bit) { $num=(($num<<32)>>32); }
6768: return $num;
6769: }
6770: }
6771:
6772: sub rndseed_64bit {
6773: my ($symb,$courseid,$domain,$username)=@_;
6774: {
6775: use integer;
6776: my $symbchck=unpack("%32S*",$symb) << 21;
6777: my $symbseed=numval($symb) << 10;
6778: my $namechck=unpack("%32S*",$username);
6779:
6780: my $nameseed=numval($username) << 21;
6781: my $domainseed=unpack("%32S*",$domain) << 10;
6782: my $courseseed=unpack("%32S*",$courseid);
6783:
6784: my $num1=$symbchck+$symbseed+$namechck;
6785: my $num2=$nameseed+$domainseed+$courseseed;
6786: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6787: #&logthis("rndseed :$num:$symb");
6788: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6789: return "$num1,$num2";
6790: }
6791: }
6792:
6793: sub rndseed_64bit2 {
6794: my ($symb,$courseid,$domain,$username)=@_;
6795: {
6796: use integer;
6797: # strings need to be an even # of cahracters long, it it is odd the
6798: # last characters gets thrown away
6799: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6800: my $symbseed=numval($symb) << 10;
6801: my $namechck=unpack("%32S*",$username.' ');
6802:
6803: my $nameseed=numval($username) << 21;
6804: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6805: my $courseseed=unpack("%32S*",$courseid.' ');
6806:
6807: my $num1=$symbchck+$symbseed+$namechck;
6808: my $num2=$nameseed+$domainseed+$courseseed;
6809: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6810: #&logthis("rndseed :$num:$symb");
6811: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6812: return "$num1,$num2";
6813: }
6814: }
6815:
6816: sub rndseed_64bit3 {
6817: my ($symb,$courseid,$domain,$username)=@_;
6818: {
6819: use integer;
6820: # strings need to be an even # of cahracters long, it it is odd the
6821: # last characters gets thrown away
6822: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6823: my $symbseed=numval2($symb) << 10;
6824: my $namechck=unpack("%32S*",$username.' ');
6825:
6826: my $nameseed=numval2($username) << 21;
6827: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6828: my $courseseed=unpack("%32S*",$courseid.' ');
6829:
6830: my $num1=$symbchck+$symbseed+$namechck;
6831: my $num2=$nameseed+$domainseed+$courseseed;
6832: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6833: #&logthis("rndseed :$num1:$num2:$_64bit");
6834: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6835:
6836: return "$num1:$num2";
6837: }
6838: }
6839:
6840: sub rndseed_64bit4 {
6841: my ($symb,$courseid,$domain,$username)=@_;
6842: {
6843: use integer;
6844: # strings need to be an even # of cahracters long, it it is odd the
6845: # last characters gets thrown away
6846: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6847: my $symbseed=numval3($symb) << 10;
6848: my $namechck=unpack("%32S*",$username.' ');
6849:
6850: my $nameseed=numval3($username) << 21;
6851: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6852: my $courseseed=unpack("%32S*",$courseid.' ');
6853:
6854: my $num1=$symbchck+$symbseed+$namechck;
6855: my $num2=$nameseed+$domainseed+$courseseed;
6856: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6857: #&logthis("rndseed :$num1:$num2:$_64bit");
6858: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6859:
6860: return "$num1:$num2";
6861: }
6862: }
6863:
6864: sub rndseed_64bit5 {
6865: my ($symb,$courseid,$domain,$username)=@_;
6866: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
6867: return "$num1:$num2";
6868: }
6869:
6870: sub rndseed_CODE_64bit {
6871: my ($symb,$courseid,$domain,$username)=@_;
6872: {
6873: use integer;
6874: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6875: my $symbseed=numval2($symb);
6876: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6877: my $CODEseed=numval(&getCODE());
6878: my $courseseed=unpack("%32S*",$courseid.' ');
6879: my $num1=$symbseed+$CODEchck;
6880: my $num2=$CODEseed+$courseseed+$symbchck;
6881: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6882: #&logthis("rndseed :$num1:$num2:$symb");
6883: if ($_64bit) { $num1=(($num1<<32)>>32); }
6884: if ($_64bit) { $num2=(($num2<<32)>>32); }
6885: return "$num1:$num2";
6886: }
6887: }
6888:
6889: sub rndseed_CODE_64bit4 {
6890: my ($symb,$courseid,$domain,$username)=@_;
6891: {
6892: use integer;
6893: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6894: my $symbseed=numval3($symb);
6895: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6896: my $CODEseed=numval3(&getCODE());
6897: my $courseseed=unpack("%32S*",$courseid.' ');
6898: my $num1=$symbseed+$CODEchck;
6899: my $num2=$CODEseed+$courseseed+$symbchck;
6900: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6901: #&logthis("rndseed :$num1:$num2:$symb");
6902: if ($_64bit) { $num1=(($num1<<32)>>32); }
6903: if ($_64bit) { $num2=(($num2<<32)>>32); }
6904: return "$num1:$num2";
6905: }
6906: }
6907:
6908: sub rndseed_CODE_64bit5 {
6909: my ($symb,$courseid,$domain,$username)=@_;
6910: my $code = &getCODE();
6911: my ($num1,$num2)=&digest("$symb,$courseid,$code");
6912: return "$num1:$num2";
6913: }
6914:
6915: sub setup_random_from_rndseed {
6916: my ($rndseed)=@_;
6917: if ($rndseed =~/([,:])/) {
6918: my ($num1,$num2)=split(/[,:]/,$rndseed);
6919: &Math::Random::random_set_seed(abs($num1),abs($num2));
6920: } else {
6921: &Math::Random::random_set_seed_from_phrase($rndseed);
6922: }
6923: }
6924:
6925: sub latest_receipt_algorithm_id {
6926: return 'receipt2';
6927: }
6928:
6929: sub recunique {
6930: my $fucourseid=shift;
6931: my $unique;
6932: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6933: $unique=$env{"course.$fucourseid.internal.encseed"};
6934: } else {
6935: $unique=$perlvar{'lonReceipt'};
6936: }
6937: return unpack("%32C*",$unique);
6938: }
6939:
6940: sub recprefix {
6941: my $fucourseid=shift;
6942: my $prefix;
6943: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6944: $prefix=$env{"course.$fucourseid.internal.encpref"};
6945: } else {
6946: $prefix=$perlvar{'lonHostID'};
6947: }
6948: return unpack("%32C*",$prefix);
6949: }
6950:
6951: sub ireceipt {
6952: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
6953: my $cuname=unpack("%32C*",$funame);
6954: my $cudom=unpack("%32C*",$fudom);
6955: my $cucourseid=unpack("%32C*",$fucourseid);
6956: my $cusymb=unpack("%32C*",$fusymb);
6957: my $cunique=&recunique($fucourseid);
6958: my $cpart=unpack("%32S*",$part);
6959: my $return =&recprefix($fucourseid).'-';
6960: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
6961: $env{'request.state'} eq 'construct') {
6962: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
6963:
6964: $return.= ($cunique%$cuname+
6965: $cunique%$cudom+
6966: $cusymb%$cuname+
6967: $cusymb%$cudom+
6968: $cucourseid%$cuname+
6969: $cucourseid%$cudom+
6970: $cpart%$cuname+
6971: $cpart%$cudom);
6972: } else {
6973: $return.= ($cunique%$cuname+
6974: $cunique%$cudom+
6975: $cusymb%$cuname+
6976: $cusymb%$cudom+
6977: $cucourseid%$cuname+
6978: $cucourseid%$cudom);
6979: }
6980: return $return;
6981: }
6982:
6983: sub receipt {
6984: my ($part)=@_;
6985: my ($symb,$courseid,$domain,$name) = &whichuser();
6986: return &ireceipt($name,$domain,$courseid,$symb,$part);
6987: }
6988:
6989: sub whichuser {
6990: my ($passedsymb)=@_;
6991: my ($symb,$courseid,$domain,$name,$publicuser);
6992: if (defined($env{'form.grade_symb'})) {
6993: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
6994: my $allowed=&allowed('vgr',$tmp_courseid);
6995: if (!$allowed &&
6996: exists($env{'request.course.sec'}) &&
6997: $env{'request.course.sec'} !~ /^\s*$/) {
6998: $allowed=&allowed('vgr',$tmp_courseid.
6999: '/'.$env{'request.course.sec'});
7000: }
7001: if ($allowed) {
7002: ($symb)=&get_env_multiple('form.grade_symb');
7003: $courseid=$tmp_courseid;
7004: ($domain)=&get_env_multiple('form.grade_domain');
7005: ($name)=&get_env_multiple('form.grade_username');
7006: return ($symb,$courseid,$domain,$name,$publicuser);
7007: }
7008: }
7009: if (!$passedsymb) {
7010: $symb=&symbread();
7011: } else {
7012: $symb=$passedsymb;
7013: }
7014: $courseid=$env{'request.course.id'};
7015: $domain=$env{'user.domain'};
7016: $name=$env{'user.name'};
7017: if ($name eq 'public' && $domain eq 'public') {
7018: if (!defined($env{'form.username'})) {
7019: $env{'form.username'}.=time.rand(10000000);
7020: }
7021: $name.=$env{'form.username'};
7022: }
7023: return ($symb,$courseid,$domain,$name,$publicuser);
7024:
7025: }
7026:
7027: # ------------------------------------------------------------ Serves up a file
7028: # returns either the contents of the file or
7029: # -1 if the file doesn't exist
7030: #
7031: # if the target is a file that was uploaded via DOCS,
7032: # a check will be made to see if a current copy exists on the local server,
7033: # if it does this will be served, otherwise a copy will be retrieved from
7034: # the home server for the course and stored in /home/httpd/html/userfiles on
7035: # the local server.
7036:
7037: sub getfile {
7038: my ($file) = @_;
7039: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7040: &repcopy($file);
7041: return &readfile($file);
7042: }
7043:
7044: sub repcopy_userfile {
7045: my ($file)=@_;
7046: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7047: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
7048: my ($cdom,$cnum,$filename) =
7049: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
7050: my ($info,$rtncode);
7051: my $uri="/uploaded/$cdom/$cnum/$filename";
7052: if (-e "$file") {
7053: my @fileinfo = stat($file);
7054: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
7055: if ($lwpresp ne 'ok') {
7056: if ($rtncode eq '404') {
7057: unlink($file);
7058: }
7059: #my $ua=new LWP::UserAgent;
7060: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
7061: #my $response=$ua->request($request);
7062: #if ($response->is_success()) {
7063: # return $response->content;
7064: # } else {
7065: # return -1;
7066: # }
7067: return -1;
7068: }
7069: if ($info < $fileinfo[9]) {
7070: return 'ok';
7071: }
7072: $info = '';
7073: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
7074: if ($lwpresp ne 'ok') {
7075: return -1;
7076: }
7077: } else {
7078: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
7079: if ($lwpresp ne 'ok') {
7080: my $ua=new LWP::UserAgent;
7081: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
7082: my $response=$ua->request($request);
7083: if ($response->is_success()) {
7084: $info=$response->content;
7085: } else {
7086: return -1;
7087: }
7088: }
7089: my @parts = ($cdom,$cnum);
7090: if ($filename =~ m|^(.+)/[^/]+$|) {
7091: push @parts, split(/\//,$1);
7092: }
7093: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7094: foreach my $part (@parts) {
7095: $path .= '/'.$part;
7096: if (!-e $path) {
7097: mkdir($path,0770);
7098: }
7099: }
7100: }
7101: open(FILE,">$file");
7102: print FILE $info;
7103: close(FILE);
7104: return 'ok';
7105: }
7106:
7107: sub tokenwrapper {
7108: my $uri=shift;
7109: $uri=~s|^http\://([^/]+)||;
7110: $uri=~s|^/||;
7111: $env{'user.environment'}=~/\/([^\/]+)\.id/;
7112: my $token=$1;
7113: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7114: if ($udom && $uname && $file) {
7115: $file=~s|(\?\.*)*$||;
7116: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
7117: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
7118: (($uri=~/\?/)?'&':'?').'token='.$token.
7119: '&tokenissued='.$perlvar{'lonHostID'};
7120: } else {
7121: return '/adm/notfound.html';
7122: }
7123: }
7124:
7125: sub getuploaded {
7126: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7127: $uri=~s/^\///;
7128: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
7129: my $ua=new LWP::UserAgent;
7130: my $request=new HTTP::Request($reqtype,$uri);
7131: my $response=$ua->request($request);
7132: $$rtncode = $response->code;
7133: if (! $response->is_success()) {
7134: return 'failed';
7135: }
7136: if ($reqtype eq 'HEAD') {
7137: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
7138: } elsif ($reqtype eq 'GET') {
7139: $$info = $response->content;
7140: }
7141: return 'ok';
7142: }
7143:
7144: sub readfile {
7145: my $file = shift;
7146: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7147: my $fh;
7148: open($fh,"<$file");
7149: my $a='';
7150: while (my $line = <$fh>) { $a .= $line; }
7151: return $a;
7152: }
7153:
7154: sub filelocation {
7155: my ($dir,$file) = @_;
7156: my $location;
7157: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
7158:
7159: if ($file =~ m-^/adm/-) {
7160: $file=~s-^/adm/wrapper/-/-;
7161: $file=~s-^/adm/coursedocs/showdoc/-/-;
7162: }
7163: if ($file=~m:^/~:) { # is a contruction space reference
7164: $location = $file;
7165: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
7166: } elsif ($file=~m{^/home/$match_username/public_html/}) {
7167: # is a correct contruction space reference
7168: $location = $file;
7169: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
7170: my ($udom,$uname,$filename)=
7171: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
7172: my $home=&homeserver($uname,$udom);
7173: my $is_me=0;
7174: my @ids=¤t_machine_ids();
7175: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7176: if ($is_me) {
7177: $location=&propath($udom,$uname).
7178: '/userfiles/'.$filename;
7179: } else {
7180: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7181: $udom.'/'.$uname.'/'.$filename;
7182: }
7183: } else {
7184: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7185: $file=~s:^/res/:/:;
7186: if ( !( $file =~ m:^/:) ) {
7187: $location = $dir. '/'.$file;
7188: } else {
7189: $location = '/home/httpd/html/res'.$file;
7190: }
7191: }
7192: $location=~s://+:/:g; # remove duplicate /
7193: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7194: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7195: return $location;
7196: }
7197:
7198: sub hreflocation {
7199: my ($dir,$file)=@_;
7200: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
7201: $file=filelocation($dir,$file);
7202: } elsif ($file=~m-^/adm/-) {
7203: $file=~s-^/adm/wrapper/-/-;
7204: $file=~s-^/adm/coursedocs/showdoc/-/-;
7205: }
7206: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7207: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7208: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7209: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
7210: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7211: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
7212: -/uploaded/$1/$2/-x;
7213: }
7214: return $file;
7215: }
7216:
7217: sub current_machine_domains {
7218: my $hostname=$hostname{$perlvar{'lonHostID'}};
7219: my @domains;
7220: while( my($id, $name) = each(%hostname)) {
7221: # &logthis("-$id-$name-$hostname-");
7222: if ($hostname eq $name) {
7223: push(@domains,$hostdom{$id});
7224: }
7225: }
7226: return @domains;
7227: }
7228:
7229: sub current_machine_ids {
7230: my $hostname=$hostname{$perlvar{'lonHostID'}};
7231: my @ids;
7232: while( my($id, $name) = each(%hostname)) {
7233: # &logthis("-$id-$name-$hostname-");
7234: if ($hostname eq $name) {
7235: push(@ids,$id);
7236: }
7237: }
7238: return @ids;
7239: }
7240:
7241: # ------------------------------------------------------------- Declutters URLs
7242:
7243: sub declutter {
7244: my $thisfn=shift;
7245: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7246: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7247: $thisfn=~s/^\///;
7248: $thisfn=~s|^adm/wrapper/||;
7249: $thisfn=~s|^adm/coursedocs/showdoc/||;
7250: $thisfn=~s/^res\///;
7251: $thisfn=~s/\?.+$//;
7252: return $thisfn;
7253: }
7254:
7255: # ------------------------------------------------------------- Clutter up URLs
7256:
7257: sub clutter {
7258: my $thisfn='/'.&declutter(shift);
7259: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
7260: $thisfn='/res'.$thisfn;
7261: }
7262: if ($thisfn !~m|/adm|) {
7263: if ($thisfn =~ m|/ext/|) {
7264: $thisfn='/adm/wrapper'.$thisfn;
7265: } else {
7266: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7267: my $embstyle=&Apache::loncommon::fileembstyle($ext);
7268: if ($embstyle eq 'ssi'
7269: || ($embstyle eq 'hdn')
7270: || ($embstyle eq 'rat')
7271: || ($embstyle eq 'prv')
7272: || ($embstyle eq 'ign')) {
7273: #do nothing with these
7274: } elsif (($embstyle eq 'img')
7275: || ($embstyle eq 'emb')
7276: || ($embstyle eq 'wrp')) {
7277: $thisfn='/adm/wrapper'.$thisfn;
7278: } elsif ($embstyle eq 'unk'
7279: && $thisfn!~/\.(sequence|page)$/) {
7280: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
7281: } else {
7282: # &logthis("Got a blank emb style");
7283: }
7284: }
7285: }
7286: return $thisfn;
7287: }
7288:
7289: sub clutter_with_no_wrapper {
7290: my $uri = &clutter(shift);
7291: if ($uri =~ m-^/adm/-) {
7292: $uri =~ s-^/adm/wrapper/-/-;
7293: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7294: }
7295: return $uri;
7296: }
7297:
7298: sub freeze_escape {
7299: my ($value)=@_;
7300: if (ref($value)) {
7301: $value=&nfreeze($value);
7302: return '__FROZEN__'.&escape($value);
7303: }
7304: return &escape($value);
7305: }
7306:
7307:
7308: sub thaw_unescape {
7309: my ($value)=@_;
7310: if ($value =~ /^__FROZEN__/) {
7311: substr($value,0,10,undef);
7312: $value=&unescape($value);
7313: return &thaw($value);
7314: }
7315: return &unescape($value);
7316: }
7317:
7318: sub correct_line_ends {
7319: my ($result)=@_;
7320: $$result =~s/\r\n/\n/mg;
7321: $$result =~s/\r/\n/mg;
7322: }
7323: # ================================================================ Main Program
7324:
7325: sub goodbye {
7326: &logthis("Starting Shut down");
7327: #not converted to using infrastruture and probably shouldn't be
7328: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
7329: #converted
7330: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7331: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7332: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7333: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
7334: #1.1 only
7335: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7336: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7337: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7338: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7339: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7340: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7341: &logthis(sprintf("%-20s is %s",'hits',$hits));
7342: &flushcourselogs();
7343: &logthis("Shutting down");
7344: }
7345:
7346: BEGIN {
7347: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7348: unless ($readit) {
7349: {
7350: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7351: %perlvar = (%perlvar,%{$configvars});
7352: }
7353:
7354: # ------------------------------------------------------------ Read domain file
7355: {
7356: %domaindescription = ();
7357: %domain_auth_def = ();
7358: %domain_auth_arg_def = ();
7359: my $fh;
7360: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
7361: while (my $line = <$fh>) {
7362: next if ($line =~ /^(\#|\s*$)/);
7363: # next if /^\#/;
7364: chomp $line;
7365: my ($domain, $domain_description, $def_auth, $def_auth_arg,
7366: $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
7367: $domain_auth_def{$domain}=$def_auth;
7368: $domain_auth_arg_def{$domain}=$def_auth_arg;
7369: $domaindescription{$domain}=$domain_description;
7370: $domain_lang_def{$domain}=$def_lang;
7371: $domain_city{$domain}=$city;
7372: $domain_longi{$domain}=$longi;
7373: $domain_lati{$domain}=$lati;
7374: $domain_primary{$domain}=$primary;
7375:
7376: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
7377: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
7378: }
7379: }
7380: close ($fh);
7381: }
7382:
7383:
7384: # ------------------------------------------------------------- Read hosts file
7385: {
7386: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7387:
7388: while (my $configline=<$config>) {
7389: next if ($configline =~ /^(\#|\s*$)/);
7390: chomp($configline);
7391: my ($id,$domain,$role,$name)=split(/:/,$configline);
7392: $name=~s/\s//g;
7393: if ($id && $domain && $role && $name) {
7394: $hostname{$id}=$name;
7395: $hostdom{$id}=$domain;
7396: if ($role eq 'library') { $libserv{$id}=$name; }
7397: }
7398: }
7399: close($config);
7400: # FIXME: dev server don't want this, production servers _do_ want this
7401: #&get_iphost();
7402: }
7403:
7404: sub get_iphost {
7405: if (%iphost) { return %iphost; }
7406: my %name_to_ip;
7407: foreach my $id (keys(%hostname)) {
7408: my $name=$hostname{$id};
7409: my $ip;
7410: if (!exists($name_to_ip{$name})) {
7411: $ip = gethostbyname($name);
7412: if (!$ip || length($ip) ne 4) {
7413: &logthis("Skipping host $id name $name no IP found\n");
7414: next;
7415: }
7416: $ip=inet_ntoa($ip);
7417: $name_to_ip{$name} = $ip;
7418: } else {
7419: $ip = $name_to_ip{$name};
7420: }
7421: push(@{$iphost{$ip}},$id);
7422: }
7423: return %iphost;
7424: }
7425:
7426: # ------------------------------------------------------ Read spare server file
7427: {
7428: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7429:
7430: while (my $configline=<$config>) {
7431: chomp($configline);
7432: if ($configline) {
7433: my ($host,$type) = split(':',$configline,2);
7434: if (!defined($type) || $type eq '') { $type = 'default' };
7435: push(@{ $spareid{$type} }, $host);
7436: }
7437: }
7438: close($config);
7439: }
7440: # ------------------------------------------------------------ Read permissions
7441: {
7442: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7443:
7444: while (my $configline=<$config>) {
7445: chomp($configline);
7446: if ($configline) {
7447: my ($role,$perm)=split(/ /,$configline);
7448: if ($perm ne '') { $pr{$role}=$perm; }
7449: }
7450: }
7451: close($config);
7452: }
7453:
7454: # -------------------------------------------- Read plain texts for permissions
7455: {
7456: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7457:
7458: while (my $configline=<$config>) {
7459: chomp($configline);
7460: if ($configline) {
7461: my ($short,@plain)=split(/:/,$configline);
7462: %{$prp{$short}} = ();
7463: if (@plain > 0) {
7464: $prp{$short}{'std'} = $plain[0];
7465: for (my $i=1; $i<@plain; $i++) {
7466: $prp{$short}{'alt'.$i} = $plain[$i];
7467: }
7468: }
7469: }
7470: }
7471: close($config);
7472: }
7473:
7474: # ---------------------------------------------------------- Read package table
7475: {
7476: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7477:
7478: while (my $configline=<$config>) {
7479: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
7480: chomp($configline);
7481: my ($short,$plain)=split(/:/,$configline);
7482: my ($pack,$name)=split(/\&/,$short);
7483: if ($plain ne '') {
7484: $packagetab{$pack.'&'.$name.'&name'}=$name;
7485: $packagetab{$short}=$plain;
7486: }
7487: }
7488: close($config);
7489: }
7490:
7491: # ------------- set up temporary directory
7492: {
7493: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7494:
7495: }
7496:
7497: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7498: 'compress_threshold'=> 20_000,
7499: });
7500:
7501: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7502: $dumpcount=0;
7503:
7504: &logtouch();
7505: &logthis('<font color="yellow">INFO: Read configuration</font>');
7506: $readit=1;
7507: {
7508: use integer;
7509: my $test=(2**32)+1;
7510: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
7511: &logthis(" Detected 64bit platform ($_64bit)");
7512: }
7513: }
7514: }
7515:
7516: 1;
7517: __END__
7518:
7519: =pod
7520:
7521: =head1 NAME
7522:
7523: Apache::lonnet - Subroutines to ask questions about things in the network.
7524:
7525: =head1 SYNOPSIS
7526:
7527: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
7528:
7529: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7530:
7531: Common parameters:
7532:
7533: =over 4
7534:
7535: =item *
7536:
7537: $uname : an internal username (if $cname expecting a course Id specifically)
7538:
7539: =item *
7540:
7541: $udom : a domain (if $cdom expecting a course's domain specifically)
7542:
7543: =item *
7544:
7545: $symb : a resource instance identifier
7546:
7547: =item *
7548:
7549: $namespace : the name of a .db file that contains the data needed or
7550: being set.
7551:
7552: =back
7553:
7554: =head1 OVERVIEW
7555:
7556: lonnet provides subroutines which interact with the
7557: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7558: about classes, users, and resources.
7559:
7560: For many of these objects you can also use this to store data about
7561: them or modify them in various ways.
7562:
7563: =head2 Symbs
7564:
7565: To identify a specific instance of a resource, LON-CAPA uses symbols
7566: or "symbs"X<symb>. These identifiers are built from the URL of the
7567: map, the resource number of the resource in the map, and the URL of
7568: the resource itself. The latter is somewhat redundant, but might help
7569: if maps change.
7570:
7571: An example is
7572:
7573: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7574:
7575: The respective map entry is
7576:
7577: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7578: title="Problem 2">
7579: </resource>
7580:
7581: Symbs are used by the random number generator, as well as to store and
7582: restore data specific to a certain instance of for example a problem.
7583:
7584: =head2 Storing And Retrieving Data
7585:
7586: X<store()>X<cstore()>X<restore()>Three of the most important functions
7587: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7588: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7589: is is the non-critical message twin of cstore. These functions are for
7590: handlers to store a perl hash to a user's permanent data space in an
7591: easy manner, and to retrieve it again on another call. It is expected
7592: that a handler would use this once at the beginning to retrieve data,
7593: and then again once at the end to send only the new data back.
7594:
7595: The data is stored in the user's data directory on the user's
7596: homeserver under the ID of the course.
7597:
7598: The hash that is returned by restore will have all of the previous
7599: value for all of the elements of the hash.
7600:
7601: Example:
7602:
7603: #creating a hash
7604: my %hash;
7605: $hash{'foo'}='bar';
7606:
7607: #storing it
7608: &Apache::lonnet::cstore(\%hash);
7609:
7610: #changing a value
7611: $hash{'foo'}='notbar';
7612:
7613: #adding a new value
7614: $hash{'bar'}='foo';
7615: &Apache::lonnet::cstore(\%hash);
7616:
7617: #retrieving the hash
7618: my %history=&Apache::lonnet::restore();
7619:
7620: #print the hash
7621: foreach my $key (sort(keys(%history))) {
7622: print("\%history{$key} = $history{$key}");
7623: }
7624:
7625: Will print out:
7626:
7627: %history{1:foo} = bar
7628: %history{1:keys} = foo:timestamp
7629: %history{1:timestamp} = 990455579
7630: %history{2:bar} = foo
7631: %history{2:foo} = notbar
7632: %history{2:keys} = foo:bar:timestamp
7633: %history{2:timestamp} = 990455580
7634: %history{bar} = foo
7635: %history{foo} = notbar
7636: %history{timestamp} = 990455580
7637: %history{version} = 2
7638:
7639: Note that the special hash entries C<keys>, C<version> and
7640: C<timestamp> were added to the hash. C<version> will be equal to the
7641: total number of versions of the data that have been stored. The
7642: C<timestamp> attribute will be the UNIX time the hash was
7643: stored. C<keys> is available in every historical section to list which
7644: keys were added or changed at a specific historical revision of a
7645: hash.
7646:
7647: B<Warning>: do not store the hash that restore returns directly. This
7648: will cause a mess since it will restore the historical keys as if the
7649: were new keys. I.E. 1:foo will become 1:1:foo etc.
7650:
7651: Calling convention:
7652:
7653: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
7654: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
7655:
7656: For more detailed information, see lonnet specific documentation.
7657:
7658: =head1 RETURN MESSAGES
7659:
7660: =over 4
7661:
7662: =item * B<con_lost>: unable to contact remote host
7663:
7664: =item * B<con_delayed>: unable to contact remote host, message will be delivered
7665: when the connection is brought back up
7666:
7667: =item * B<con_failed>: unable to contact remote host and unable to save message
7668: for later delivery
7669:
7670: =item * B<error:>: an error a occured, a description of the error follows the :
7671:
7672: =item * B<no_such_host>: unable to fund a host associated with the user/domain
7673: that was requested
7674:
7675: =back
7676:
7677: =head1 PUBLIC SUBROUTINES
7678:
7679: =head2 Session Environment Functions
7680:
7681: =over 4
7682:
7683: =item *
7684: X<appenv()>
7685: B<appenv(%hash)>: the value of %hash is written to
7686: the user envirnoment file, and will be restored for each access this
7687: user makes during this session, also modifies the %env for the current
7688: process
7689:
7690: =item *
7691: X<delenv()>
7692: B<delenv($regexp)>: removes all items from the session
7693: environment file that matches the regular expression in $regexp. The
7694: values are also delted from the current processes %env.
7695:
7696: =item * get_env_multiple($name)
7697:
7698: gets $name from the %env hash, it seemlessly handles the cases where multiple
7699: values may be defined and end up as an array ref.
7700:
7701: returns an array of values
7702:
7703: =back
7704:
7705: =head2 User Information
7706:
7707: =over 4
7708:
7709: =item *
7710: X<queryauthenticate()>
7711: B<queryauthenticate($uname,$udom)>: try to determine user's current
7712: authentication scheme
7713:
7714: =item *
7715: X<authenticate()>
7716: B<authenticate($uname,$upass,$udom)>: try to
7717: authenticate user from domain's lib servers (first use the current
7718: one). C<$upass> should be the users password.
7719:
7720: =item *
7721: X<homeserver()>
7722: B<homeserver($uname,$udom)>: find the server which has
7723: the user's directory and files (there must be only one), this caches
7724: the answer, and also caches if there is a borken connection.
7725:
7726: =item *
7727: X<idget()>
7728: B<idget($udom,@ids)>: find the usernames behind a list of IDs
7729: (IDs are a unique resource in a domain, there must be only 1 ID per
7730: username, and only 1 username per ID in a specific domain) (returns
7731: hash: id=>name,id=>name)
7732:
7733: =item *
7734: X<idrget()>
7735: B<idrget($udom,@unames)>: find the IDs behind a list of
7736: usernames (returns hash: name=>id,name=>id)
7737:
7738: =item *
7739: X<idput()>
7740: B<idput($udom,%ids)>: store away a list of names and associated IDs
7741:
7742: =item *
7743: X<rolesinit()>
7744: B<rolesinit($udom,$username,$authhost)>: get user privileges
7745:
7746: =item *
7747: X<getsection()>
7748: B<getsection($udom,$uname,$cname)>: finds the section of student in the
7749: course $cname, return section name/number or '' for "not in course"
7750: and '-1' for "no section"
7751:
7752: =item *
7753: X<userenvironment()>
7754: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
7755: passed in @what from the requested user's environment, returns a hash
7756:
7757: =back
7758:
7759: =head2 User Roles
7760:
7761: =over 4
7762:
7763: =item *
7764:
7765: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
7766: F: full access
7767: U,I,K: authentication modes (cxx only)
7768: '': forbidden
7769: 1: user needs to choose course
7770: 2: browse allowed
7771: A: passphrase authentication needed
7772:
7773: =item *
7774:
7775: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
7776: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
7777: and course level
7778:
7779: =item *
7780:
7781: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
7782: explanation of a user role term
7783:
7784: =back
7785:
7786: =head2 User Modification
7787:
7788: =over 4
7789:
7790: =item *
7791:
7792: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
7793: user for the level given by URL. Optional start and end dates (leave empty
7794: string or zero for "no date")
7795:
7796: =item *
7797:
7798: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
7799: change a users, password, possible return values are: ok,
7800: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
7801: refused
7802:
7803: =item *
7804:
7805: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
7806:
7807: =item *
7808:
7809: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
7810: modify user
7811:
7812: =item *
7813:
7814: modifystudent
7815:
7816: modify a students enrollment and identification information.
7817: The course id is resolved based on the current users environment.
7818: This means the envoking user must be a course coordinator or otherwise
7819: associated with a course.
7820:
7821: This call is essentially a wrapper for lonnet::modifyuser and
7822: lonnet::modify_student_enrollment
7823:
7824: Inputs:
7825:
7826: =over 4
7827:
7828: =item B<$udom> Students loncapa domain
7829:
7830: =item B<$uname> Students loncapa login name
7831:
7832: =item B<$uid> Students id/student number
7833:
7834: =item B<$umode> Students authentication mode
7835:
7836: =item B<$upass> Students password
7837:
7838: =item B<$first> Students first name
7839:
7840: =item B<$middle> Students middle name
7841:
7842: =item B<$last> Students last name
7843:
7844: =item B<$gene> Students generation
7845:
7846: =item B<$usec> Students section in course
7847:
7848: =item B<$end> Unix time of the roles expiration
7849:
7850: =item B<$start> Unix time of the roles start date
7851:
7852: =item B<$forceid> If defined, allow $uid to be changed
7853:
7854: =item B<$desiredhome> server to use as home server for student
7855:
7856: =back
7857:
7858: =item *
7859:
7860: modify_student_enrollment
7861:
7862: Change a students enrollment status in a class. The environment variable
7863: 'role.request.course' must be defined for this function to proceed.
7864:
7865: Inputs:
7866:
7867: =over 4
7868:
7869: =item $udom, students domain
7870:
7871: =item $uname, students name
7872:
7873: =item $uid, students user id
7874:
7875: =item $first, students first name
7876:
7877: =item $middle
7878:
7879: =item $last
7880:
7881: =item $gene
7882:
7883: =item $usec
7884:
7885: =item $end
7886:
7887: =item $start
7888:
7889: =back
7890:
7891:
7892: =item *
7893:
7894: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
7895: custom role; give a custom role to a user for the level given by URL. Specify
7896: name and domain of role author, and role name
7897:
7898: =item *
7899:
7900: revokerole($udom,$uname,$url,$role) : revoke a role for url
7901:
7902: =item *
7903:
7904: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
7905:
7906: =back
7907:
7908: =head2 Course Infomation
7909:
7910: =over 4
7911:
7912: =item *
7913:
7914: coursedescription($courseid) : returns a hash of information about the
7915: specified course id, including all environment settings for the
7916: course, the description of the course will be in the hash under the
7917: key 'description'
7918:
7919: =item *
7920:
7921: resdata($name,$domain,$type,@which) : request for current parameter
7922: setting for a specific $type, where $type is either 'course' or 'user',
7923: @what should be a list of parameters to ask about. This routine caches
7924: answers for 5 minutes.
7925:
7926: =back
7927:
7928: =head2 Course Modification
7929:
7930: =over 4
7931:
7932: =item *
7933:
7934: writecoursepref($courseid,%prefs) : write preferences (environment
7935: database) for a course
7936:
7937: =item *
7938:
7939: createcourse($udom,$description,$url) : make/modify course
7940:
7941: =back
7942:
7943: =head2 Resource Subroutines
7944:
7945: =over 4
7946:
7947: =item *
7948:
7949: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
7950:
7951: =item *
7952:
7953: repcopy($filename) : subscribes to the requested file, and attempts to
7954: replicate from the owning library server, Might return
7955: 'unavailable', 'not_found', 'forbidden', 'ok', or
7956: 'bad_request', also attempts to grab the metadata for the
7957: resource. Expects the local filesystem pathname
7958: (/home/httpd/html/res/....)
7959:
7960: =back
7961:
7962: =head2 Resource Information
7963:
7964: =over 4
7965:
7966: =item *
7967:
7968: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
7969: a vairety of different possible values, $varname should be a request
7970: string, and the other parameters can be used to specify who and what
7971: one is asking about.
7972:
7973: Possible values for $varname are environment.lastname (or other item
7974: from the envirnment hash), user.name (or someother aspect about the
7975: user), resource.0.maxtries (or some other part and parameter of a
7976: resource)
7977:
7978: =item *
7979:
7980: directcondval($number) : get current value of a condition; reads from a state
7981: string
7982:
7983: =item *
7984:
7985: condval($condidx) : value of condition index based on state
7986:
7987: =item *
7988:
7989: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
7990: resource's metadata, $what should be either a specific key, or either
7991: 'keys' (to get a list of possible keys) or 'packages' to get a list of
7992: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
7993:
7994: this function automatically caches all requests
7995:
7996: =item *
7997:
7998: metadata_query($query,$custom,$customshow) : make a metadata query against the
7999: network of library servers; returns file handle of where SQL and regex results
8000: will be stored for query
8001:
8002: =item *
8003:
8004: symbread($filename) : return symbolic list entry (filename argument optional);
8005: returns the data handle
8006:
8007: =item *
8008:
8009: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
8010: a possible symb for the URL in $thisfn, and if is an encryypted
8011: resource that the user accessed using /enc/ returns a 1 on success, 0
8012: on failure, user must be in a course, as it assumes the existance of
8013: the course initial hash, and uses $env('request.course.id'}
8014:
8015:
8016: =item *
8017:
8018: symbclean($symb) : removes versions numbers from a symb, returns the
8019: cleaned symb
8020:
8021: =item *
8022:
8023: is_on_map($uri) : checks if the $uri is somewhere on the current
8024: course map, user must be in a course for it to work.
8025:
8026: =item *
8027:
8028: numval($salt) : return random seed value (addend for rndseed)
8029:
8030: =item *
8031:
8032: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8033: a random seed, all arguments are optional, if they aren't sent it uses the
8034: environment to derive them. Note: if symb isn't sent and it can't get one
8035: from &symbread it will use the current time as its return value
8036:
8037: =item *
8038:
8039: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8040: unfakeable, receipt
8041:
8042: =item *
8043:
8044: receipt() : API to ireceipt working off of env values; given out to users
8045:
8046: =item *
8047:
8048: countacc($url) : count the number of accesses to a given URL
8049:
8050: =item *
8051:
8052: 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
8053:
8054: =item *
8055:
8056: 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)
8057:
8058: =item *
8059:
8060: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
8061:
8062: =item *
8063:
8064: devalidate($symb) : devalidate temporary spreadsheet calculations,
8065: forcing spreadsheet to reevaluate the resource scores next time.
8066:
8067: =back
8068:
8069: =head2 Storing/Retreiving Data
8070:
8071: =over 4
8072:
8073: =item *
8074:
8075: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8076: for this url; hashref needs to be given and should be a \%hashname; the
8077: remaining args aren't required and if they aren't passed or are '' they will
8078: be derived from the env
8079:
8080: =item *
8081:
8082: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8083: uses critical subroutine
8084:
8085: =item *
8086:
8087: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8088: all args are optional
8089:
8090: =item *
8091:
8092: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8093: dumps the complete (or key matching regexp) namespace into a hash
8094: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8095: normally &store()ed into
8096:
8097: $range should be either an integer '100' (give me the first 100
8098: matching records)
8099: or be two integers sperated by a - with no spaces
8100: '30-50' (give me the 30th through the 50th matching
8101: records)
8102:
8103:
8104: =item *
8105:
8106: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8107: replaces a &store() version of data with a replacement set of data
8108: for a particular resource in a namespace passed in the $storehash hash
8109: reference
8110:
8111: =item *
8112:
8113: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8114: works very similar to store/cstore, but all data is stored in a
8115: temporary location and can be reset using tmpreset, $storehash should
8116: be a hash reference, returns nothing on success
8117:
8118: =item *
8119:
8120: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8121: similar to restore, but all data is stored in a temporary location and
8122: can be reset using tmpreset. Returns a hash of values on success,
8123: error string otherwise.
8124:
8125: =item *
8126:
8127: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8128: deltes all keys for $symb form the temporary storage hash.
8129:
8130: =item *
8131:
8132: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8133: reference filled in from namesp ($udom and $uname are optional)
8134:
8135: =item *
8136:
8137: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8138: namesp ($udom and $uname are optional)
8139:
8140: =item *
8141:
8142: dump($namespace,$udom,$uname,$regexp,$range) :
8143: dumps the complete (or key matching regexp) namespace into a hash
8144: ($udom, $uname, $regexp, $range are optional)
8145:
8146: $range should be either an integer '100' (give me the first 100
8147: matching records)
8148: or be two integers sperated by a - with no spaces
8149: '30-50' (give me the 30th through the 50th matching
8150: records)
8151: =item *
8152:
8153: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8154: $store can be a scalar, an array reference, or if the amount to be
8155: incremented is > 1, a hash reference.
8156:
8157: ($udom and $uname are optional)
8158:
8159: =item *
8160:
8161: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8162: ($udom and $uname are optional)
8163:
8164: =item *
8165:
8166: cput($namespace,$storehash,$udom,$uname) : critical put
8167: ($udom and $uname are optional)
8168:
8169: =item *
8170:
8171: newput($namespace,$storehash,$udom,$uname) :
8172:
8173: Attempts to store the items in the $storehash, but only if they don't
8174: currently exist, if this succeeds you can be certain that you have
8175: successfully created a new key value pair in the $namespace db.
8176:
8177:
8178: Args:
8179: $namespace: name of database to store values to
8180: $storehash: hashref to store to the db
8181: $udom: (optional) domain of user containing the db
8182: $uname: (optional) name of user caontaining the db
8183:
8184: Returns:
8185: 'ok' -> succeeded in storing all keys of $storehash
8186: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8187: least <key> already existed in the db (other
8188: requested keys may also already exist)
8189: 'error: <msg>' -> unable to tie the DB or other erorr occured
8190: 'con_lost' -> unable to contact request server
8191: 'refused' -> action was not allowed by remote machine
8192:
8193:
8194: =item *
8195:
8196: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8197: reference filled in from namesp (encrypts the return communication)
8198: ($udom and $uname are optional)
8199:
8200: =item *
8201:
8202: log($udom,$name,$home,$message) : write to permanent log for user; use
8203: critical subroutine
8204:
8205: =item *
8206:
8207: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
8208: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
8209:
8210: =item *
8211:
8212: put_dom($namespace,$storehash,$udomain) : stores hash in namespace at domain level on primary domain server ($udomain is optional)
8213:
8214: =back
8215:
8216: =head2 Network Status Functions
8217:
8218: =over 4
8219:
8220: =item *
8221:
8222: dirlist($uri) : return directory list based on URI
8223:
8224: =item *
8225:
8226: spareserver() : find server with least workload from spare.tab
8227:
8228: =back
8229:
8230: =head2 Apache Request
8231:
8232: =over 4
8233:
8234: =item *
8235:
8236: ssi($url,%hash) : server side include, does a complete request cycle on url to
8237: localhost, posts hash
8238:
8239: =back
8240:
8241: =head2 Data to String to Data
8242:
8243: =over 4
8244:
8245: =item *
8246:
8247: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8248: and '&' separators, supports elements that are arrayrefs and hashrefs
8249:
8250: =item *
8251:
8252: hashref2str($hashref) : convert a hashref into a string complete with
8253: escaping and '=' and '&' separators, supports elements that are
8254: arrayrefs and hashrefs
8255:
8256: =item *
8257:
8258: arrayref2str($arrayref) : convert an arrayref into a string complete
8259: with escaping and '&' separators, supports elements that are arrayrefs
8260: and hashrefs
8261:
8262: =item *
8263:
8264: str2hash($string) : convert string to hash using unescaping and
8265: splitting on '=' and '&', supports elements that are arrayrefs and
8266: hashrefs
8267:
8268: =item *
8269:
8270: str2array($string) : convert string to hash using unescaping and
8271: splitting on '&', supports elements that are arrayrefs and hashrefs
8272:
8273: =back
8274:
8275: =head2 Logging Routines
8276:
8277: =over 4
8278:
8279: These routines allow one to make log messages in the lonnet.log and
8280: lonnet.perm logfiles.
8281:
8282: =item *
8283:
8284: logtouch() : make sure the logfile, lonnet.log, exists
8285:
8286: =item *
8287:
8288: logthis() : append message to the normal lonnet.log file, it gets
8289: preiodically rolled over and deleted.
8290:
8291: =item *
8292:
8293: logperm() : append a permanent message to lonnet.perm.log, this log
8294: file never gets deleted by any automated portion of the system, only
8295: messages of critical importance should go in here.
8296:
8297: =back
8298:
8299: =head2 General File Helper Routines
8300:
8301: =over 4
8302:
8303: =item *
8304:
8305: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8306: (a) files in /uploaded
8307: (i) If a local copy of the file exists -
8308: compares modification date of local copy with last-modified date for
8309: definitive version stored on home server for course. If local copy is
8310: stale, requests a new version from the home server and stores it.
8311: If the original has been removed from the home server, then local copy
8312: is unlinked.
8313: (ii) If local copy does not exist -
8314: requests the file from the home server and stores it.
8315:
8316: If $caller is 'uploadrep':
8317: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8318: for request for files originally uploaded via DOCS.
8319: - returns 'ok' if fresh local copy now available, -1 otherwise.
8320:
8321: Otherwise:
8322: This indicates a call from the content generation phase of the request.
8323: - returns the entire contents of the file or -1.
8324:
8325: (b) files in /res
8326: - returns the entire contents of a file or -1;
8327: it properly subscribes to and replicates the file if neccessary.
8328:
8329:
8330: =item *
8331:
8332: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8333: reference
8334:
8335: returns either a stat() list of data about the file or an empty list
8336: if the file doesn't exist or couldn't find out about it (connection
8337: problems or user unknown)
8338:
8339: =item *
8340:
8341: filelocation($dir,$file) : returns file system location of a file
8342: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8343: directory that relative $file lookups are to looked in ($dir of /a/dir
8344: and a file of ../bob will become /a/bob)
8345:
8346: =item *
8347:
8348: hreflocation($dir,$file) : returns file system location or a URL; same as
8349: filelocation except for hrefs
8350:
8351: =item *
8352:
8353: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8354:
8355: =back
8356:
8357: =head2 Usererfile file routines (/uploaded*)
8358:
8359: =over 4
8360:
8361: =item *
8362:
8363: userfileupload(): main rotine for putting a file in a user or course's
8364: filespace, arguments are,
8365:
8366: formname - required - this is the name of the element in $env where the
8367: filename, and the contents of the file to create/modifed exist
8368: the filename is in $env{'form.'.$formname.'.filename'} and the
8369: contents of the file is located in $env{'form.'.$formname}
8370: coursedoc - if true, store the file in the course of the active role
8371: of the current user
8372: subdir - required - subdirectory to put the file in under ../userfiles/
8373: if undefined, it will be placed in "unknown"
8374:
8375: (This routine calls clean_filename() to remove any dangerous
8376: characters from the filename, and then calls finuserfileupload() to
8377: complete the transaction)
8378:
8379: returns either the url of the uploaded file (/uploaded/....) if successful
8380: and /adm/notfound.html if unsuccessful
8381:
8382: =item *
8383:
8384: clean_filename(): routine for cleaing a filename up for storage in
8385: userfile space, argument is:
8386:
8387: filename - proposed filename
8388:
8389: returns: the new clean filename
8390:
8391: =item *
8392:
8393: finishuserfileupload(): routine that creaes and sends the file to
8394: userspace, probably shouldn't be called directly
8395:
8396: docuname: username or courseid of destination for the file
8397: docudom: domain of user/course of destination for the file
8398: formname: same as for userfileupload()
8399: fname: filename (inculding subdirectories) for the file
8400:
8401: returns either the url of the uploaded file (/uploaded/....) if successful
8402: and /adm/notfound.html if unsuccessful
8403:
8404: =item *
8405:
8406: renameuserfile(): renames an existing userfile to a new name
8407:
8408: Args:
8409: docuname: username or courseid of destination for the file
8410: docudom: domain of user/course of destination for the file
8411: old: current file name (including any subdirs under userfiles)
8412: new: desired file name (including any subdirs under userfiles)
8413:
8414: =item *
8415:
8416: mkdiruserfile(): creates a directory is a userfiles dir
8417:
8418: Args:
8419: docuname: username or courseid of destination for the file
8420: docudom: domain of user/course of destination for the file
8421: dir: dir to create (including any subdirs under userfiles)
8422:
8423: =item *
8424:
8425: removeuserfile(): removes a file that exists in userfiles
8426:
8427: Args:
8428: docuname: username or courseid of destination for the file
8429: docudom: domain of user/course of destination for the file
8430: fname: filname to delete (including any subdirs under userfiles)
8431:
8432: =item *
8433:
8434: removeuploadedurl(): convience function for removeuserfile()
8435:
8436: Args:
8437: url: a full /uploaded/... url to delete
8438:
8439: =item *
8440:
8441: get_portfile_permissions():
8442: Args:
8443: domain: domain of user or course contain the portfolio files
8444: user: name of user or num of course contain the portfolio files
8445: Returns:
8446: hashref of a dump of the proper file_permissions.db
8447:
8448:
8449: =item *
8450:
8451: get_access_controls():
8452:
8453: Args:
8454: current_permissions: the hash ref returned from get_portfile_permissions()
8455: group: (optional) the group you want the files associated with
8456: file: (optional) the file you want access info on
8457:
8458: Returns:
8459: a hash (keys are file names) of hashes containing
8460: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8461: values are XML containing access control settings (see below)
8462:
8463: Internal notes:
8464:
8465: access controls are stored in file_permissions.db as key=value pairs.
8466: key -> path to file/file_name\0uniqueID:scope_end_start
8467: where scope -> public,guest,course,group,domains or users.
8468: end -> UNIX time for end of access (0 -> no end date)
8469: start -> UNIX time for start of access
8470:
8471: value -> XML description of access control
8472: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8473: <start></start>
8474: <end></end>
8475:
8476: <password></password> for scope type = guest
8477:
8478: <domain></domain> for scope type = course or group
8479: <number></number>
8480: <roles id="">
8481: <role></role>
8482: <access></access>
8483: <section></section>
8484: <group></group>
8485: </roles>
8486:
8487: <dom></dom> for scope type = domains
8488:
8489: <users> for scope type = users
8490: <user>
8491: <uname></uname>
8492: <udom></udom>
8493: </user>
8494: </users>
8495: </scope>
8496:
8497: Access data is also aggregated for each file in an additional key=value pair:
8498: key -> path to file/file_name\0accesscontrol
8499: value -> reference to hash
8500: hash contains key = value pairs
8501: where key = uniqueID:scope_end_start
8502: value = UNIX time record was last updated
8503:
8504: Used to improve speed of look-ups of access controls for each file.
8505:
8506: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8507:
8508: modify_access_controls():
8509:
8510: Modifies access controls for a portfolio file
8511: Args
8512: 1. file name
8513: 2. reference to hash of required changes,
8514: 3. domain
8515: 4. username
8516: where domain,username are the domain of the portfolio owner
8517: (either a user or a course)
8518:
8519: Returns:
8520: 1. result of additions or updates ('ok' or 'error', with error message).
8521: 2. result of deletions ('ok' or 'error', with error message).
8522: 3. reference to hash of any new or updated access controls.
8523: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8524: key = integer (inbound ID)
8525: value = uniqueID
8526:
8527: =back
8528:
8529: =head2 HTTP Helper Routines
8530:
8531: =over 4
8532:
8533: =item *
8534:
8535: escape() : unpack non-word characters into CGI-compatible hex codes
8536:
8537: =item *
8538:
8539: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8540:
8541: =back
8542:
8543: =head1 PRIVATE SUBROUTINES
8544:
8545: =head2 Underlying communication routines (Shouldn't call)
8546:
8547: =over 4
8548:
8549: =item *
8550:
8551: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8552:
8553: =item *
8554:
8555: reply() : uses subreply to send a message to remote machine, logs all failures
8556:
8557: =item *
8558:
8559: critical() : passes a critical message to another server; if cannot
8560: get through then place message in connection buffer directory and
8561: returns con_delayed, if incapable of saving message, returns
8562: con_failed
8563:
8564: =item *
8565:
8566: reconlonc() : tries to reconnect lonc client processes.
8567:
8568: =back
8569:
8570: =head2 Resource Access Logging
8571:
8572: =over 4
8573:
8574: =item *
8575:
8576: flushcourselogs() : flush (save) buffer logs and access logs
8577:
8578: =item *
8579:
8580: courselog($what) : save message for course in hash
8581:
8582: =item *
8583:
8584: courseacclog($what) : save message for course using &courselog(). Perform
8585: special processing for specific resource types (problems, exams, quizzes, etc).
8586:
8587: =item *
8588:
8589: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8590: as a PerlChildExitHandler
8591:
8592: =back
8593:
8594: =head2 Other
8595:
8596: =over 4
8597:
8598: =item *
8599:
8600: symblist($mapname,%newhash) : update symbolic storage links
8601:
8602: =back
8603:
8604: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>