File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.822:
download - view:
text,
annotated -
select for diffs
Thu Jan 11 21:09:10 2007 UTC (17 years, 6 months ago) by
albertel
Branches:
MAIN
CVS tags:
HEAD
- dumping of lonnet::stored info has only the symb and the
parameter escaped so need to push the unescaping off into
the users of the dumped info (as a result resources with :
in the symb work in STAT again)
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.822 2007/01/11 21:09:10 albertel 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 LONCAPA qw(:DEFAULT :match);
57: use LONCAPA::Configuration;
58:
59: my $readit;
60: my $max_connection_retries = 10; # Or some such value.
61:
62: require Exporter;
63:
64: our @ISA = qw (Exporter);
65: our @EXPORT = qw(%env);
66:
67: =pod
68:
69: =head1 Package Variables
70:
71: These are largely undocumented, so if you decipher one please note it here.
72:
73: =over 4
74:
75: =item $processmarker
76:
77: Contains the time this process was started and this servers host id.
78:
79: =item $dumpcount
80:
81: Counts the number of times a message log flush has been attempted (regardless
82: of success) by this process. Used as part of the filename when messages are
83: delayed.
84:
85: =back
86:
87: =cut
88:
89:
90: # --------------------------------------------------------------------- Logging
91: {
92: my $logid;
93: sub instructor_log {
94: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
95: $logid++;
96: my $id=time().'00000'.$$.'00000'.$logid;
97: return &Apache::lonnet::put('nohist_'.$hash_name,
98: { $id => {
99: 'exe_uname' => $env{'user.name'},
100: 'exe_udom' => $env{'user.domain'},
101: 'exe_time' => time(),
102: 'exe_ip' => $ENV{'REMOTE_ADDR'},
103: 'delflag' => $delflag,
104: 'logentry' => $storehash,
105: 'uname' => $uname,
106: 'udom' => $udom,
107: }
108: },
109: $env{'course.'.$env{'request.course.id'}.'.domain'},
110: $env{'course.'.$env{'request.course.id'}.'.num'}
111: );
112: }
113: }
114:
115: sub logtouch {
116: my $execdir=$perlvar{'lonDaemons'};
117: unless (-e "$execdir/logs/lonnet.log") {
118: open(my $fh,">>$execdir/logs/lonnet.log");
119: close $fh;
120: }
121: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
122: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
123: }
124:
125: sub logthis {
126: my $message=shift;
127: my $execdir=$perlvar{'lonDaemons'};
128: my $now=time;
129: my $local=localtime($now);
130: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
131: print $fh "$local ($$): $message\n";
132: close($fh);
133: }
134: return 1;
135: }
136:
137: sub logperm {
138: my $message=shift;
139: my $execdir=$perlvar{'lonDaemons'};
140: my $now=time;
141: my $local=localtime($now);
142: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
143: print $fh "$now:$message:$local\n";
144: close($fh);
145: }
146: return 1;
147: }
148:
149: # -------------------------------------------------- Non-critical communication
150: sub subreply {
151: my ($cmd,$server)=@_;
152: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
153: #
154: # With loncnew process trimming, there's a timing hole between lonc server
155: # process exit and the master server picking up the listen on the AF_UNIX
156: # socket. In that time interval, a lock file will exist:
157:
158: my $lockfile=$peerfile.".lock";
159: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
160: sleep(1);
161: }
162: # At this point, either a loncnew parent is listening or an old lonc
163: # or loncnew child is listening so we can connect or everything's dead.
164: #
165: # We'll give the connection a few tries before abandoning it. If
166: # connection is not possible, we'll con_lost back to the client.
167: #
168: my $client;
169: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
170: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
171: Type => SOCK_STREAM,
172: Timeout => 10);
173: if($client) {
174: last; # Connected!
175: }
176: sleep(1); # Try again later if failed connection.
177: }
178: my $answer;
179: if ($client) {
180: print $client "sethost:$server:$cmd\n";
181: $answer=<$client>;
182: if (!$answer) { $answer="con_lost"; }
183: chomp($answer);
184: } else {
185: $answer = 'con_lost'; # Failed connection.
186: }
187: return $answer;
188: }
189:
190: sub reply {
191: my ($cmd,$server)=@_;
192: unless (defined($hostname{$server})) { return 'no_such_host'; }
193: my $answer=subreply($cmd,$server);
194: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
195: &logthis("<font color=\"blue\">WARNING:".
196: " $cmd to $server returned $answer</font>");
197: }
198: return $answer;
199: }
200:
201: # ----------------------------------------------------------- Send USR1 to lonc
202:
203: sub reconlonc {
204: my $peerfile=shift;
205: &logthis("Trying to reconnect for $peerfile");
206: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
207: if (open(my $fh,"<$loncfile")) {
208: my $loncpid=<$fh>;
209: chomp($loncpid);
210: if (kill 0 => $loncpid) {
211: &logthis("lonc at pid $loncpid responding, sending USR1");
212: kill USR1 => $loncpid;
213: sleep 1;
214: if (-e "$peerfile") { return; }
215: &logthis("$peerfile still not there, give it another try");
216: sleep 5;
217: if (-e "$peerfile") { return; }
218: &logthis(
219: "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
220: } else {
221: &logthis(
222: "<font color=\"blue\">WARNING:".
223: " lonc at pid $loncpid not responding, giving up</font>");
224: }
225: } else {
226: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
227: }
228: }
229:
230: # ------------------------------------------------------ Critical communication
231:
232: sub critical {
233: my ($cmd,$server)=@_;
234: unless ($hostname{$server}) {
235: &logthis("<font color=\"blue\">WARNING:".
236: " Critical message to unknown server ($server)</font>");
237: return 'no_such_host';
238: }
239: my $answer=reply($cmd,$server);
240: if ($answer eq 'con_lost') {
241: &reconlonc("$perlvar{'lonSockDir'}/$server");
242: my $answer=reply($cmd,$server);
243: if ($answer eq 'con_lost') {
244: my $now=time;
245: my $middlename=$cmd;
246: $middlename=substr($middlename,0,16);
247: $middlename=~s/\W//g;
248: my $dfilename=
249: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
250: $dumpcount++;
251: {
252: my $dfh;
253: if (open($dfh,">$dfilename")) {
254: print $dfh "$cmd\n";
255: close($dfh);
256: }
257: }
258: sleep 2;
259: my $wcmd='';
260: {
261: my $dfh;
262: if (open($dfh,"<$dfilename")) {
263: $wcmd=<$dfh>;
264: close($dfh);
265: }
266: }
267: chomp($wcmd);
268: if ($wcmd eq $cmd) {
269: &logthis("<font color=\"blue\">WARNING: ".
270: "Connection buffer $dfilename: $cmd</font>");
271: &logperm("D:$server:$cmd");
272: return 'con_delayed';
273: } else {
274: &logthis("<font color=\"red\">CRITICAL:"
275: ." Critical connection failed: $server $cmd</font>");
276: &logperm("F:$server:$cmd");
277: return 'con_failed';
278: }
279: }
280: }
281: return $answer;
282: }
283:
284: # ------------------------------------------- check if return value is an error
285:
286: sub error {
287: my ($result) = @_;
288: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
289: if ($2 == 2) { return undef; }
290: return $1;
291: }
292: return undef;
293: }
294:
295: sub convert_and_load_session_env {
296: my ($lonidsdir,$handle)=@_;
297: my @profile;
298: {
299: open(my $idf,"$lonidsdir/$handle.id");
300: flock($idf,LOCK_SH);
301: @profile=<$idf>;
302: close($idf);
303: }
304: my %temp_env;
305: foreach my $line (@profile) {
306: if ($line !~ m/=/) {
307: return 0;
308: }
309: chomp($line);
310: my ($envname,$envvalue)=split(/=/,$line,2);
311: $temp_env{&unescape($envname)} = &unescape($envvalue);
312: }
313: unlink("$lonidsdir/$handle.id");
314: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
315: 0640)) {
316: %disk_env = %temp_env;
317: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
318: untie(%disk_env);
319: }
320: return 1;
321: }
322:
323: # ------------------------------------------- Transfer profile into environment
324: my $env_loaded;
325: sub transfer_profile_to_env {
326: my ($lonidsdir,$handle,$force_transfer) = @_;
327: if (!$force_transfer && $env_loaded) { return; }
328:
329: if (!defined($lonidsdir)) {
330: $lonidsdir = $perlvar{'lonIDsDir'};
331: }
332: if (!defined($handle)) {
333: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
334: }
335:
336: my $convert;
337: {
338: open(my $idf,"$lonidsdir/$handle.id");
339: flock($idf,LOCK_SH);
340: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
341: &GDBM_READER(),0640)) {
342: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
343: untie(%disk_env);
344: } else {
345: $convert = 1;
346: }
347: }
348: if ($convert) {
349: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
350: &logthis("Failed to load session, or convert session.");
351: }
352: }
353:
354: my %remove;
355: while ( my $envname = each(%env) ) {
356: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
357: if ($time < time-300) {
358: $remove{$key}++;
359: }
360: }
361: }
362:
363: $env{'user.environment'} = "$lonidsdir/$handle.id";
364: $env_loaded=1;
365: foreach my $expired_key (keys(%remove)) {
366: &delenv($expired_key);
367: }
368: }
369:
370: # ---------------------------------------------------------- Append Environment
371:
372: sub appenv {
373: my %newenv=@_;
374: foreach my $key (keys(%newenv)) {
375: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
376: &logthis("<font color=\"blue\">WARNING: ".
377: "Attempt to modify environment ".$key." to ".$newenv{$key}
378: .'</font>');
379: delete($newenv{$key});
380: } else {
381: $env{$key}=$newenv{$key};
382: }
383: }
384: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
385: 0640)) {
386: while (my ($key,$value) = each(%newenv)) {
387: $disk_env{$key} = $value;
388: }
389: untie(%disk_env);
390: }
391: return 'ok';
392: }
393: # ----------------------------------------------------- Delete from Environment
394:
395: sub delenv {
396: my $delthis=shift;
397: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
398: &logthis("<font color=\"blue\">WARNING: ".
399: "Attempt to delete from environment ".$delthis);
400: return 'error';
401: }
402: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
403: 0640)) {
404: foreach my $key (keys(%disk_env)) {
405: if ($key=~/^$delthis/) {
406: delete($env{$key});
407: delete($disk_env{$key});
408: }
409: }
410: untie(%disk_env);
411: }
412: return 'ok';
413: }
414:
415: sub get_env_multiple {
416: my ($name) = @_;
417: my @values;
418: if (defined($env{$name})) {
419: # exists is it an array
420: if (ref($env{$name})) {
421: @values=@{ $env{$name} };
422: } else {
423: $values[0]=$env{$name};
424: }
425: }
426: return(@values);
427: }
428:
429: # ------------------------------------------ Find out current server userload
430: # there is a copy in lond
431: sub userload {
432: my $numusers=0;
433: {
434: opendir(LONIDS,$perlvar{'lonIDsDir'});
435: my $filename;
436: my $curtime=time;
437: while ($filename=readdir(LONIDS)) {
438: if ($filename eq '.' || $filename eq '..') {next;}
439: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
440: if ($curtime-$mtime < 1800) { $numusers++; }
441: }
442: closedir(LONIDS);
443: }
444: my $userloadpercent=0;
445: my $maxuserload=$perlvar{'lonUserLoadLim'};
446: if ($maxuserload) {
447: $userloadpercent=100*$numusers/$maxuserload;
448: }
449: $userloadpercent=sprintf("%.2f",$userloadpercent);
450: return $userloadpercent;
451: }
452:
453: # ------------------------------------------ Fight off request when overloaded
454:
455: sub overloaderror {
456: my ($r,$checkserver)=@_;
457: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
458: my $loadavg;
459: if ($checkserver eq $perlvar{'lonHostID'}) {
460: open(my $loadfile,'/proc/loadavg');
461: $loadavg=<$loadfile>;
462: $loadavg =~ s/\s.*//g;
463: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
464: close($loadfile);
465: } else {
466: $loadavg=&reply('load',$checkserver);
467: }
468: my $overload=$loadavg-100;
469: if ($overload>0) {
470: $r->err_headers_out->{'Retry-After'}=$overload;
471: $r->log_error('Overload of '.$overload.' on '.$checkserver);
472: return 413;
473: }
474: return '';
475: }
476:
477: # ------------------------------ Find server with least workload from spare.tab
478:
479: sub spareserver {
480: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
481: my $spare_server;
482: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
483: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
484: : $userloadpercent;
485:
486: foreach my $try_server (@{ $spareid{'primary'} }) {
487: ($spare_server, $lowest_load) =
488: &compare_server_load($try_server, $spare_server, $lowest_load);
489: }
490:
491: my $found_server = ($spare_server ne '' && $lowest_load < 100);
492:
493: if (!$found_server) {
494: foreach my $try_server (@{ $spareid{'default'} }) {
495: ($spare_server, $lowest_load) =
496: &compare_server_load($try_server, $spare_server, $lowest_load);
497: }
498: }
499:
500: if (!$want_server_name) {
501: $spare_server="http://$hostname{$spare_server}";
502: }
503: return $spare_server;
504: }
505:
506: sub compare_server_load {
507: my ($try_server, $spare_server, $lowest_load) = @_;
508:
509: my $loadans = &reply('load', $try_server);
510: my $userloadans = &reply('userload',$try_server);
511:
512: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
513: next; #didn't get a number from the server
514: }
515:
516: my $load;
517: if ($loadans =~ /\d/) {
518: if ($userloadans =~ /\d/) {
519: #both are numbers, pick the bigger one
520: $load = ($loadans > $userloadans) ? $loadans
521: : $userloadans;
522: } else {
523: $load = $loadans;
524: }
525: } else {
526: $load = $userloadans;
527: }
528:
529: if (($load =~ /\d/) && ($load < $lowest_load)) {
530: $spare_server = $try_server;
531: $lowest_load = $load;
532: }
533: return ($spare_server,$lowest_load);
534: }
535: # --------------------------------------------- Try to change a user's password
536:
537: sub changepass {
538: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
539: $currentpass = &escape($currentpass);
540: $newpass = &escape($newpass);
541: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
542: $server);
543: if (! $answer) {
544: &logthis("No reply on password change request to $server ".
545: "by $uname in domain $udom.");
546: } elsif ($answer =~ "^ok") {
547: &logthis("$uname in $udom successfully changed their password ".
548: "on $server.");
549: } elsif ($answer =~ "^pwchange_failure") {
550: &logthis("$uname in $udom was unable to change their password ".
551: "on $server. The action was blocked by either lcpasswd ".
552: "or pwchange");
553: } elsif ($answer =~ "^non_authorized") {
554: &logthis("$uname in $udom did not get their password correct when ".
555: "attempting to change it on $server.");
556: } elsif ($answer =~ "^auth_mode_error") {
557: &logthis("$uname in $udom attempted to change their password despite ".
558: "not being locally or internally authenticated on $server.");
559: } elsif ($answer =~ "^unknown_user") {
560: &logthis("$uname in $udom attempted to change their password ".
561: "on $server but were unable to because $server is not ".
562: "their home server.");
563: } elsif ($answer =~ "^refused") {
564: &logthis("$server refused to change $uname in $udom password because ".
565: "it was sent an unencrypted request to change the password.");
566: }
567: return $answer;
568: }
569:
570: # ----------------------- Try to determine user's current authentication scheme
571:
572: sub queryauthenticate {
573: my ($uname,$udom)=@_;
574: my $uhome=&homeserver($uname,$udom);
575: if (!$uhome) {
576: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
577: return 'no_host';
578: }
579: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
580: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
581: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
582: }
583: return $answer;
584: }
585:
586: # --------- Try to authenticate user from domain's lib servers (first this one)
587:
588: sub authenticate {
589: my ($uname,$upass,$udom)=@_;
590: $upass=&escape($upass);
591: $uname= &LONCAPA::clean_username($uname);
592: my $uhome=&homeserver($uname,$udom);
593: if (!$uhome) {
594: &logthis("User $uname at $udom is unknown in authenticate");
595: return 'no_host';
596: }
597: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
598: if ($answer eq 'authorized') {
599: &logthis("User $uname at $udom authorized by $uhome");
600: return $uhome;
601: }
602: if ($answer eq 'non_authorized') {
603: &logthis("User $uname at $udom rejected by $uhome");
604: return 'no_host';
605: }
606: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
607: return 'no_host';
608: }
609:
610: # ---------------------- Find the homebase for a user from domain's lib servers
611:
612: my %homecache;
613: sub homeserver {
614: my ($uname,$udom,$ignoreBadCache)=@_;
615: my $index="$uname:$udom";
616:
617: if (exists($homecache{$index})) { return $homecache{$index}; }
618: my $tryserver;
619: foreach $tryserver (keys %libserv) {
620: next if ($ignoreBadCache ne 'true' &&
621: exists($badServerCache{$tryserver}));
622: if ($hostdom{$tryserver} eq $udom) {
623: my $answer=reply("home:$udom:$uname",$tryserver);
624: if ($answer eq 'found') {
625: return $homecache{$index}=$tryserver;
626: } elsif ($answer eq 'no_host') {
627: $badServerCache{$tryserver}=1;
628: }
629: }
630: }
631: return 'no_host';
632: }
633:
634: # ------------------------------------- Find the usernames behind a list of IDs
635:
636: sub idget {
637: my ($udom,@ids)=@_;
638: my %returnhash=();
639:
640: my $tryserver;
641: foreach $tryserver (keys %libserv) {
642: if ($hostdom{$tryserver} eq $udom) {
643: my $idlist=join('&',@ids);
644: $idlist=~tr/A-Z/a-z/;
645: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
646: my @answer=();
647: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
648: @answer=split(/\&/,$reply);
649: } ;
650: my $i;
651: for ($i=0;$i<=$#ids;$i++) {
652: if ($answer[$i]) {
653: $returnhash{$ids[$i]}=$answer[$i];
654: }
655: }
656: }
657: }
658: return %returnhash;
659: }
660:
661: # ------------------------------------- Find the IDs behind a list of usernames
662:
663: sub idrget {
664: my ($udom,@unames)=@_;
665: my %returnhash=();
666: foreach my $uname (@unames) {
667: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
668: }
669: return %returnhash;
670: }
671:
672: # ------------------------------- Store away a list of names and associated IDs
673:
674: sub idput {
675: my ($udom,%ids)=@_;
676: my %servers=();
677: foreach my $uname (keys(%ids)) {
678: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
679: my $uhom=&homeserver($uname,$udom);
680: if ($uhom ne 'no_host') {
681: my $id=&escape($ids{$uname});
682: $id=~tr/A-Z/a-z/;
683: my $esc_unam=&escape($uname);
684: if ($servers{$uhom}) {
685: $servers{$uhom}.='&'.$id.'='.$esc_unam;
686: } else {
687: $servers{$uhom}=$id.'='.$esc_unam;
688: }
689: }
690: }
691: foreach my $server (keys(%servers)) {
692: &critical('idput:'.$udom.':'.$servers{$server},$server);
693: }
694: }
695:
696: # ------------------------------------------- get items from domain db files
697:
698: sub get_dom {
699: my ($namespace,$storearr,$udom)=@_;
700: my $items='';
701: foreach my $item (@$storearr) {
702: $items.=&escape($item).'&';
703: }
704: $items=~s/\&$//;
705: if (!$udom) { $udom=$env{'user.domain'}; }
706: if (exists($domain_primary{$udom})) {
707: my $uhome=$domain_primary{$udom};
708: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
709: my @pairs=split(/\&/,$rep);
710: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
711: return @pairs;
712: }
713: my %returnhash=();
714: my $i=0;
715: foreach my $item (@$storearr) {
716: $returnhash{$item}=&thaw_unescape($pairs[$i]);
717: $i++;
718: }
719: return %returnhash;
720: } else {
721: &logthis("get_dom failed - no primary domain server for $udom");
722: }
723: }
724:
725: # -------------------------------------------- put items in domain db files
726:
727: sub put_dom {
728: my ($namespace,$storehash,$udom)=@_;
729: if (!$udom) { $udom=$env{'user.domain'}; }
730: if (exists($domain_primary{$udom})) {
731: my $uhome=$domain_primary{$udom};
732: my $items='';
733: foreach my $item (keys(%$storehash)) {
734: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
735: }
736: $items=~s/\&$//;
737: return &reply("putdom:$udom:$namespace:$items",$uhome);
738: } else {
739: &logthis("put_dom failed - no primary domain server for $udom");
740: }
741: }
742:
743: # --------------------------------------------------- Assign a key to a student
744:
745: sub assign_access_key {
746: #
747: # a valid key looks like uname:udom#comments
748: # comments are being appended
749: #
750: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
751: $kdom=
752: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
753: $knum=
754: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
755: $cdom=
756: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
757: $cnum=
758: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
759: $udom=$env{'user.name'} unless (defined($udom));
760: $uname=$env{'user.domain'} unless (defined($uname));
761: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
762: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
763: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
764: # assigned to this person
765: # - this should not happen,
766: # unless something went wrong
767: # the first time around
768: # ready to assign
769: $logentry=$1.'; '.$logentry;
770: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
771: $kdom,$knum) eq 'ok') {
772: # key now belongs to user
773: my $envkey='key.'.$cdom.'_'.$cnum;
774: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
775: &appenv('environment.'.$envkey => $ckey);
776: return 'ok';
777: } else {
778: return
779: 'error: Count not permanently assign key, will need to be re-entered later.';
780: }
781: } else {
782: return 'error: Could not assign key, try again later.';
783: }
784: } elsif (!$existing{$ckey}) {
785: # the key does not exist
786: return 'error: The key does not exist';
787: } else {
788: # the key is somebody else's
789: return 'error: The key is already in use';
790: }
791: }
792:
793: # ------------------------------------------ put an additional comment on a key
794:
795: sub comment_access_key {
796: #
797: # a valid key looks like uname:udom#comments
798: # comments are being appended
799: #
800: my ($ckey,$cdom,$cnum,$logentry)=@_;
801: $cdom=
802: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
803: $cnum=
804: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
805: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
806: if ($existing{$ckey}) {
807: $existing{$ckey}.='; '.$logentry;
808: # ready to assign
809: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
810: $cdom,$cnum) eq 'ok') {
811: return 'ok';
812: } else {
813: return 'error: Count not store comment.';
814: }
815: } else {
816: # the key does not exist
817: return 'error: The key does not exist';
818: }
819: }
820:
821: # ------------------------------------------------------ Generate a set of keys
822:
823: sub generate_access_keys {
824: my ($number,$cdom,$cnum,$logentry)=@_;
825: $cdom=
826: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
827: $cnum=
828: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
829: unless (&allowed('mky',$cdom)) { return 0; }
830: unless (($cdom) && ($cnum)) { return 0; }
831: if ($number>10000) { return 0; }
832: sleep(2); # make sure don't get same seed twice
833: srand(time()^($$+($$<<15))); # from "Programming Perl"
834: my $total=0;
835: for (my $i=1;$i<=$number;$i++) {
836: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
837: sprintf("%lx",int(100000*rand)).'-'.
838: sprintf("%lx",int(100000*rand));
839: $newkey=~s/1/g/g; # folks mix up 1 and l
840: $newkey=~s/0/h/g; # and also 0 and O
841: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
842: if ($existing{$newkey}) {
843: $i--;
844: } else {
845: if (&put('accesskeys',
846: { $newkey => '# generated '.localtime().
847: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
848: '; '.$logentry },
849: $cdom,$cnum) eq 'ok') {
850: $total++;
851: }
852: }
853: }
854: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
855: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
856: return $total;
857: }
858:
859: # ------------------------------------------------------- Validate an accesskey
860:
861: sub validate_access_key {
862: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
863: $cdom=
864: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
865: $cnum=
866: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
867: $udom=$env{'user.domain'} unless (defined($udom));
868: $uname=$env{'user.name'} unless (defined($uname));
869: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
870: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
871: }
872:
873: # ------------------------------------- Find the section of student in a course
874: sub devalidate_getsection_cache {
875: my ($udom,$unam,$courseid)=@_;
876: my $hashid="$udom:$unam:$courseid";
877: &devalidate_cache_new('getsection',$hashid);
878: }
879:
880: sub courseid_to_courseurl {
881: my ($courseid) = @_;
882: #already url style courseid
883: return $courseid if ($courseid =~ m{^/});
884:
885: if (exists($env{'course.'.$courseid.'.num'})) {
886: my $cnum = $env{'course.'.$courseid.'.num'};
887: my $cdom = $env{'course.'.$courseid.'.domain'};
888: return "/$cdom/$cnum";
889: }
890:
891: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
892: if (exists($courseinfo{'num'})) {
893: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
894: }
895:
896: return undef;
897: }
898:
899: sub getsection {
900: my ($udom,$unam,$courseid)=@_;
901: my $cachetime=1800;
902:
903: my $hashid="$udom:$unam:$courseid";
904: my ($result,$cached)=&is_cached_new('getsection',$hashid);
905: if (defined($cached)) { return $result; }
906:
907: my %Pending;
908: my %Expired;
909: #
910: # Each role can either have not started yet (pending), be active,
911: # or have expired.
912: #
913: # If there is an active role, we are done.
914: #
915: # If there is more than one role which has not started yet,
916: # choose the one which will start sooner
917: # If there is one role which has not started yet, return it.
918: #
919: # If there is more than one expired role, choose the one which ended last.
920: # If there is a role which has expired, return it.
921: #
922: $courseid = &courseid_to_courseurl($courseid);
923: my %roleshash = &dump('roles',$udom,$unam,$courseid);
924: foreach my $key (keys(%roleshash)) {
925: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
926: my $section=$1;
927: if ($key eq $courseid.'_st') { $section=''; }
928: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
929: my $now=time;
930: if (defined($end) && $end && ($now > $end)) {
931: $Expired{$end}=$section;
932: next;
933: }
934: if (defined($start) && $start && ($now < $start)) {
935: $Pending{$start}=$section;
936: next;
937: }
938: return &do_cache_new('getsection',$hashid,$section,$cachetime);
939: }
940: #
941: # Presumedly there will be few matching roles from the above
942: # loop and the sorting time will be negligible.
943: if (scalar(keys(%Pending))) {
944: my ($time) = sort {$a <=> $b} keys(%Pending);
945: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
946: }
947: if (scalar(keys(%Expired))) {
948: my @sorted = sort {$a <=> $b} keys(%Expired);
949: my $time = pop(@sorted);
950: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
951: }
952: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
953: }
954:
955: sub save_cache {
956: &purge_remembered();
957: #&Apache::loncommon::validate_page();
958: undef(%env);
959: undef($env_loaded);
960: }
961:
962: my $to_remember=-1;
963: my %remembered;
964: my %accessed;
965: my $kicks=0;
966: my $hits=0;
967: sub devalidate_cache_new {
968: my ($name,$id,$debug) = @_;
969: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
970: $id=&escape($name.':'.$id);
971: $memcache->delete($id);
972: delete($remembered{$id});
973: delete($accessed{$id});
974: }
975:
976: sub is_cached_new {
977: my ($name,$id,$debug) = @_;
978: $id=&escape($name.':'.$id);
979: if (exists($remembered{$id})) {
980: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
981: $accessed{$id}=[&gettimeofday()];
982: $hits++;
983: return ($remembered{$id},1);
984: }
985: my $value = $memcache->get($id);
986: if (!(defined($value))) {
987: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
988: return (undef,undef);
989: }
990: if ($value eq '__undef__') {
991: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
992: $value=undef;
993: }
994: &make_room($id,$value,$debug);
995: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
996: return ($value,1);
997: }
998:
999: sub do_cache_new {
1000: my ($name,$id,$value,$time,$debug) = @_;
1001: $id=&escape($name.':'.$id);
1002: my $setvalue=$value;
1003: if (!defined($setvalue)) {
1004: $setvalue='__undef__';
1005: }
1006: if (!defined($time) ) {
1007: $time=600;
1008: }
1009: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1010: $memcache->set($id,$setvalue,$time);
1011: # need to make a copy of $value
1012: #&make_room($id,$value,$debug);
1013: return $value;
1014: }
1015:
1016: sub make_room {
1017: my ($id,$value,$debug)=@_;
1018: $remembered{$id}=$value;
1019: if ($to_remember<0) { return; }
1020: $accessed{$id}=[&gettimeofday()];
1021: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1022: my $to_kick;
1023: my $max_time=0;
1024: foreach my $other (keys(%accessed)) {
1025: if (&tv_interval($accessed{$other}) > $max_time) {
1026: $to_kick=$other;
1027: $max_time=&tv_interval($accessed{$other});
1028: }
1029: }
1030: delete($remembered{$to_kick});
1031: delete($accessed{$to_kick});
1032: $kicks++;
1033: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1034: return;
1035: }
1036:
1037: sub purge_remembered {
1038: #&logthis("Tossing ".scalar(keys(%remembered)));
1039: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1040: undef(%remembered);
1041: undef(%accessed);
1042: }
1043: # ------------------------------------- Read an entry from a user's environment
1044:
1045: sub userenvironment {
1046: my ($udom,$unam,@what)=@_;
1047: my %returnhash=();
1048: my @answer=split(/\&/,
1049: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1050: &homeserver($unam,$udom)));
1051: my $i;
1052: for ($i=0;$i<=$#what;$i++) {
1053: $returnhash{$what[$i]}=&unescape($answer[$i]);
1054: }
1055: return %returnhash;
1056: }
1057:
1058: # ---------------------------------------------------------- Get a studentphoto
1059: sub studentphoto {
1060: my ($udom,$unam,$ext) = @_;
1061: my $home=&Apache::lonnet::homeserver($unam,$udom);
1062: if (defined($env{'request.course.id'})) {
1063: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1064: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1065: return(&retrievestudentphoto($udom,$unam,$ext));
1066: } else {
1067: my ($result,$perm_reqd)=
1068: &Apache::lonnet::auto_photo_permission($unam,$udom);
1069: if ($result eq 'ok') {
1070: if (!($perm_reqd eq 'yes')) {
1071: return(&retrievestudentphoto($udom,$unam,$ext));
1072: }
1073: }
1074: }
1075: }
1076: } else {
1077: my ($result,$perm_reqd) =
1078: &Apache::lonnet::auto_photo_permission($unam,$udom);
1079: if ($result eq 'ok') {
1080: if (!($perm_reqd eq 'yes')) {
1081: return(&retrievestudentphoto($udom,$unam,$ext));
1082: }
1083: }
1084: }
1085: return '/adm/lonKaputt/lonlogo_broken.gif';
1086: }
1087:
1088: sub retrievestudentphoto {
1089: my ($udom,$unam,$ext,$type) = @_;
1090: my $home=&Apache::lonnet::homeserver($unam,$udom);
1091: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1092: if ($ret eq 'ok') {
1093: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1094: if ($type eq 'thumbnail') {
1095: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1096: }
1097: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1098: return $tokenurl;
1099: } else {
1100: if ($type eq 'thumbnail') {
1101: return '/adm/lonKaputt/genericstudent_tn.gif';
1102: } else {
1103: return '/adm/lonKaputt/lonlogo_broken.gif';
1104: }
1105: }
1106: }
1107:
1108: # -------------------------------------------------------------------- New chat
1109:
1110: sub chatsend {
1111: my ($newentry,$anon,$group)=@_;
1112: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1113: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1114: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1115: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1116: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1117: &escape($newentry)).':'.$group,$chome);
1118: }
1119:
1120: # ------------------------------------------ Find current version of a resource
1121:
1122: sub getversion {
1123: my $fname=&clutter(shift);
1124: unless ($fname=~/^\/res\//) { return -1; }
1125: return ¤tversion(&filelocation('',$fname));
1126: }
1127:
1128: sub currentversion {
1129: my $fname=shift;
1130: my ($result,$cached)=&is_cached_new('resversion',$fname);
1131: if (defined($cached)) { return $result; }
1132: my $author=$fname;
1133: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1134: my ($udom,$uname)=split(/\//,$author);
1135: my $home=homeserver($uname,$udom);
1136: if ($home eq 'no_host') {
1137: return -1;
1138: }
1139: my $answer=reply("currentversion:$fname",$home);
1140: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1141: return -1;
1142: }
1143: return &do_cache_new('resversion',$fname,$answer,600);
1144: }
1145:
1146: # ----------------------------- Subscribe to a resource, return URL if possible
1147:
1148: sub subscribe {
1149: my $fname=shift;
1150: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1151: $fname=~s/[\n\r]//g;
1152: my $author=$fname;
1153: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1154: my ($udom,$uname)=split(/\//,$author);
1155: my $home=homeserver($uname,$udom);
1156: if ($home eq 'no_host') {
1157: return 'not_found';
1158: }
1159: my $answer=reply("sub:$fname",$home);
1160: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1161: $answer.=' by '.$home;
1162: }
1163: return $answer;
1164: }
1165:
1166: # -------------------------------------------------------------- Replicate file
1167:
1168: sub repcopy {
1169: my $filename=shift;
1170: $filename=~s/\/+/\//g;
1171: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1172: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1173: if ($filename=~m|^/home/httpd/html/userfiles/| or
1174: $filename=~m -^/*(uploaded|editupload)/-) {
1175: return &repcopy_userfile($filename);
1176: }
1177: $filename=~s/[\n\r]//g;
1178: my $transname="$filename.in.transfer";
1179: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1180: my $remoteurl=subscribe($filename);
1181: if ($remoteurl =~ /^con_lost by/) {
1182: &logthis("Subscribe returned $remoteurl: $filename");
1183: return 'unavailable';
1184: } elsif ($remoteurl eq 'not_found') {
1185: #&logthis("Subscribe returned not_found: $filename");
1186: return 'not_found';
1187: } elsif ($remoteurl =~ /^rejected by/) {
1188: &logthis("Subscribe returned $remoteurl: $filename");
1189: return 'forbidden';
1190: } elsif ($remoteurl eq 'directory') {
1191: return 'ok';
1192: } else {
1193: my $author=$filename;
1194: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1195: my ($udom,$uname)=split(/\//,$author);
1196: my $home=homeserver($uname,$udom);
1197: unless ($home eq $perlvar{'lonHostID'}) {
1198: my @parts=split(/\//,$filename);
1199: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1200: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1201: &logthis("Malconfiguration for replication: $filename");
1202: return 'bad_request';
1203: }
1204: my $count;
1205: for ($count=5;$count<$#parts;$count++) {
1206: $path.="/$parts[$count]";
1207: if ((-e $path)!=1) {
1208: mkdir($path,0777);
1209: }
1210: }
1211: my $ua=new LWP::UserAgent;
1212: my $request=new HTTP::Request('GET',"$remoteurl");
1213: my $response=$ua->request($request,$transname);
1214: if ($response->is_error()) {
1215: unlink($transname);
1216: my $message=$response->status_line;
1217: &logthis("<font color=\"blue\">WARNING:"
1218: ." LWP get: $message: $filename</font>");
1219: return 'unavailable';
1220: } else {
1221: if ($remoteurl!~/\.meta$/) {
1222: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1223: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1224: if ($mresponse->is_error()) {
1225: unlink($filename.'.meta');
1226: &logthis(
1227: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1228: }
1229: }
1230: rename($transname,$filename);
1231: return 'ok';
1232: }
1233: }
1234: }
1235: }
1236:
1237: # ------------------------------------------------ Get server side include body
1238: sub ssi_body {
1239: my ($filelink,%form)=@_;
1240: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1241: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1242: }
1243: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1244: &ssi($filelink,%form));
1245: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1246: $output=~s/^.*?\<body[^\>]*\>//si;
1247: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1248: return $output;
1249: }
1250:
1251: # --------------------------------------------------------- Server Side Include
1252:
1253: sub absolute_url {
1254: my ($host_name) = @_;
1255: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1256: if ($host_name eq '') {
1257: $host_name = $ENV{'SERVER_NAME'};
1258: }
1259: return $protocol.$host_name;
1260: }
1261:
1262: sub ssi {
1263:
1264: my ($fn,%form)=@_;
1265:
1266: my $ua=new LWP::UserAgent;
1267:
1268: my $request;
1269:
1270: $form{'no_update_last_known'}=1;
1271:
1272: if (%form) {
1273: $request=new HTTP::Request('POST',&absolute_url().$fn);
1274: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1275: } else {
1276: $request=new HTTP::Request('GET',&absolute_url().$fn);
1277: }
1278:
1279: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1280: my $response=$ua->request($request);
1281:
1282: return $response->content;
1283: }
1284:
1285: sub externalssi {
1286: my ($url)=@_;
1287: my $ua=new LWP::UserAgent;
1288: my $request=new HTTP::Request('GET',$url);
1289: my $response=$ua->request($request);
1290: return $response->content;
1291: }
1292:
1293: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1294:
1295: sub allowuploaded {
1296: my ($srcurl,$url)=@_;
1297: $url=&clutter(&declutter($url));
1298: my $dir=$url;
1299: $dir=~s/\/[^\/]+$//;
1300: my %httpref=();
1301: my $httpurl=&hreflocation('',$url);
1302: $httpref{'httpref.'.$httpurl}=$srcurl;
1303: &Apache::lonnet::appenv(%httpref);
1304: }
1305:
1306: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1307: # input: action, courseID, current domain, intended
1308: # path to file, source of file, instruction to parse file for objects,
1309: # ref to hash for embedded objects,
1310: # ref to hash for codebase of java objects.
1311: #
1312: # output: url to file (if action was uploaddoc),
1313: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1314: #
1315: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1316: # course.
1317: #
1318: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1319: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1320: # course's home server.
1321: #
1322: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1323: # be copied from $source (current location) to
1324: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1325: # and will then be copied to
1326: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1327: # course's home server.
1328: #
1329: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1330: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1331: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1332: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1333: # in course's home server.
1334: #
1335:
1336: sub process_coursefile {
1337: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1338: my $fetchresult;
1339: my $home=&homeserver($docuname,$docudom);
1340: if ($action eq 'propagate') {
1341: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1342: $home);
1343: } else {
1344: my $fpath = '';
1345: my $fname = $file;
1346: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1347: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1348: my $filepath = &build_filepath($fpath);
1349: if ($action eq 'copy') {
1350: if ($source eq '') {
1351: $fetchresult = 'no source file';
1352: return $fetchresult;
1353: } else {
1354: my $destination = $filepath.'/'.$fname;
1355: rename($source,$destination);
1356: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1357: $home);
1358: }
1359: } elsif ($action eq 'uploaddoc') {
1360: open(my $fh,'>'.$filepath.'/'.$fname);
1361: print $fh $env{'form.'.$source};
1362: close($fh);
1363: if ($parser eq 'parse') {
1364: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1365: unless ($parse_result eq 'ok') {
1366: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1367: }
1368: }
1369: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1370: $home);
1371: if ($fetchresult eq 'ok') {
1372: return '/uploaded/'.$fpath.'/'.$fname;
1373: } else {
1374: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1375: ' to host '.$home.': '.$fetchresult);
1376: return '/adm/notfound.html';
1377: }
1378: }
1379: }
1380: unless ( $fetchresult eq 'ok') {
1381: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1382: ' to host '.$home.': '.$fetchresult);
1383: }
1384: return $fetchresult;
1385: }
1386:
1387: sub build_filepath {
1388: my ($fpath) = @_;
1389: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1390: unless ($fpath eq '') {
1391: my @parts=split('/',$fpath);
1392: foreach my $part (@parts) {
1393: $filepath.= '/'.$part;
1394: if ((-e $filepath)!=1) {
1395: mkdir($filepath,0777);
1396: }
1397: }
1398: }
1399: return $filepath;
1400: }
1401:
1402: sub store_edited_file {
1403: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1404: my $file = $primary_url;
1405: $file =~ s#^/uploaded/$docudom/$docuname/##;
1406: my $fpath = '';
1407: my $fname = $file;
1408: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1409: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1410: my $filepath = &build_filepath($fpath);
1411: open(my $fh,'>'.$filepath.'/'.$fname);
1412: print $fh $content;
1413: close($fh);
1414: my $home=&homeserver($docuname,$docudom);
1415: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1416: $home);
1417: if ($$fetchresult eq 'ok') {
1418: return '/uploaded/'.$fpath.'/'.$fname;
1419: } else {
1420: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1421: ' to host '.$home.': '.$$fetchresult);
1422: return '/adm/notfound.html';
1423: }
1424: }
1425:
1426: sub clean_filename {
1427: my ($fname)=@_;
1428: # Replace Windows backslashes by forward slashes
1429: $fname=~s/\\/\//g;
1430: # Get rid of everything but the actual filename
1431: $fname=~s/^.*\/([^\/]+)$/$1/;
1432: # Replace spaces by underscores
1433: $fname=~s/\s+/\_/g;
1434: # Replace all other weird characters by nothing
1435: $fname=~s/[^\w\.\-]//g;
1436: # Replace all .\d. sequences with _\d. so they no longer look like version
1437: # numbers
1438: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1439: return $fname;
1440: }
1441:
1442: # --------------- Take an uploaded file and put it into the userfiles directory
1443: # input: $formname - the contents of the file are in $env{"form.$formname"}
1444: # the desired filenam is in $env{"form.$formname.filename"}
1445: # $coursedoc - if true up to the current course
1446: # if false
1447: # $subdir - directory in userfile to store the file into
1448: # $parser, $allfiles, $codebase - unknown
1449: #
1450: # output: url of file in userspace, or error: <message>
1451: # or /adm/notfound.html if failure to upload occurse
1452:
1453:
1454: sub userfileupload {
1455: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1456: if (!defined($subdir)) { $subdir='unknown'; }
1457: my $fname=$env{'form.'.$formname.'.filename'};
1458: $fname=&clean_filename($fname);
1459: # See if there is anything left
1460: unless ($fname) { return 'error: no uploaded file'; }
1461: chop($env{'form.'.$formname});
1462: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1463: my $now = time;
1464: my $filepath = 'tmp/helprequests/'.$now;
1465: my @parts=split(/\//,$filepath);
1466: my $fullpath = $perlvar{'lonDaemons'};
1467: for (my $i=0;$i<@parts;$i++) {
1468: $fullpath .= '/'.$parts[$i];
1469: if ((-e $fullpath)!=1) {
1470: mkdir($fullpath,0777);
1471: }
1472: }
1473: open(my $fh,'>'.$fullpath.'/'.$fname);
1474: print $fh $env{'form.'.$formname};
1475: close($fh);
1476: return $fullpath.'/'.$fname;
1477: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1478: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1479: '_'.$env{'user.domain'}.'/pending';
1480: my @parts=split(/\//,$filepath);
1481: my $fullpath = $perlvar{'lonDaemons'};
1482: for (my $i=0;$i<@parts;$i++) {
1483: $fullpath .= '/'.$parts[$i];
1484: if ((-e $fullpath)!=1) {
1485: mkdir($fullpath,0777);
1486: }
1487: }
1488: open(my $fh,'>'.$fullpath.'/'.$fname);
1489: print $fh $env{'form.'.$formname};
1490: close($fh);
1491: return $fullpath.'/'.$fname;
1492: }
1493:
1494: # Create the directory if not present
1495: $fname="$subdir/$fname";
1496: if ($coursedoc) {
1497: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1498: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1499: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1500: return &finishuserfileupload($docuname,$docudom,
1501: $formname,$fname,$parser,$allfiles,
1502: $codebase);
1503: } else {
1504: $fname=$env{'form.folder'}.'/'.$fname;
1505: return &process_coursefile('uploaddoc',$docuname,$docudom,
1506: $fname,$formname,$parser,
1507: $allfiles,$codebase);
1508: }
1509: } elsif (defined($destuname)) {
1510: my $docuname=$destuname;
1511: my $docudom=$destudom;
1512: return &finishuserfileupload($docuname,$docudom,$formname,
1513: $fname,$parser,$allfiles,$codebase);
1514:
1515: } else {
1516: my $docuname=$env{'user.name'};
1517: my $docudom=$env{'user.domain'};
1518: if (exists($env{'form.group'})) {
1519: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1520: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1521: }
1522: return &finishuserfileupload($docuname,$docudom,$formname,
1523: $fname,$parser,$allfiles,$codebase);
1524: }
1525: }
1526:
1527: sub finishuserfileupload {
1528: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1529: my $path=$docudom.'/'.$docuname.'/';
1530: my $filepath=$perlvar{'lonDocRoot'};
1531: my ($fnamepath,$file);
1532: $file=$fname;
1533: if ($fname=~m|/|) {
1534: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1535: $path.=$fnamepath.'/';
1536: }
1537: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1538: my $count;
1539: for ($count=4;$count<=$#parts;$count++) {
1540: $filepath.="/$parts[$count]";
1541: if ((-e $filepath)!=1) {
1542: mkdir($filepath,0777);
1543: }
1544: }
1545: # Save the file
1546: {
1547: if (!open(FH,'>'.$filepath.'/'.$file)) {
1548: &logthis('Failed to create '.$filepath.'/'.$file);
1549: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1550: return '/adm/notfound.html';
1551: }
1552: if (!print FH ($env{'form.'.$formname})) {
1553: &logthis('Failed to write to '.$filepath.'/'.$file);
1554: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1555: return '/adm/notfound.html';
1556: }
1557: close(FH);
1558: }
1559: if ($parser eq 'parse') {
1560: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1561: $codebase);
1562: unless ($parse_result eq 'ok') {
1563: &logthis('Failed to parse '.$filepath.$file.
1564: ' for embedded media: '.$parse_result);
1565: }
1566: }
1567: # Notify homeserver to grep it
1568: #
1569: my $docuhome=&homeserver($docuname,$docudom);
1570: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1571: if ($fetchresult eq 'ok') {
1572: #
1573: # Return the URL to it
1574: return '/uploaded/'.$path.$file;
1575: } else {
1576: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1577: ': '.$fetchresult);
1578: return '/adm/notfound.html';
1579: }
1580: }
1581:
1582: sub extract_embedded_items {
1583: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1584: my @state = ();
1585: my %javafiles = (
1586: codebase => '',
1587: code => '',
1588: archive => ''
1589: );
1590: my %mediafiles = (
1591: src => '',
1592: movie => '',
1593: );
1594: my $p;
1595: if ($content) {
1596: $p = HTML::LCParser->new($content);
1597: } else {
1598: $p = HTML::LCParser->new($filepath.'/'.$file);
1599: }
1600: while (my $t=$p->get_token()) {
1601: if ($t->[0] eq 'S') {
1602: my ($tagname, $attr) = ($t->[1],$t->[2]);
1603: push (@state, $tagname);
1604: if (lc($tagname) eq 'allow') {
1605: &add_filetype($allfiles,$attr->{'src'},'src');
1606: }
1607: if (lc($tagname) eq 'img') {
1608: &add_filetype($allfiles,$attr->{'src'},'src');
1609: }
1610: if (lc($tagname) eq 'script') {
1611: if ($attr->{'archive'} =~ /\.jar$/i) {
1612: &add_filetype($allfiles,$attr->{'archive'},'archive');
1613: } else {
1614: &add_filetype($allfiles,$attr->{'src'},'src');
1615: }
1616: }
1617: if (lc($tagname) eq 'link') {
1618: if (lc($attr->{'rel'}) eq 'stylesheet') {
1619: &add_filetype($allfiles,$attr->{'href'},'href');
1620: }
1621: }
1622: if (lc($tagname) eq 'object' ||
1623: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1624: foreach my $item (keys(%javafiles)) {
1625: $javafiles{$item} = '';
1626: }
1627: }
1628: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1629: my $name = lc($attr->{'name'});
1630: foreach my $item (keys(%javafiles)) {
1631: if ($name eq $item) {
1632: $javafiles{$item} = $attr->{'value'};
1633: last;
1634: }
1635: }
1636: foreach my $item (keys(%mediafiles)) {
1637: if ($name eq $item) {
1638: &add_filetype($allfiles, $attr->{'value'}, 'value');
1639: last;
1640: }
1641: }
1642: }
1643: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1644: foreach my $item (keys(%javafiles)) {
1645: if ($attr->{$item}) {
1646: $javafiles{$item} = $attr->{$item};
1647: last;
1648: }
1649: }
1650: foreach my $item (keys(%mediafiles)) {
1651: if ($attr->{$item}) {
1652: &add_filetype($allfiles,$attr->{$item},$item);
1653: last;
1654: }
1655: }
1656: }
1657: } elsif ($t->[0] eq 'E') {
1658: my ($tagname) = ($t->[1]);
1659: if ($javafiles{'codebase'} ne '') {
1660: $javafiles{'codebase'} .= '/';
1661: }
1662: if (lc($tagname) eq 'applet' ||
1663: lc($tagname) eq 'object' ||
1664: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1665: ) {
1666: foreach my $item (keys(%javafiles)) {
1667: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1668: my $file=$javafiles{'codebase'}.$javafiles{$item};
1669: &add_filetype($allfiles,$file,$item);
1670: }
1671: }
1672: }
1673: pop @state;
1674: }
1675: }
1676: return 'ok';
1677: }
1678:
1679: sub add_filetype {
1680: my ($allfiles,$file,$type)=@_;
1681: if (exists($allfiles->{$file})) {
1682: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1683: push(@{$allfiles->{$file}}, &escape($type));
1684: }
1685: } else {
1686: @{$allfiles->{$file}} = (&escape($type));
1687: }
1688: }
1689:
1690: sub removeuploadedurl {
1691: my ($url)=@_;
1692: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1693: return &removeuserfile($uname,$udom,$fname);
1694: }
1695:
1696: sub removeuserfile {
1697: my ($docuname,$docudom,$fname)=@_;
1698: my $home=&homeserver($docuname,$docudom);
1699: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1700: if ($result eq 'ok') {
1701: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1702: my $metafile = $fname.'.meta';
1703: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1704: my ($group,$file);
1705: if ($fname =~ /^groups\/(\w+)\/portfolio(\/.+)$/) {
1706: $group = $1;
1707: $file = $2;
1708: } elsif ($fname =~ /^portfolio(\/.+)$/) {
1709: $file = $1;
1710: }
1711: my $sqlresult =
1712: &update_portfolio_table($docuname,$docudom,$group.$file,
1713: 'portfolio_metadata',$group,
1714: 'delete');
1715: }
1716: }
1717: return $result;
1718: }
1719:
1720: sub mkdiruserfile {
1721: my ($docuname,$docudom,$dir)=@_;
1722: my $home=&homeserver($docuname,$docudom);
1723: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1724: }
1725:
1726: sub renameuserfile {
1727: my ($docuname,$docudom,$old,$new)=@_;
1728: my $home=&homeserver($docuname,$docudom);
1729: my $result = &reply("renameuserfile:$docudom:$docuname:".
1730: &escape("$old").':'.&escape("$new"),$home);
1731: if ($result eq 'ok') {
1732: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1733: my $oldmeta = $old.'.meta';
1734: my $newmeta = $new.'.meta';
1735: my $metaresult =
1736: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1737: my ($group,$file);
1738: if ($old =~ /^groups\/(\w+)\/portfolio(\/.+)$/) {
1739: $group = $1;
1740: $file = $2;
1741: } elsif ($old =~ /^portfolio(\/.+)$/) {
1742: $file = $1;
1743: }
1744: my $sqlresult =
1745: &update_portfolio_table($docuname,$docudom,$group.$file,
1746: 'portfolio_metadata',$group,
1747: 'delete');
1748: }
1749: }
1750: return $result;
1751: }
1752:
1753: # ------------------------------------------------------------------------- Log
1754:
1755: sub log {
1756: my ($dom,$nam,$hom,$what)=@_;
1757: return critical("log:$dom:$nam:$what",$hom);
1758: }
1759:
1760: # ------------------------------------------------------------------ Course Log
1761: #
1762: # This routine flushes several buffers of non-mission-critical nature
1763: #
1764:
1765: sub flushcourselogs {
1766: &logthis('Flushing log buffers');
1767: #
1768: # course logs
1769: # This is a log of all transactions in a course, which can be used
1770: # for data mining purposes
1771: #
1772: # It also collects the courseid database, which lists last transaction
1773: # times and course titles for all courseids
1774: #
1775: my %courseidbuffer=();
1776: foreach my $crsid (keys %courselogs) {
1777: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1778: &escape($courselogs{$crsid}),
1779: $coursehombuf{$crsid}) eq 'ok') {
1780: delete $courselogs{$crsid};
1781: } else {
1782: &logthis('Failed to flush log buffer for '.$crsid);
1783: if (length($courselogs{$crsid})>40000) {
1784: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1785: " exceeded maximum size, deleting.</font>");
1786: delete $courselogs{$crsid};
1787: }
1788: }
1789: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1790: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1791: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1792: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1793: } else {
1794: $courseidbuffer{$coursehombuf{$crsid}}=
1795: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1796: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1797: }
1798: }
1799: #
1800: # Write course id database (reverse lookup) to homeserver of courses
1801: # Is used in pickcourse
1802: #
1803: foreach my $crsid (keys(%courseidbuffer)) {
1804: &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1805: }
1806: #
1807: # File accesses
1808: # Writes to the dynamic metadata of resources to get hit counts, etc.
1809: #
1810: foreach my $entry (keys(%accesshash)) {
1811: if ($entry =~ /___count$/) {
1812: my ($dom,$name);
1813: ($dom,$name,undef)=
1814: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1815: if (! defined($dom) || $dom eq '' ||
1816: ! defined($name) || $name eq '') {
1817: my $cid = $env{'request.course.id'};
1818: $dom = $env{'request.'.$cid.'.domain'};
1819: $name = $env{'request.'.$cid.'.num'};
1820: }
1821: my $value = $accesshash{$entry};
1822: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1823: my %temphash=($url => $value);
1824: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1825: if ($result eq 'ok') {
1826: delete $accesshash{$entry};
1827: } elsif ($result eq 'unknown_cmd') {
1828: # Target server has old code running on it.
1829: my %temphash=($entry => $value);
1830: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1831: delete $accesshash{$entry};
1832: }
1833: }
1834: } else {
1835: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1836: my %temphash=($entry => $accesshash{$entry});
1837: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1838: delete $accesshash{$entry};
1839: }
1840: }
1841: }
1842: #
1843: # Roles
1844: # Reverse lookup of user roles for course faculty/staff and co-authorship
1845: #
1846: foreach my $entry (keys(%userrolehash)) {
1847: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1848: split(/\:/,$entry);
1849: if (&Apache::lonnet::put('nohist_userroles',
1850: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1851: $rudom,$runame) eq 'ok') {
1852: delete $userrolehash{$entry};
1853: }
1854: }
1855: #
1856: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1857: #
1858: my %domrolebuffer = ();
1859: foreach my $entry (keys %domainrolehash) {
1860: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1861: if ($domrolebuffer{$rudom}) {
1862: $domrolebuffer{$rudom}.='&'.&escape($entry).
1863: '='.&escape($domainrolehash{$entry});
1864: } else {
1865: $domrolebuffer{$rudom}.=&escape($entry).
1866: '='.&escape($domainrolehash{$entry});
1867: }
1868: delete $domainrolehash{$entry};
1869: }
1870: foreach my $dom (keys(%domrolebuffer)) {
1871: foreach my $tryserver (keys %libserv) {
1872: if ($hostdom{$tryserver} eq $dom) {
1873: unless (&reply('domroleput:'.$dom.':'.
1874: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1875: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1876: }
1877: }
1878: }
1879: }
1880: $dumpcount++;
1881: }
1882:
1883: sub courselog {
1884: my $what=shift;
1885: $what=time.':'.$what;
1886: unless ($env{'request.course.id'}) { return ''; }
1887: $coursedombuf{$env{'request.course.id'}}=
1888: $env{'course.'.$env{'request.course.id'}.'.domain'};
1889: $coursenumbuf{$env{'request.course.id'}}=
1890: $env{'course.'.$env{'request.course.id'}.'.num'};
1891: $coursehombuf{$env{'request.course.id'}}=
1892: $env{'course.'.$env{'request.course.id'}.'.home'};
1893: $coursedescrbuf{$env{'request.course.id'}}=
1894: $env{'course.'.$env{'request.course.id'}.'.description'};
1895: $courseinstcodebuf{$env{'request.course.id'}}=
1896: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1897: $courseownerbuf{$env{'request.course.id'}}=
1898: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1899: $coursetypebuf{$env{'request.course.id'}}=
1900: $env{'course.'.$env{'request.course.id'}.'.type'};
1901: if (defined $courselogs{$env{'request.course.id'}}) {
1902: $courselogs{$env{'request.course.id'}}.='&'.$what;
1903: } else {
1904: $courselogs{$env{'request.course.id'}}.=$what;
1905: }
1906: if (length($courselogs{$env{'request.course.id'}})>4048) {
1907: &flushcourselogs();
1908: }
1909: }
1910:
1911: sub courseacclog {
1912: my $fnsymb=shift;
1913: unless ($env{'request.course.id'}) { return ''; }
1914: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1915: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1916: $what.=':POST';
1917: # FIXME: Probably ought to escape things....
1918: foreach my $key (keys(%env)) {
1919: if ($key=~/^form\.(.*)/) {
1920: $what.=':'.$1.'='.$env{$key};
1921: }
1922: }
1923: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1924: # FIXME: We should not be depending on a form parameter that someone
1925: # editing lonsearchcat.pm might change in the future.
1926: if ($env{'form.phase'} eq 'course_search') {
1927: $what.= ':POST';
1928: # FIXME: Probably ought to escape things....
1929: foreach my $element ('courseexp','crsfulltext','crsrelated',
1930: 'crsdiscuss') {
1931: $what.=':'.$element.'='.$env{'form.'.$element};
1932: }
1933: }
1934: }
1935: &courselog($what);
1936: }
1937:
1938: sub countacc {
1939: my $url=&declutter(shift);
1940: return if (! defined($url) || $url eq '');
1941: unless ($env{'request.course.id'}) { return ''; }
1942: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1943: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1944: $accesshash{$key}++;
1945: }
1946:
1947: sub linklog {
1948: my ($from,$to)=@_;
1949: $from=&declutter($from);
1950: $to=&declutter($to);
1951: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1952: $accesshash{$to.'___'.$from.'___goto'}=1;
1953: }
1954:
1955: sub userrolelog {
1956: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1957: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1958: ($trole=~/^in/) || ($trole=~/^cc/) ||
1959: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1960: ($trole=~/^ta/)) {
1961: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1962: $userrolehash
1963: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1964: =$tend.':'.$tstart;
1965: }
1966: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
1967: ($trole=~/^li/) || ($trole=~/^li/) ||
1968: ($trole=~/^au/) || ($trole=~/^dg/) ||
1969: ($trole=~/^sc/)) {
1970: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1971: $domainrolehash
1972: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1973: = $tend.':'.$tstart;
1974: }
1975: }
1976:
1977: sub get_course_adv_roles {
1978: my $cid=shift;
1979: $cid=$env{'request.course.id'} unless (defined($cid));
1980: my %coursehash=&coursedescription($cid);
1981: my %nothide=();
1982: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1983: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1984: }
1985: my %returnhash=();
1986: my %dumphash=
1987: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1988: my $now=time;
1989: foreach my $entry (keys %dumphash) {
1990: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1991: if (($tstart) && ($tstart<0)) { next; }
1992: if (($tend) && ($tend<$now)) { next; }
1993: if (($tstart) && ($now<$tstart)) { next; }
1994: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1995: if ($username eq '' || $domain eq '') { next; }
1996: if ((&privileged($username,$domain)) &&
1997: (!$nothide{$username.':'.$domain})) { next; }
1998: if ($role eq 'cr') { next; }
1999: my $key=&plaintext($role);
2000: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2001: if ($returnhash{$key}) {
2002: $returnhash{$key}.=','.$username.':'.$domain;
2003: } else {
2004: $returnhash{$key}=$username.':'.$domain;
2005: }
2006: }
2007: return %returnhash;
2008: }
2009:
2010: sub get_my_roles {
2011: my ($uname,$udom)=@_;
2012: unless (defined($uname)) { $uname=$env{'user.name'}; }
2013: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2014: my %dumphash=
2015: &dump('nohist_userroles',$udom,$uname);
2016: my %returnhash=();
2017: my $now=time;
2018: foreach my $entry (keys(%dumphash)) {
2019: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2020: if (($tstart) && ($tstart<0)) { next; }
2021: if (($tend) && ($tend<$now)) { next; }
2022: if (($tstart) && ($now<$tstart)) { next; }
2023: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2024: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2025: }
2026: return %returnhash;
2027: }
2028:
2029: # ----------------------------------------------------- Frontpage Announcements
2030: #
2031: #
2032:
2033: sub postannounce {
2034: my ($server,$text)=@_;
2035: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
2036: unless ($text=~/\w/) { $text=''; }
2037: return &reply('setannounce:'.&escape($text),$server);
2038: }
2039:
2040: sub getannounce {
2041:
2042: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2043: my $announcement='';
2044: while (my $line = <$fh>) { $announcement .= $line; }
2045: close($fh);
2046: if ($announcement=~/\w/) {
2047: return
2048: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2049: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2050: } else {
2051: return '';
2052: }
2053: } else {
2054: return '';
2055: }
2056: }
2057:
2058: # ---------------------------------------------------------- Course ID routines
2059: # Deal with domain's nohist_courseid.db files
2060: #
2061:
2062: sub courseidput {
2063: my ($domain,$what,$coursehome)=@_;
2064: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2065: }
2066:
2067: sub courseiddump {
2068: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
2069: my %returnhash=();
2070: unless ($domfilter) { $domfilter=''; }
2071: foreach my $tryserver (keys %libserv) {
2072: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
2073: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
2074: foreach my $line (
2075: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
2076: $sincefilter.':'.&escape($descfilter).':'.
2077: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
2078: $tryserver))) {
2079: my ($key,$value)=split(/\=/,$line,2);
2080: if (($key) && ($value)) {
2081: $returnhash{&unescape($key)}=$value;
2082: }
2083: }
2084: }
2085: }
2086: }
2087: return %returnhash;
2088: }
2089:
2090: # ---------------------------------------------------------- DC e-mail
2091:
2092: sub dcmailput {
2093: my ($domain,$msgid,$message,$server)=@_;
2094: my $status = &Apache::lonnet::critical(
2095: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2096: &escape($message),$server);
2097: return $status;
2098: }
2099:
2100: sub dcmaildump {
2101: my ($dom,$startdate,$enddate,$senders) = @_;
2102: my %returnhash=();
2103: if (exists($domain_primary{$dom})) {
2104: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2105: &escape($enddate).':';
2106: my @esc_senders=map { &escape($_)} @$senders;
2107: $cmd.=&escape(join('&',@esc_senders));
2108: foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
2109: my ($key,$value) = split(/\=/,$line,2);
2110: if (($key) && ($value)) {
2111: $returnhash{&unescape($key)} = &unescape($value);
2112: }
2113: }
2114: }
2115: return %returnhash;
2116: }
2117: # ---------------------------------------------------------- Domain roles
2118:
2119: sub get_domain_roles {
2120: my ($dom,$roles,$startdate,$enddate)=@_;
2121: if (undef($startdate) || $startdate eq '') {
2122: $startdate = '.';
2123: }
2124: if (undef($enddate) || $enddate eq '') {
2125: $enddate = '.';
2126: }
2127: my $rolelist = join(':',@{$roles});
2128: my %personnel = ();
2129: foreach my $tryserver (keys(%libserv)) {
2130: if ($hostdom{$tryserver} eq $dom) {
2131: %{$personnel{$tryserver}}=();
2132: foreach my $line (
2133: split(/\&/,&reply('domrolesdump:'.$dom.':'.
2134: &escape($startdate).':'.&escape($enddate).':'.
2135: &escape($rolelist), $tryserver))) {
2136: my ($key,$value) = split(/\=/,$line,2);
2137: if (($key) && ($value)) {
2138: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2139: }
2140: }
2141: }
2142: }
2143: return %personnel;
2144: }
2145:
2146: # ----------------------------------------------------------- Check out an item
2147:
2148: sub get_first_access {
2149: my ($type,$argsymb)=@_;
2150: my ($symb,$courseid,$udom,$uname)=&whichuser();
2151: if ($argsymb) { $symb=$argsymb; }
2152: my ($map,$id,$res)=&decode_symb($symb);
2153: if ($type eq 'map') {
2154: $res=&symbread($map);
2155: } else {
2156: $res=$symb;
2157: }
2158: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2159: return $times{"$courseid\0$res"};
2160: }
2161:
2162: sub set_first_access {
2163: my ($type)=@_;
2164: my ($symb,$courseid,$udom,$uname)=&whichuser();
2165: my ($map,$id,$res)=&decode_symb($symb);
2166: if ($type eq 'map') {
2167: $res=&symbread($map);
2168: } else {
2169: $res=$symb;
2170: }
2171: my $firstaccess=&get_first_access($type,$symb);
2172: if (!$firstaccess) {
2173: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2174: }
2175: return 'already_set';
2176: }
2177:
2178: sub checkout {
2179: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2180: my $now=time;
2181: my $lonhost=$perlvar{'lonHostID'};
2182: my $infostr=&escape(
2183: 'CHECKOUTTOKEN&'.
2184: $tuname.'&'.
2185: $tudom.'&'.
2186: $tcrsid.'&'.
2187: $symb.'&'.
2188: $now.'&'.$ENV{'REMOTE_ADDR'});
2189: my $token=&reply('tmpput:'.$infostr,$lonhost);
2190: if ($token=~/^error\:/) {
2191: &logthis("<font color=\"blue\">WARNING: ".
2192: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2193: "</font>");
2194: return '';
2195: }
2196:
2197: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2198: $token=~tr/a-z/A-Z/;
2199:
2200: my %infohash=('resource.0.outtoken' => $token,
2201: 'resource.0.checkouttime' => $now,
2202: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2203:
2204: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2205: return '';
2206: } else {
2207: &logthis("<font color=\"blue\">WARNING: ".
2208: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2209: "</font>");
2210: }
2211:
2212: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2213: &escape('Checkout '.$infostr.' - '.
2214: $token)) ne 'ok') {
2215: return '';
2216: } else {
2217: &logthis("<font color=\"blue\">WARNING: ".
2218: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2219: "</font>");
2220: }
2221: return $token;
2222: }
2223:
2224: # ------------------------------------------------------------ Check in an item
2225:
2226: sub checkin {
2227: my $token=shift;
2228: my $now=time;
2229: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2230: $lonhost=~tr/A-Z/a-z/;
2231: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
2232: $dtoken=~s/\W/\_/g;
2233: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2234: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2235:
2236: unless (($tuname) && ($tudom)) {
2237: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2238: return '';
2239: }
2240:
2241: unless (&allowed('mgr',$tcrsid)) {
2242: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
2243: $env{'user.name'}.' - '.$env{'user.domain'});
2244: return '';
2245: }
2246:
2247: my %infohash=('resource.0.intoken' => $token,
2248: 'resource.0.checkintime' => $now,
2249: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
2250:
2251: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2252: return '';
2253: }
2254:
2255: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2256: &escape('Checkin - '.$token)) ne 'ok') {
2257: return '';
2258: }
2259:
2260: return ($symb,$tuname,$tudom,$tcrsid);
2261: }
2262:
2263: # --------------------------------------------- Set Expire Date for Spreadsheet
2264:
2265: sub expirespread {
2266: my ($uname,$udom,$stype,$usymb)=@_;
2267: my $cid=$env{'request.course.id'};
2268: if ($cid) {
2269: my $now=time;
2270: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2271: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2272: $env{'course.'.$cid.'.num'}.
2273: ':nohist_expirationdates:'.
2274: &escape($key).'='.$now,
2275: $env{'course.'.$cid.'.home'})
2276: }
2277: return 'ok';
2278: }
2279:
2280: # ----------------------------------------------------- Devalidate Spreadsheets
2281:
2282: sub devalidate {
2283: my ($symb,$uname,$udom)=@_;
2284: my $cid=$env{'request.course.id'};
2285: if ($cid) {
2286: # delete the stored spreadsheets for
2287: # - the student level sheet of this user in course's homespace
2288: # - the assessment level sheet for this resource
2289: # for this user in user's homespace
2290: # - current conditional state info
2291: my $key=$uname.':'.$udom.':';
2292: my $status=
2293: &del('nohist_calculatedsheets',
2294: [$key.'studentcalc:'],
2295: $env{'course.'.$cid.'.domain'},
2296: $env{'course.'.$cid.'.num'})
2297: .' '.
2298: &del('nohist_calculatedsheets_'.$cid,
2299: [$key.'assesscalc:'.$symb],$udom,$uname);
2300: unless ($status eq 'ok ok') {
2301: &logthis('Could not devalidate spreadsheet '.
2302: $uname.' at '.$udom.' for '.
2303: $symb.': '.$status);
2304: }
2305: &delenv('user.state.'.$cid);
2306: }
2307: }
2308:
2309: sub get_scalar {
2310: my ($string,$end) = @_;
2311: my $value;
2312: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2313: $value = $1;
2314: } elsif ($$string =~ s/^([^&]*?)&//) {
2315: $value = $1;
2316: }
2317: return &unescape($value);
2318: }
2319:
2320: sub array2str {
2321: my (@array) = @_;
2322: my $result=&arrayref2str(\@array);
2323: $result=~s/^__ARRAY_REF__//;
2324: $result=~s/__END_ARRAY_REF__$//;
2325: return $result;
2326: }
2327:
2328: sub arrayref2str {
2329: my ($arrayref) = @_;
2330: my $result='__ARRAY_REF__';
2331: foreach my $elem (@$arrayref) {
2332: if(ref($elem) eq 'ARRAY') {
2333: $result.=&arrayref2str($elem).'&';
2334: } elsif(ref($elem) eq 'HASH') {
2335: $result.=&hashref2str($elem).'&';
2336: } elsif(ref($elem)) {
2337: #print("Got a ref of ".(ref($elem))." skipping.");
2338: } else {
2339: $result.=&escape($elem).'&';
2340: }
2341: }
2342: $result=~s/\&$//;
2343: $result .= '__END_ARRAY_REF__';
2344: return $result;
2345: }
2346:
2347: sub hash2str {
2348: my (%hash) = @_;
2349: my $result=&hashref2str(\%hash);
2350: $result=~s/^__HASH_REF__//;
2351: $result=~s/__END_HASH_REF__$//;
2352: return $result;
2353: }
2354:
2355: sub hashref2str {
2356: my ($hashref)=@_;
2357: my $result='__HASH_REF__';
2358: foreach my $key (sort(keys(%$hashref))) {
2359: if (ref($key) eq 'ARRAY') {
2360: $result.=&arrayref2str($key).'=';
2361: } elsif (ref($key) eq 'HASH') {
2362: $result.=&hashref2str($key).'=';
2363: } elsif (ref($key)) {
2364: $result.='=';
2365: #print("Got a ref of ".(ref($key))." skipping.");
2366: } else {
2367: if ($key) {$result.=&escape($key).'=';} else { last; }
2368: }
2369:
2370: if(ref($hashref->{$key}) eq 'ARRAY') {
2371: $result.=&arrayref2str($hashref->{$key}).'&';
2372: } elsif(ref($hashref->{$key}) eq 'HASH') {
2373: $result.=&hashref2str($hashref->{$key}).'&';
2374: } elsif(ref($hashref->{$key})) {
2375: $result.='&';
2376: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
2377: } else {
2378: $result.=&escape($hashref->{$key}).'&';
2379: }
2380: }
2381: $result=~s/\&$//;
2382: $result .= '__END_HASH_REF__';
2383: return $result;
2384: }
2385:
2386: sub str2hash {
2387: my ($string)=@_;
2388: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2389: return %$hash;
2390: }
2391:
2392: sub str2hashref {
2393: my ($string) = @_;
2394:
2395: my %hash;
2396:
2397: if($string !~ /^__HASH_REF__/) {
2398: if (! ($string eq '' || !defined($string))) {
2399: $hash{'error'}='Not hash reference';
2400: }
2401: return (\%hash, $string);
2402: }
2403:
2404: $string =~ s/^__HASH_REF__//;
2405:
2406: while($string !~ /^__END_HASH_REF__/) {
2407: #key
2408: my $key='';
2409: if($string =~ /^__HASH_REF__/) {
2410: ($key, $string)=&str2hashref($string);
2411: if(defined($key->{'error'})) {
2412: $hash{'error'}='Bad data';
2413: return (\%hash, $string);
2414: }
2415: } elsif($string =~ /^__ARRAY_REF__/) {
2416: ($key, $string)=&str2arrayref($string);
2417: if($key->[0] eq 'Array reference error') {
2418: $hash{'error'}='Bad data';
2419: return (\%hash, $string);
2420: }
2421: } else {
2422: $string =~ s/^(.*?)=//;
2423: $key=&unescape($1);
2424: }
2425: $string =~ s/^=//;
2426:
2427: #value
2428: my $value='';
2429: if($string =~ /^__HASH_REF__/) {
2430: ($value, $string)=&str2hashref($string);
2431: if(defined($value->{'error'})) {
2432: $hash{'error'}='Bad data';
2433: return (\%hash, $string);
2434: }
2435: } elsif($string =~ /^__ARRAY_REF__/) {
2436: ($value, $string)=&str2arrayref($string);
2437: if($value->[0] eq 'Array reference error') {
2438: $hash{'error'}='Bad data';
2439: return (\%hash, $string);
2440: }
2441: } else {
2442: $value=&get_scalar(\$string,'__END_HASH_REF__');
2443: }
2444: $string =~ s/^&//;
2445:
2446: $hash{$key}=$value;
2447: }
2448:
2449: $string =~ s/^__END_HASH_REF__//;
2450:
2451: return (\%hash, $string);
2452: }
2453:
2454: sub str2array {
2455: my ($string)=@_;
2456: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2457: return @$array;
2458: }
2459:
2460: sub str2arrayref {
2461: my ($string) = @_;
2462: my @array;
2463:
2464: if($string !~ /^__ARRAY_REF__/) {
2465: if (! ($string eq '' || !defined($string))) {
2466: $array[0]='Array reference error';
2467: }
2468: return (\@array, $string);
2469: }
2470:
2471: $string =~ s/^__ARRAY_REF__//;
2472:
2473: while($string !~ /^__END_ARRAY_REF__/) {
2474: my $value='';
2475: if($string =~ /^__HASH_REF__/) {
2476: ($value, $string)=&str2hashref($string);
2477: if(defined($value->{'error'})) {
2478: $array[0] ='Array reference error';
2479: return (\@array, $string);
2480: }
2481: } elsif($string =~ /^__ARRAY_REF__/) {
2482: ($value, $string)=&str2arrayref($string);
2483: if($value->[0] eq 'Array reference error') {
2484: $array[0] ='Array reference error';
2485: return (\@array, $string);
2486: }
2487: } else {
2488: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2489: }
2490: $string =~ s/^&//;
2491:
2492: push(@array, $value);
2493: }
2494:
2495: $string =~ s/^__END_ARRAY_REF__//;
2496:
2497: return (\@array, $string);
2498: }
2499:
2500: # -------------------------------------------------------------------Temp Store
2501:
2502: sub tmpreset {
2503: my ($symb,$namespace,$domain,$stuname) = @_;
2504: if (!$symb) {
2505: $symb=&symbread();
2506: if (!$symb) { $symb= $env{'request.url'}; }
2507: }
2508: $symb=escape($symb);
2509:
2510: if (!$namespace) { $namespace=$env{'request.state'}; }
2511: $namespace=~s/\//\_/g;
2512: $namespace=~s/\W//g;
2513:
2514: if (!$domain) { $domain=$env{'user.domain'}; }
2515: if (!$stuname) { $stuname=$env{'user.name'}; }
2516: if ($domain eq 'public' && $stuname eq 'public') {
2517: $stuname=$ENV{'REMOTE_ADDR'};
2518: }
2519: my $path=$perlvar{'lonDaemons'}.'/tmp';
2520: my %hash;
2521: if (tie(%hash,'GDBM_File',
2522: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2523: &GDBM_WRCREAT(),0640)) {
2524: foreach my $key (keys %hash) {
2525: if ($key=~ /:$symb/) {
2526: delete($hash{$key});
2527: }
2528: }
2529: }
2530: }
2531:
2532: sub tmpstore {
2533: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2534:
2535: if (!$symb) {
2536: $symb=&symbread();
2537: if (!$symb) { $symb= $env{'request.url'}; }
2538: }
2539: $symb=escape($symb);
2540:
2541: if (!$namespace) {
2542: # I don't think we would ever want to store this for a course.
2543: # it seems this will only be used if we don't have a course.
2544: #$namespace=$env{'request.course.id'};
2545: #if (!$namespace) {
2546: $namespace=$env{'request.state'};
2547: #}
2548: }
2549: $namespace=~s/\//\_/g;
2550: $namespace=~s/\W//g;
2551: if (!$domain) { $domain=$env{'user.domain'}; }
2552: if (!$stuname) { $stuname=$env{'user.name'}; }
2553: if ($domain eq 'public' && $stuname eq 'public') {
2554: $stuname=$ENV{'REMOTE_ADDR'};
2555: }
2556: my $now=time;
2557: my %hash;
2558: my $path=$perlvar{'lonDaemons'}.'/tmp';
2559: if (tie(%hash,'GDBM_File',
2560: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2561: &GDBM_WRCREAT(),0640)) {
2562: $hash{"version:$symb"}++;
2563: my $version=$hash{"version:$symb"};
2564: my $allkeys='';
2565: foreach my $key (keys(%$storehash)) {
2566: $allkeys.=$key.':';
2567: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
2568: }
2569: $hash{"$version:$symb:timestamp"}=$now;
2570: $allkeys.='timestamp';
2571: $hash{"$version:keys:$symb"}=$allkeys;
2572: if (untie(%hash)) {
2573: return 'ok';
2574: } else {
2575: return "error:$!";
2576: }
2577: } else {
2578: return "error:$!";
2579: }
2580: }
2581:
2582: # -----------------------------------------------------------------Temp Restore
2583:
2584: sub tmprestore {
2585: my ($symb,$namespace,$domain,$stuname) = @_;
2586:
2587: if (!$symb) {
2588: $symb=&symbread();
2589: if (!$symb) { $symb= $env{'request.url'}; }
2590: }
2591: $symb=escape($symb);
2592:
2593: if (!$namespace) { $namespace=$env{'request.state'}; }
2594:
2595: if (!$domain) { $domain=$env{'user.domain'}; }
2596: if (!$stuname) { $stuname=$env{'user.name'}; }
2597: if ($domain eq 'public' && $stuname eq 'public') {
2598: $stuname=$ENV{'REMOTE_ADDR'};
2599: }
2600: my %returnhash;
2601: $namespace=~s/\//\_/g;
2602: $namespace=~s/\W//g;
2603: my %hash;
2604: my $path=$perlvar{'lonDaemons'}.'/tmp';
2605: if (tie(%hash,'GDBM_File',
2606: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2607: &GDBM_READER(),0640)) {
2608: my $version=$hash{"version:$symb"};
2609: $returnhash{'version'}=$version;
2610: my $scope;
2611: for ($scope=1;$scope<=$version;$scope++) {
2612: my $vkeys=$hash{"$scope:keys:$symb"};
2613: my @keys=split(/:/,$vkeys);
2614: my $key;
2615: $returnhash{"$scope:keys"}=$vkeys;
2616: foreach $key (@keys) {
2617: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2618: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2619: }
2620: }
2621: if (!(untie(%hash))) {
2622: return "error:$!";
2623: }
2624: } else {
2625: return "error:$!";
2626: }
2627: return %returnhash;
2628: }
2629:
2630: # ----------------------------------------------------------------------- Store
2631:
2632: sub store {
2633: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2634: my $home='';
2635:
2636: if ($stuname) { $home=&homeserver($stuname,$domain); }
2637:
2638: $symb=&symbclean($symb);
2639: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2640:
2641: if (!$domain) { $domain=$env{'user.domain'}; }
2642: if (!$stuname) { $stuname=$env{'user.name'}; }
2643:
2644: &devalidate($symb,$stuname,$domain);
2645:
2646: $symb=escape($symb);
2647: if (!$namespace) {
2648: unless ($namespace=$env{'request.course.id'}) {
2649: return '';
2650: }
2651: }
2652: if (!$home) { $home=$env{'user.home'}; }
2653:
2654: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2655: $$storehash{'host'}=$perlvar{'lonHostID'};
2656:
2657: my $namevalue='';
2658: foreach my $key (keys(%$storehash)) {
2659: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2660: }
2661: $namevalue=~s/\&$//;
2662: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2663: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2664: }
2665:
2666: # -------------------------------------------------------------- Critical Store
2667:
2668: sub cstore {
2669: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2670: my $home='';
2671:
2672: if ($stuname) { $home=&homeserver($stuname,$domain); }
2673:
2674: $symb=&symbclean($symb);
2675: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2676:
2677: if (!$domain) { $domain=$env{'user.domain'}; }
2678: if (!$stuname) { $stuname=$env{'user.name'}; }
2679:
2680: &devalidate($symb,$stuname,$domain);
2681:
2682: $symb=escape($symb);
2683: if (!$namespace) {
2684: unless ($namespace=$env{'request.course.id'}) {
2685: return '';
2686: }
2687: }
2688: if (!$home) { $home=$env{'user.home'}; }
2689:
2690: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2691: $$storehash{'host'}=$perlvar{'lonHostID'};
2692:
2693: my $namevalue='';
2694: foreach my $key (keys(%$storehash)) {
2695: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2696: }
2697: $namevalue=~s/\&$//;
2698: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2699: return critical
2700: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2701: }
2702:
2703: # --------------------------------------------------------------------- Restore
2704:
2705: sub restore {
2706: my ($symb,$namespace,$domain,$stuname) = @_;
2707: my $home='';
2708:
2709: if ($stuname) { $home=&homeserver($stuname,$domain); }
2710:
2711: if (!$symb) {
2712: unless ($symb=escape(&symbread())) { return ''; }
2713: } else {
2714: $symb=&escape(&symbclean($symb));
2715: }
2716: if (!$namespace) {
2717: unless ($namespace=$env{'request.course.id'}) {
2718: return '';
2719: }
2720: }
2721: if (!$domain) { $domain=$env{'user.domain'}; }
2722: if (!$stuname) { $stuname=$env{'user.name'}; }
2723: if (!$home) { $home=$env{'user.home'}; }
2724: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2725:
2726: my %returnhash=();
2727: foreach my $line (split(/\&/,$answer)) {
2728: my ($name,$value)=split(/\=/,$line);
2729: $returnhash{&unescape($name)}=&thaw_unescape($value);
2730: }
2731: my $version;
2732: for ($version=1;$version<=$returnhash{'version'};$version++) {
2733: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2734: $returnhash{$item}=$returnhash{$version.':'.$item};
2735: }
2736: }
2737: return %returnhash;
2738: }
2739:
2740: # ---------------------------------------------------------- Course Description
2741:
2742: sub coursedescription {
2743: my ($courseid,$args)=@_;
2744: $courseid=~s/^\///;
2745: $courseid=~s/\_/\//g;
2746: my ($cdomain,$cnum)=split(/\//,$courseid);
2747: my $chome=&homeserver($cnum,$cdomain);
2748: my $normalid=$cdomain.'_'.$cnum;
2749: # need to always cache even if we get errors otherwise we keep
2750: # trying and trying and trying to get the course description.
2751: my %envhash=();
2752: my %returnhash=();
2753:
2754: my $expiretime=600;
2755: if ($env{'request.course.id'} eq $normalid) {
2756: $expiretime=120;
2757: }
2758:
2759: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2760: if (!$args->{'freshen_cache'}
2761: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2762: foreach my $key (keys(%env)) {
2763: next if ($key !~ /^\Q$prefix\E(.*)/);
2764: my ($setting) = $1;
2765: $returnhash{$setting} = $env{$key};
2766: }
2767: return %returnhash;
2768: }
2769:
2770: # get the data agin
2771: if (!$args->{'one_time'}) {
2772: $envhash{'course.'.$normalid.'.last_cache'}=time;
2773: }
2774:
2775: if ($chome ne 'no_host') {
2776: %returnhash=&dump('environment',$cdomain,$cnum);
2777: if (!exists($returnhash{'con_lost'})) {
2778: $returnhash{'home'}= $chome;
2779: $returnhash{'domain'} = $cdomain;
2780: $returnhash{'num'} = $cnum;
2781: if (!defined($returnhash{'type'})) {
2782: $returnhash{'type'} = 'Course';
2783: }
2784: while (my ($name,$value) = each %returnhash) {
2785: $envhash{'course.'.$normalid.'.'.$name}=$value;
2786: }
2787: $returnhash{'url'}=&clutter($returnhash{'url'});
2788: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2789: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2790: $envhash{'course.'.$normalid.'.home'}=$chome;
2791: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2792: $envhash{'course.'.$normalid.'.num'}=$cnum;
2793: }
2794: }
2795: if (!$args->{'one_time'}) {
2796: &appenv(%envhash);
2797: }
2798: return %returnhash;
2799: }
2800:
2801: # -------------------------------------------------See if a user is privileged
2802:
2803: sub privileged {
2804: my ($username,$domain)=@_;
2805: my $rolesdump=&reply("dump:$domain:$username:roles",
2806: &homeserver($username,$domain));
2807: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2808: my $now=time;
2809: if ($rolesdump ne '') {
2810: foreach my $entry (split(/&/,$rolesdump)) {
2811: if ($entry!~/^rolesdef_/) {
2812: my ($area,$role)=split(/=/,$entry);
2813: $area=~s/\_\w\w$//;
2814: my ($trole,$tend,$tstart)=split(/_/,$role);
2815: if (($trole eq 'dc') || ($trole eq 'su')) {
2816: my $active=1;
2817: if ($tend) {
2818: if ($tend<$now) { $active=0; }
2819: }
2820: if ($tstart) {
2821: if ($tstart>$now) { $active=0; }
2822: }
2823: if ($active) { return 1; }
2824: }
2825: }
2826: }
2827: }
2828: return 0;
2829: }
2830:
2831: # -------------------------------------------------------- Get user privileges
2832:
2833: sub rolesinit {
2834: my ($domain,$username,$authhost)=@_;
2835: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
2836: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
2837: my %allroles=();
2838: my %allgroups=();
2839: my $now=time;
2840: my %userroles = ('user.login.time' => $now);
2841: my $group_privs;
2842:
2843: if ($rolesdump ne '') {
2844: foreach my $entry (split(/&/,$rolesdump)) {
2845: if ($entry!~/^rolesdef_/) {
2846: my ($area,$role)=split(/=/,$entry);
2847: $area=~s/\_\w\w$//;
2848: my ($trole,$tend,$tstart,$group_privs);
2849: if ($role=~/^cr/) {
2850: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
2851: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
2852: ($tend,$tstart)=split('_',$trest);
2853: } else {
2854: $trole=$role;
2855: }
2856: } elsif ($role =~ m|^gr/|) {
2857: ($trole,$tend,$tstart) = split(/_/,$role);
2858: ($trole,$group_privs) = split(/\//,$trole);
2859: $group_privs = &unescape($group_privs);
2860: } else {
2861: ($trole,$tend,$tstart)=split(/_/,$role);
2862: }
2863: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2864: $username);
2865: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
2866: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2867: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2868: if (($area ne '') && ($trole ne '')) {
2869: my $spec=$trole.'.'.$area;
2870: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2871: if ($trole =~ /^cr\//) {
2872: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2873: } elsif ($trole eq 'gr') {
2874: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
2875: } else {
2876: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2877: }
2878: }
2879: }
2880: }
2881: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2882: $userroles{'user.adv'} = $adv;
2883: $userroles{'user.author'} = $author;
2884: $env{'user.adv'}=$adv;
2885: }
2886: return \%userroles;
2887: }
2888:
2889: sub set_arearole {
2890: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2891: # log the associated role with the area
2892: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2893: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
2894: }
2895:
2896: sub custom_roleprivs {
2897: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2898: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2899: my $homsvr=homeserver($rauthor,$rdomain);
2900: if ($hostname{$homsvr} ne '') {
2901: my ($rdummy,$roledef)=
2902: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2903: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2904: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2905: if (defined($syspriv)) {
2906: $$allroles{'cm./'}.=':'.$syspriv;
2907: $$allroles{$spec.'./'}.=':'.$syspriv;
2908: }
2909: if ($tdomain ne '') {
2910: if (defined($dompriv)) {
2911: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2912: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2913: }
2914: if (($trest ne '') && (defined($coursepriv))) {
2915: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2916: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2917: }
2918: }
2919: }
2920: }
2921: }
2922:
2923: sub group_roleprivs {
2924: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
2925: my $access = 1;
2926: my $now = time;
2927: if (($tend!=0) && ($tend<$now)) { $access = 0; }
2928: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
2929: if ($access) {
2930: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
2931: $$allgroups{$course}{$group} .=':'.$group_privs;
2932: }
2933: }
2934:
2935: sub standard_roleprivs {
2936: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2937: if (defined($pr{$trole.':s'})) {
2938: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2939: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2940: }
2941: if ($tdomain ne '') {
2942: if (defined($pr{$trole.':d'})) {
2943: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2944: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2945: }
2946: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2947: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2948: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2949: }
2950: }
2951: }
2952:
2953: sub set_userprivs {
2954: my ($userroles,$allroles,$allgroups) = @_;
2955: my $author=0;
2956: my $adv=0;
2957: my %grouproles = ();
2958: if (keys(%{$allgroups}) > 0) {
2959: foreach my $role (keys %{$allroles}) {
2960: my ($trole,$area,$sec,$extendedarea);
2961: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
2962: $trole = $1;
2963: $area = $2;
2964: $sec = $3;
2965: $extendedarea = $area.$sec;
2966: if (exists($$allgroups{$area})) {
2967: foreach my $group (keys(%{$$allgroups{$area}})) {
2968: my $spec = $trole.'.'.$extendedarea;
2969: $grouproles{$spec.'.'.$area.'/'.$group} =
2970: $$allgroups{$area}{$group};
2971: }
2972: }
2973: }
2974: }
2975: }
2976: foreach my $group (keys(%grouproles)) {
2977: $$allroles{$group} = $grouproles{$group};
2978: }
2979: foreach my $role (keys(%{$allroles})) {
2980: my %thesepriv;
2981: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
2982: foreach my $item (split(/:/,$$allroles{$role})) {
2983: if ($item ne '') {
2984: my ($privilege,$restrictions)=split(/&/,$item);
2985: if ($restrictions eq '') {
2986: $thesepriv{$privilege}='F';
2987: } elsif ($thesepriv{$privilege} ne 'F') {
2988: $thesepriv{$privilege}.=$restrictions;
2989: }
2990: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2991: }
2992: }
2993: my $thesestr='';
2994: foreach my $priv (keys(%thesepriv)) {
2995: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
2996: }
2997: $userroles->{'user.priv.'.$role} = $thesestr;
2998: }
2999: return ($author,$adv);
3000: }
3001:
3002: # --------------------------------------------------------------- get interface
3003:
3004: sub get {
3005: my ($namespace,$storearr,$udomain,$uname)=@_;
3006: my $items='';
3007: foreach my $item (@$storearr) {
3008: $items.=&escape($item).'&';
3009: }
3010: $items=~s/\&$//;
3011: if (!$udomain) { $udomain=$env{'user.domain'}; }
3012: if (!$uname) { $uname=$env{'user.name'}; }
3013: my $uhome=&homeserver($uname,$udomain);
3014:
3015: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
3016: my @pairs=split(/\&/,$rep);
3017: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3018: return @pairs;
3019: }
3020: my %returnhash=();
3021: my $i=0;
3022: foreach my $item (@$storearr) {
3023: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3024: $i++;
3025: }
3026: return %returnhash;
3027: }
3028:
3029: # --------------------------------------------------------------- del interface
3030:
3031: sub del {
3032: my ($namespace,$storearr,$udomain,$uname)=@_;
3033: my $items='';
3034: foreach my $item (@$storearr) {
3035: $items.=&escape($item).'&';
3036: }
3037: $items=~s/\&$//;
3038: if (!$udomain) { $udomain=$env{'user.domain'}; }
3039: if (!$uname) { $uname=$env{'user.name'}; }
3040: my $uhome=&homeserver($uname,$udomain);
3041:
3042: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3043: }
3044:
3045: # -------------------------------------------------------------- dump interface
3046:
3047: sub dump {
3048: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3049: if (!$udomain) { $udomain=$env{'user.domain'}; }
3050: if (!$uname) { $uname=$env{'user.name'}; }
3051: my $uhome=&homeserver($uname,$udomain);
3052: if ($regexp) {
3053: $regexp=&escape($regexp);
3054: } else {
3055: $regexp='.';
3056: }
3057: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3058: my @pairs=split(/\&/,$rep);
3059: my %returnhash=();
3060: foreach my $item (@pairs) {
3061: my ($key,$value)=split(/=/,$item,2);
3062: $key = &unescape($key);
3063: next if ($key =~ /^error: 2 /);
3064: $returnhash{$key}=&thaw_unescape($value);
3065: }
3066: return %returnhash;
3067: }
3068:
3069: # --------------------------------------------------------- dumpstore interface
3070:
3071: sub dumpstore {
3072: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3073: if (!$udomain) { $udomain=$env{'user.domain'}; }
3074: if (!$uname) { $uname=$env{'user.name'}; }
3075: my $uhome=&homeserver($uname,$udomain);
3076: if ($regexp) {
3077: $regexp=&escape($regexp);
3078: } else {
3079: $regexp='.';
3080: }
3081: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3082: my @pairs=split(/\&/,$rep);
3083: my %returnhash=();
3084: foreach my $item (@pairs) {
3085: my ($key,$value)=split(/=/,$item,2);
3086: next if ($key =~ /^error: 2 /);
3087: $returnhash{$key}=&thaw_unescape($value);
3088: }
3089: return %returnhash;
3090: }
3091:
3092: # -------------------------------------------------------------- keys interface
3093:
3094: sub getkeys {
3095: my ($namespace,$udomain,$uname)=@_;
3096: if (!$udomain) { $udomain=$env{'user.domain'}; }
3097: if (!$uname) { $uname=$env{'user.name'}; }
3098: my $uhome=&homeserver($uname,$udomain);
3099: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3100: my @keyarray=();
3101: foreach my $key (split(/\&/,$rep)) {
3102: next if ($key =~ /^error: 2 /);
3103: push(@keyarray,&unescape($key));
3104: }
3105: return @keyarray;
3106: }
3107:
3108: # --------------------------------------------------------------- currentdump
3109: sub currentdump {
3110: my ($courseid,$sdom,$sname)=@_;
3111: $courseid = $env{'request.course.id'} if (! defined($courseid));
3112: $sdom = $env{'user.domain'} if (! defined($sdom));
3113: $sname = $env{'user.name'} if (! defined($sname));
3114: my $uhome = &homeserver($sname,$sdom);
3115: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3116: return if ($rep =~ /^(error:|no_such_host)/);
3117: #
3118: my %returnhash=();
3119: #
3120: if ($rep eq "unknown_cmd") {
3121: # an old lond will not know currentdump
3122: # Do a dump and make it look like a currentdump
3123: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
3124: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3125: my %hash = @tmp;
3126: @tmp=();
3127: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3128: } else {
3129: my @pairs=split(/\&/,$rep);
3130: foreach my $pair (@pairs) {
3131: my ($key,$value)=split(/=/,$pair,2);
3132: my ($symb,$param) = split(/:/,$key);
3133: $returnhash{&unescape($symb)}->{&unescape($param)} =
3134: &thaw_unescape($value);
3135: }
3136: }
3137: return %returnhash;
3138: }
3139:
3140: sub convert_dump_to_currentdump{
3141: my %hash = %{shift()};
3142: my %returnhash;
3143: # Code ripped from lond, essentially. The only difference
3144: # here is the unescaping done by lonnet::dump(). Conceivably
3145: # we might run in to problems with parameter names =~ /^v\./
3146: while (my ($key,$value) = each(%hash)) {
3147: my ($v,$symb,$param) = split(/:/,$key);
3148: $symb = &unescape($symb);
3149: $param = &unescape($param);
3150: next if ($v eq 'version' || $symb eq 'keys');
3151: next if (exists($returnhash{$symb}) &&
3152: exists($returnhash{$symb}->{$param}) &&
3153: $returnhash{$symb}->{'v.'.$param} > $v);
3154: $returnhash{$symb}->{$param}=$value;
3155: $returnhash{$symb}->{'v.'.$param}=$v;
3156: }
3157: #
3158: # Remove all of the keys in the hashes which keep track of
3159: # the version of the parameter.
3160: while (my ($symb,$param_hash) = each(%returnhash)) {
3161: # use a foreach because we are going to delete from the hash.
3162: foreach my $key (keys(%$param_hash)) {
3163: delete($param_hash->{$key}) if ($key =~ /^v\./);
3164: }
3165: }
3166: return \%returnhash;
3167: }
3168:
3169: # ------------------------------------------------------ critical inc interface
3170:
3171: sub cinc {
3172: return &inc(@_,'critical');
3173: }
3174:
3175: # --------------------------------------------------------------- inc interface
3176:
3177: sub inc {
3178: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3179: if (!$udomain) { $udomain=$env{'user.domain'}; }
3180: if (!$uname) { $uname=$env{'user.name'}; }
3181: my $uhome=&homeserver($uname,$udomain);
3182: my $items='';
3183: if (! ref($store)) {
3184: # got a single value, so use that instead
3185: $items = &escape($store).'=&';
3186: } elsif (ref($store) eq 'SCALAR') {
3187: $items = &escape($$store).'=&';
3188: } elsif (ref($store) eq 'ARRAY') {
3189: $items = join('=&',map {&escape($_);} @{$store});
3190: } elsif (ref($store) eq 'HASH') {
3191: while (my($key,$value) = each(%{$store})) {
3192: $items.= &escape($key).'='.&escape($value).'&';
3193: }
3194: }
3195: $items=~s/\&$//;
3196: if ($critical) {
3197: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3198: } else {
3199: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3200: }
3201: }
3202:
3203: # --------------------------------------------------------------- put interface
3204:
3205: sub put {
3206: my ($namespace,$storehash,$udomain,$uname)=@_;
3207: if (!$udomain) { $udomain=$env{'user.domain'}; }
3208: if (!$uname) { $uname=$env{'user.name'}; }
3209: my $uhome=&homeserver($uname,$udomain);
3210: my $items='';
3211: foreach my $item (keys(%$storehash)) {
3212: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3213: }
3214: $items=~s/\&$//;
3215: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3216: }
3217:
3218: # ------------------------------------------------------------ newput interface
3219:
3220: sub newput {
3221: my ($namespace,$storehash,$udomain,$uname)=@_;
3222: if (!$udomain) { $udomain=$env{'user.domain'}; }
3223: if (!$uname) { $uname=$env{'user.name'}; }
3224: my $uhome=&homeserver($uname,$udomain);
3225: my $items='';
3226: foreach my $key (keys(%$storehash)) {
3227: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3228: }
3229: $items=~s/\&$//;
3230: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3231: }
3232:
3233: # --------------------------------------------------------- putstore interface
3234:
3235: sub putstore {
3236: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3237: if (!$udomain) { $udomain=$env{'user.domain'}; }
3238: if (!$uname) { $uname=$env{'user.name'}; }
3239: my $uhome=&homeserver($uname,$udomain);
3240: my $items='';
3241: foreach my $key (keys(%$storehash)) {
3242: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3243: }
3244: $items=~s/\&$//;
3245: my $esc_symb=&escape($symb);
3246: my $esc_v=&escape($version);
3247: my $reply =
3248: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3249: $uhome);
3250: if ($reply eq 'unknown_cmd') {
3251: # gfall back to way things use to be done
3252: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3253: $uname);
3254: }
3255: return $reply;
3256: }
3257:
3258: sub old_putstore {
3259: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3260: if (!$udomain) { $udomain=$env{'user.domain'}; }
3261: if (!$uname) { $uname=$env{'user.name'}; }
3262: my $uhome=&homeserver($uname,$udomain);
3263: my %newstorehash;
3264: foreach my $item (keys(%$storehash)) {
3265: my $key = $version.':'.&escape($symb).':'.$item;
3266: $newstorehash{$key} = $storehash->{$item};
3267: }
3268: my $items='';
3269: my %allitems = ();
3270: foreach my $item (keys(%newstorehash)) {
3271: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3272: my $key = $1.':keys:'.$2;
3273: $allitems{$key} .= $3.':';
3274: }
3275: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
3276: }
3277: foreach my $item (keys(%allitems)) {
3278: $allitems{$item} =~ s/\:$//;
3279: $items.= $item.'='.$allitems{$item}.'&';
3280: }
3281: $items=~s/\&$//;
3282: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3283: }
3284:
3285: # ------------------------------------------------------ critical put interface
3286:
3287: sub cput {
3288: my ($namespace,$storehash,$udomain,$uname)=@_;
3289: if (!$udomain) { $udomain=$env{'user.domain'}; }
3290: if (!$uname) { $uname=$env{'user.name'}; }
3291: my $uhome=&homeserver($uname,$udomain);
3292: my $items='';
3293: foreach my $item (keys(%$storehash)) {
3294: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3295: }
3296: $items=~s/\&$//;
3297: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3298: }
3299:
3300: # -------------------------------------------------------------- eget interface
3301:
3302: sub eget {
3303: my ($namespace,$storearr,$udomain,$uname)=@_;
3304: my $items='';
3305: foreach my $item (@$storearr) {
3306: $items.=&escape($item).'&';
3307: }
3308: $items=~s/\&$//;
3309: if (!$udomain) { $udomain=$env{'user.domain'}; }
3310: if (!$uname) { $uname=$env{'user.name'}; }
3311: my $uhome=&homeserver($uname,$udomain);
3312: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3313: my @pairs=split(/\&/,$rep);
3314: my %returnhash=();
3315: my $i=0;
3316: foreach my $item (@$storearr) {
3317: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3318: $i++;
3319: }
3320: return %returnhash;
3321: }
3322:
3323: # ------------------------------------------------------------ tmpput interface
3324: sub tmpput {
3325: my ($storehash,$server,$context)=@_;
3326: my $items='';
3327: foreach my $item (keys(%$storehash)) {
3328: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3329: }
3330: $items=~s/\&$//;
3331: if (defined($context)) {
3332: $items .= ':'.&escape($context);
3333: }
3334: return &reply("tmpput:$items",$server);
3335: }
3336:
3337: # ------------------------------------------------------------ tmpget interface
3338: sub tmpget {
3339: my ($token,$server)=@_;
3340: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3341: my $rep=&reply("tmpget:$token",$server);
3342: my %returnhash;
3343: foreach my $item (split(/\&/,$rep)) {
3344: my ($key,$value)=split(/=/,$item);
3345: $returnhash{&unescape($key)}=&thaw_unescape($value);
3346: }
3347: return %returnhash;
3348: }
3349:
3350: # ------------------------------------------------------------ tmpget interface
3351: sub tmpdel {
3352: my ($token,$server)=@_;
3353: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3354: return &reply("tmpdel:$token",$server);
3355: }
3356:
3357: # -------------------------------------------------- portfolio access checking
3358:
3359: sub portfolio_access {
3360: my ($requrl) = @_;
3361: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3362: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3363: if ($result) {
3364: my %setters;
3365: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3366: my ($startblock,$endblock) =
3367: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3368: if ($startblock && $endblock) {
3369: return 'B';
3370: }
3371: } else {
3372: my ($startblock,$endblock) =
3373: &Apache::loncommon::blockcheck(\%setters,'port');
3374: if ($startblock && $endblock) {
3375: return 'B';
3376: }
3377: }
3378: }
3379: if ($result eq 'ok') {
3380: return 'F';
3381: } elsif ($result =~ /^[^:]+:guest_/) {
3382: return 'A';
3383: }
3384: return '';
3385: }
3386:
3387: sub get_portfolio_access {
3388: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3389:
3390: if (!ref($access_hash)) {
3391: my $current_perms = &get_portfile_permissions($udom,$unum);
3392: my %access_controls = &get_access_controls($current_perms,$group,
3393: $file_name);
3394: $access_hash = $access_controls{$file_name};
3395: }
3396:
3397: my ($public,$guest,@domains,@users,@courses,@groups);
3398: my $now = time;
3399: if (ref($access_hash) eq 'HASH') {
3400: foreach my $key (keys(%{$access_hash})) {
3401: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3402: if ($start > $now) {
3403: next;
3404: }
3405: if ($end && $end<$now) {
3406: next;
3407: }
3408: if ($scope eq 'public') {
3409: $public = $key;
3410: last;
3411: } elsif ($scope eq 'guest') {
3412: $guest = $key;
3413: } elsif ($scope eq 'domains') {
3414: push(@domains,$key);
3415: } elsif ($scope eq 'users') {
3416: push(@users,$key);
3417: } elsif ($scope eq 'course') {
3418: push(@courses,$key);
3419: } elsif ($scope eq 'group') {
3420: push(@groups,$key);
3421: }
3422: }
3423: if ($public) {
3424: return 'ok';
3425: }
3426: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3427: if ($guest) {
3428: return $guest;
3429: }
3430: } else {
3431: if (@domains > 0) {
3432: foreach my $domkey (@domains) {
3433: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3434: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3435: return 'ok';
3436: }
3437: }
3438: }
3439: }
3440: if (@users > 0) {
3441: foreach my $userkey (@users) {
3442: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3443: return 'ok';
3444: }
3445: }
3446: }
3447: my %roleshash;
3448: my @courses_and_groups = @courses;
3449: push(@courses_and_groups,@groups);
3450: if (@courses_and_groups > 0) {
3451: my (%allgroups,%allroles);
3452: my ($start,$end,$role,$sec,$group);
3453: foreach my $envkey (%env) {
3454: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
3455: my $cid = $2.'_'.$3;
3456: if ($1 eq 'gr') {
3457: $group = $4;
3458: $allgroups{$cid}{$group} = $env{$envkey};
3459: } else {
3460: if ($4 eq '') {
3461: $sec = 'none';
3462: } else {
3463: $sec = $4;
3464: }
3465: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3466: }
3467: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
3468: my $cid = $2.'_'.$3;
3469: if ($4 eq '') {
3470: $sec = 'none';
3471: } else {
3472: $sec = $4;
3473: }
3474: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3475: }
3476: }
3477: if (keys(%allroles) == 0) {
3478: return;
3479: }
3480: foreach my $key (@courses_and_groups) {
3481: my %content = %{$$access_hash{$key}};
3482: my $cnum = $content{'number'};
3483: my $cdom = $content{'domain'};
3484: my $cid = $cdom.'_'.$cnum;
3485: if (!exists($allroles{$cid})) {
3486: next;
3487: }
3488: foreach my $role_id (keys(%{$content{'roles'}})) {
3489: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3490: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3491: my @status = @{$content{'roles'}{$role_id}{'access'}};
3492: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3493: foreach my $role (keys(%{$allroles{$cid}})) {
3494: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3495: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3496: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3497: if (grep/^all$/,@sections) {
3498: return 'ok';
3499: } else {
3500: if (grep/^$sec$/,@sections) {
3501: return 'ok';
3502: }
3503: }
3504: }
3505: }
3506: if (keys(%{$allgroups{$cid}}) == 0) {
3507: if (grep/^none$/,@groups) {
3508: return 'ok';
3509: }
3510: } else {
3511: if (grep/^all$/,@groups) {
3512: return 'ok';
3513: }
3514: foreach my $group (keys(%{$allgroups{$cid}})) {
3515: if (grep/^$group$/,@groups) {
3516: return 'ok';
3517: }
3518: }
3519: }
3520: }
3521: }
3522: }
3523: }
3524: }
3525: if ($guest) {
3526: return $guest;
3527: }
3528: }
3529: }
3530: return;
3531: }
3532:
3533: sub course_group_datechecker {
3534: my ($dates,$now,$status) = @_;
3535: my ($start,$end) = split(/\./,$dates);
3536: if (!$start && !$end) {
3537: return 'ok';
3538: }
3539: if (grep/^active$/,@{$status}) {
3540: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3541: return 'ok';
3542: }
3543: }
3544: if (grep/^previous$/,@{$status}) {
3545: if ($end > $now ) {
3546: return 'ok';
3547: }
3548: }
3549: if (grep/^future$/,@{$status}) {
3550: if ($start > $now) {
3551: return 'ok';
3552: }
3553: }
3554: return;
3555: }
3556:
3557: sub parse_portfolio_url {
3558: my ($url) = @_;
3559:
3560: my ($type,$udom,$unum,$group,$file_name);
3561:
3562: if ($url =~ m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
3563: $type = 1;
3564: $udom = $1;
3565: $unum = $2;
3566: $file_name = $3;
3567: } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
3568: $type = 2;
3569: $udom = $1;
3570: $unum = $2;
3571: $group = $3;
3572: $file_name = $3.'/'.$4;
3573: }
3574: if (wantarray) {
3575: return ($type,$udom,$unum,$file_name,$group);
3576: }
3577: return $type;
3578: }
3579:
3580: sub is_portfolio_url {
3581: my ($url) = @_;
3582: return scalar(&parse_portfolio_url($url));
3583: }
3584:
3585: sub is_portfolio_file {
3586: my ($file) = @_;
3587: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
3588: return 1;
3589: }
3590: return;
3591: }
3592:
3593:
3594: # ---------------------------------------------- Custom access rule evaluation
3595:
3596: sub customaccess {
3597: my ($priv,$uri)=@_;
3598: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
3599: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
3600: $udom = &LONCAPA::clean_domain($udom);
3601: $ucrs = &LONCAPA::clean_username($ucrs);
3602: my $access=0;
3603: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3604: my ($effect,$realm,$role)=split(/\:/,$right);
3605: if ($role) {
3606: if ($role ne $urole) { next; }
3607: }
3608: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3609: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
3610: if ($tdom) {
3611: if ($tdom ne $udom) { next; }
3612: }
3613: if ($tcrs) {
3614: if ($tcrs ne $ucrs) { next; }
3615: }
3616: if ($tsec) {
3617: if ($tsec ne $usec) { next; }
3618: }
3619: $access=($effect eq 'allow');
3620: last;
3621: }
3622: if ($realm eq '' && $role eq '') {
3623: $access=($effect eq 'allow');
3624: }
3625: }
3626: return $access;
3627: }
3628:
3629: # ------------------------------------------------- Check for a user privilege
3630:
3631: sub allowed {
3632: my ($priv,$uri,$symb,$role)=@_;
3633: my $ver_orguri=$uri;
3634: $uri=&deversion($uri);
3635: my $orguri=$uri;
3636: $uri=&declutter($uri);
3637:
3638: if ($priv eq 'evb') {
3639: # Evade communication block restrictions for specified role in a course
3640: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3641: return $1;
3642: } else {
3643: return;
3644: }
3645: }
3646:
3647: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3648: # Free bre access to adm and meta resources
3649: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
3650: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3651: && ($priv eq 'bre')) {
3652: return 'F';
3653: }
3654:
3655: # Free bre access to user's own portfolio contents
3656: my ($space,$domain,$name,@dir)=split('/',$uri);
3657: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3658: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
3659: my %setters;
3660: my ($startblock,$endblock) =
3661: &Apache::loncommon::blockcheck(\%setters,'port');
3662: if ($startblock && $endblock) {
3663: return 'B';
3664: } else {
3665: return 'F';
3666: }
3667: }
3668:
3669: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
3670: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3671: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3672: if (exists($env{'request.course.id'})) {
3673: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3674: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3675: if (($domain eq $cdom) && ($name eq $cnum)) {
3676: my $courseprivid=$env{'request.course.id'};
3677: $courseprivid=~s/\_/\//;
3678: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3679: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3680: return $1;
3681: } else {
3682: if ($env{'request.course.sec'}) {
3683: $courseprivid.='/'.$env{'request.course.sec'};
3684: }
3685: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3686: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3687: return $2;
3688: }
3689: }
3690: }
3691: }
3692: }
3693:
3694: # Free bre to public access
3695:
3696: if ($priv eq 'bre') {
3697: my $copyright=&metadata($uri,'copyright');
3698: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3699: return 'F';
3700: }
3701: if ($copyright eq 'priv') {
3702: $uri=~/([^\/]+)\/([^\/]+)\//;
3703: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3704: return '';
3705: }
3706: }
3707: if ($copyright eq 'domain') {
3708: $uri=~/([^\/]+)\/([^\/]+)\//;
3709: unless (($env{'user.domain'} eq $1) ||
3710: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3711: return '';
3712: }
3713: }
3714: if ($env{'request.role'}=~ /li\.\//) {
3715: # Library role, so allow browsing of resources in this domain.
3716: return 'F';
3717: }
3718: if ($copyright eq 'custom') {
3719: unless (&customaccess($priv,$uri)) { return ''; }
3720: }
3721: }
3722: # Domain coordinator is trying to create a course
3723: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3724: # uri is the requested domain in this case.
3725: # comparison to 'request.role.domain' shows if the user has selected
3726: # a role of dc for the domain in question.
3727: return 'F' if ($uri eq $env{'request.role.domain'});
3728: }
3729:
3730: my $thisallowed='';
3731: my $statecond=0;
3732: my $courseprivid='';
3733:
3734: # Course
3735:
3736: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3737: $thisallowed.=$1;
3738: }
3739:
3740: # Domain
3741:
3742: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3743: =~/\Q$priv\E\&([^\:]*)/) {
3744: $thisallowed.=$1;
3745: }
3746:
3747: # Course: uri itself is a course
3748: my $courseuri=$uri;
3749: $courseuri=~s/\_(\d)/\/$1/;
3750: $courseuri=~s/^([^\/])/\/$1/;
3751:
3752: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3753: =~/\Q$priv\E\&([^\:]*)/) {
3754: $thisallowed.=$1;
3755: }
3756:
3757: # URI is an uploaded document for this course, default permissions don't matter
3758: # not allowing 'edit' access (editupload) to uploaded course docs
3759: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3760: $thisallowed='';
3761: my ($match)=&is_on_map($uri);
3762: if ($match) {
3763: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3764: =~/\Q$priv\E\&([^\:]*)/) {
3765: $thisallowed.=$1;
3766: }
3767: } else {
3768: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3769: if ($refuri) {
3770: if ($refuri =~ m|^/adm/|) {
3771: $thisallowed='F';
3772: } else {
3773: $refuri=&declutter($refuri);
3774: my ($match) = &is_on_map($refuri);
3775: if ($match) {
3776: $thisallowed='F';
3777: }
3778: }
3779: }
3780: }
3781: }
3782:
3783: if ($priv eq 'bre'
3784: && $thisallowed ne 'F'
3785: && $thisallowed ne '2'
3786: && &is_portfolio_url($uri)) {
3787: $thisallowed = &portfolio_access($uri);
3788: }
3789:
3790: # Full access at system, domain or course-wide level? Exit.
3791:
3792: if ($thisallowed=~/F/) {
3793: return 'F';
3794: }
3795:
3796: # If this is generating or modifying users, exit with special codes
3797:
3798: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3799: if (($priv eq 'cca') || ($priv eq 'caa')) {
3800: my ($audom,$auname)=split('/',$uri);
3801: # no author name given, so this just checks on the general right to make a co-author in this domain
3802: unless ($auname) { return $thisallowed; }
3803: # an author name is given, so we are about to actually make a co-author for a certain account
3804: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3805: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3806: ($audom ne $env{'request.role.domain'}))) { return ''; }
3807: }
3808: return $thisallowed;
3809: }
3810: #
3811: # Gathered so far: system, domain and course wide privileges
3812: #
3813: # Course: See if uri or referer is an individual resource that is part of
3814: # the course
3815:
3816: if ($env{'request.course.id'}) {
3817:
3818: $courseprivid=$env{'request.course.id'};
3819: if ($env{'request.course.sec'}) {
3820: $courseprivid.='/'.$env{'request.course.sec'};
3821: }
3822: $courseprivid=~s/\_/\//;
3823: my $checkreferer=1;
3824: my ($match,$cond)=&is_on_map($uri);
3825: if ($match) {
3826: $statecond=$cond;
3827: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3828: =~/\Q$priv\E\&([^\:]*)/) {
3829: $thisallowed.=$1;
3830: $checkreferer=0;
3831: }
3832: }
3833:
3834: if ($checkreferer) {
3835: my $refuri=$env{'httpref.'.$orguri};
3836: unless ($refuri) {
3837: foreach my $key (keys(%env)) {
3838: if ($key=~/^httpref\..*\*/) {
3839: my $pattern=$key;
3840: $pattern=~s/^httpref\.\/res\///;
3841: $pattern=~s/\*/\[\^\/\]\+/g;
3842: $pattern=~s/\//\\\//g;
3843: if ($orguri=~/$pattern/) {
3844: $refuri=$env{$key};
3845: }
3846: }
3847: }
3848: }
3849:
3850: if ($refuri) {
3851: $refuri=&declutter($refuri);
3852: my ($match,$cond)=&is_on_map($refuri);
3853: if ($match) {
3854: my $refstatecond=$cond;
3855: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3856: =~/\Q$priv\E\&([^\:]*)/) {
3857: $thisallowed.=$1;
3858: $uri=$refuri;
3859: $statecond=$refstatecond;
3860: }
3861: }
3862: }
3863: }
3864: }
3865:
3866: #
3867: # Gathered now: all privileges that could apply, and condition number
3868: #
3869: #
3870: # Full or no access?
3871: #
3872:
3873: if ($thisallowed=~/F/) {
3874: return 'F';
3875: }
3876:
3877: unless ($thisallowed) {
3878: return '';
3879: }
3880:
3881: # Restrictions exist, deal with them
3882: #
3883: # C:according to course preferences
3884: # R:according to resource settings
3885: # L:unless locked
3886: # X:according to user session state
3887: #
3888:
3889: # Possibly locked functionality, check all courses
3890: # Locks might take effect only after 10 minutes cache expiration for other
3891: # courses, and 2 minutes for current course
3892:
3893: my $envkey;
3894: if ($thisallowed=~/L/) {
3895: foreach $envkey (keys %env) {
3896: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3897: my $courseid=$2;
3898: my $roleid=$1.'.'.$2;
3899: $courseid=~s/^\///;
3900: my $expiretime=600;
3901: if ($env{'request.role'} eq $roleid) {
3902: $expiretime=120;
3903: }
3904: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3905: my $prefix='course.'.$cdom.'_'.$cnum.'.';
3906: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
3907: &coursedescription($courseid,{'freshen_cache' => 1});
3908: }
3909: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3910: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3911: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3912: &log($env{'user.domain'},$env{'user.name'},
3913: $env{'user.home'},
3914: 'Locked by res: '.$priv.' for '.$uri.' due to '.
3915: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3916: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3917: return '';
3918: }
3919: }
3920: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3921: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3922: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3923: &log($env{'user.domain'},$env{'user.name'},
3924: $env{'user.home'},
3925: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
3926: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3927: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3928: return '';
3929: }
3930: }
3931: }
3932: }
3933: }
3934:
3935: #
3936: # Rest of the restrictions depend on selected course
3937: #
3938:
3939: unless ($env{'request.course.id'}) {
3940: if ($thisallowed eq 'A') {
3941: return 'A';
3942: } elsif ($thisallowed eq 'B') {
3943: return 'B';
3944: } else {
3945: return '1';
3946: }
3947: }
3948:
3949: #
3950: # Now user is definitely in a course
3951: #
3952:
3953:
3954: # Course preferences
3955:
3956: if ($thisallowed=~/C/) {
3957: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3958: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3959: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
3960: =~/\Q$rolecode\E/) {
3961: if ($priv ne 'pch') {
3962: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3963: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3964: $env{'request.course.id'});
3965: }
3966: return '';
3967: }
3968:
3969: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
3970: =~/\Q$unamedom\E/) {
3971: if ($priv ne 'pch') {
3972: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3973: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3974: $env{'request.course.id'});
3975: }
3976: return '';
3977: }
3978: }
3979:
3980: # Resource preferences
3981:
3982: if ($thisallowed=~/R/) {
3983: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3984: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
3985: if ($priv ne 'pch') {
3986: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3987: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3988: }
3989: return '';
3990: }
3991: }
3992:
3993: # Restricted by state or randomout?
3994:
3995: if ($thisallowed=~/X/) {
3996: if ($env{'acc.randomout'}) {
3997: if (!$symb) { $symb=&symbread($uri,1); }
3998: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
3999: return '';
4000: }
4001: }
4002: if (&condval($statecond)) {
4003: return '2';
4004: } else {
4005: return '';
4006: }
4007: }
4008:
4009: if ($thisallowed eq 'A') {
4010: return 'A';
4011: } elsif ($thisallowed eq 'B') {
4012: return 'B';
4013: }
4014: return 'F';
4015: }
4016:
4017: sub split_uri_for_cond {
4018: my $uri=&deversion(&declutter(shift));
4019: my @uriparts=split(/\//,$uri);
4020: my $filename=pop(@uriparts);
4021: my $pathname=join('/',@uriparts);
4022: return ($pathname,$filename);
4023: }
4024: # --------------------------------------------------- Is a resource on the map?
4025:
4026: sub is_on_map {
4027: my ($pathname,$filename) = &split_uri_for_cond(shift);
4028: #Trying to find the conditional for the file
4029: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
4030: /\&\Q$filename\E\:([\d\|]+)\&/);
4031: if ($match) {
4032: return (1,$1);
4033: } else {
4034: return (0,0);
4035: }
4036: }
4037:
4038: # --------------------------------------------------------- Get symb from alias
4039:
4040: sub get_symb_from_alias {
4041: my $symb=shift;
4042: my ($map,$resid,$url)=&decode_symb($symb);
4043: # Already is a symb
4044: if ($url) { return $symb; }
4045: # Must be an alias
4046: my $aliassymb='';
4047: my %bighash;
4048: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
4049: &GDBM_READER(),0640)) {
4050: my $rid=$bighash{'mapalias_'.$symb};
4051: if ($rid) {
4052: my ($mapid,$resid)=split(/\./,$rid);
4053: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4054: $resid,$bighash{'src_'.$rid});
4055: }
4056: untie %bighash;
4057: }
4058: return $aliassymb;
4059: }
4060:
4061: # ----------------------------------------------------------------- Define Role
4062:
4063: sub definerole {
4064: if (allowed('mcr','/')) {
4065: my ($rolename,$sysrole,$domrole,$courole)=@_;
4066: foreach my $role (split(':',$sysrole)) {
4067: my ($crole,$cqual)=split(/\&/,$role);
4068: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4069: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4070: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4071: return "refused:s:$crole&$cqual";
4072: }
4073: }
4074: }
4075: foreach my $role (split(':',$domrole)) {
4076: my ($crole,$cqual)=split(/\&/,$role);
4077: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4078: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4079: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
4080: return "refused:d:$crole&$cqual";
4081: }
4082: }
4083: }
4084: foreach my $role (split(':',$courole)) {
4085: my ($crole,$cqual)=split(/\&/,$role);
4086: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4087: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4088: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4089: return "refused:c:$crole&$cqual";
4090: }
4091: }
4092: }
4093: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4094: "$env{'user.domain'}:$env{'user.name'}:".
4095: "rolesdef_$rolename=".
4096: escape($sysrole.'_'.$domrole.'_'.$courole);
4097: return reply($command,$env{'user.home'});
4098: } else {
4099: return 'refused';
4100: }
4101: }
4102:
4103: # ---------------- Make a metadata query against the network of library servers
4104:
4105: sub metadata_query {
4106: my ($query,$custom,$customshow,$server_array)=@_;
4107: my %rhash;
4108: my @server_list = (defined($server_array) ? @$server_array
4109: : keys(%libserv) );
4110: for my $server (@server_list) {
4111: unless ($custom or $customshow) {
4112: my $reply=&reply("querysend:".&escape($query),$server);
4113: $rhash{$server}=$reply;
4114: }
4115: else {
4116: my $reply=&reply("querysend:".&escape($query).':'.
4117: &escape($custom).':'.&escape($customshow),
4118: $server);
4119: $rhash{$server}=$reply;
4120: }
4121: }
4122: return \%rhash;
4123: }
4124:
4125: # ----------------------------------------- Send log queries and wait for reply
4126:
4127: sub log_query {
4128: my ($uname,$udom,$query,%filters)=@_;
4129: my $uhome=&homeserver($uname,$udom);
4130: if ($uhome eq 'no_host') { return 'error: no_host'; }
4131: my $uhost=$hostname{$uhome};
4132: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
4133: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4134: $uhome);
4135: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
4136: return get_query_reply($queryid);
4137: }
4138:
4139: # -------------------------- Update MySQL table for portfolio file
4140:
4141: sub update_portfolio_table {
4142: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
4143: my $homeserver = &homeserver($uname,$udom);
4144: my $queryid=
4145: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4146: ':'.&escape($file_name).':'.$action,$homeserver);
4147: my $reply = &get_query_reply($queryid);
4148: return $reply;
4149: }
4150:
4151: # ------- Request retrieval of institutional classlists for course(s)
4152:
4153: sub fetch_enrollment_query {
4154: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
4155: my $homeserver;
4156: my $maxtries = 1;
4157: if ($context eq 'automated') {
4158: $homeserver = $perlvar{'lonHostID'};
4159: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
4160: } else {
4161: $homeserver = &homeserver($cnum,$dom);
4162: }
4163: my $host=$hostname{$homeserver};
4164: my $cmd = '';
4165: foreach my $affiliate (keys %{$affiliatesref}) {
4166: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4167: }
4168: $cmd =~ s/%%$//;
4169: $cmd = &escape($cmd);
4170: my $query = 'fetchenrollment';
4171: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
4172: unless ($queryid=~/^\Q$host\E\_/) {
4173: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4174: return 'error: '.$queryid;
4175: }
4176: my $reply = &get_query_reply($queryid);
4177: my $tries = 1;
4178: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4179: $reply = &get_query_reply($queryid);
4180: $tries ++;
4181: }
4182: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4183: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4184: } else {
4185: my @responses = split/:/,$reply;
4186: if ($homeserver eq $perlvar{'lonHostID'}) {
4187: foreach my $line (@responses) {
4188: my ($key,$value) = split(/=/,$line,2);
4189: $$replyref{$key} = $value;
4190: }
4191: } else {
4192: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
4193: foreach my $line (@responses) {
4194: my ($key,$value) = split(/=/,$line);
4195: $$replyref{$key} = $value;
4196: if ($value > 0) {
4197: foreach my $item (@{$$affiliatesref{$key}}) {
4198: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
4199: my $destname = $pathname.'/'.$filename;
4200: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
4201: if ($xml_classlist =~ /^error/) {
4202: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4203: } else {
4204: if ( open(FILE,">$destname") ) {
4205: print FILE &unescape($xml_classlist);
4206: close(FILE);
4207: } else {
4208: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
4209: }
4210: }
4211: }
4212: }
4213: }
4214: }
4215: return 'ok';
4216: }
4217: return 'error';
4218: }
4219:
4220: sub get_query_reply {
4221: my $queryid=shift;
4222: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4223: my $reply='';
4224: for (1..100) {
4225: sleep 2;
4226: if (-e $replyfile.'.end') {
4227: if (open(my $fh,$replyfile)) {
4228: $reply.=<$fh>;
4229: close($fh);
4230: } else { return 'error: reply_file_error'; }
4231: return &unescape($reply);
4232: }
4233: }
4234: return 'timeout:'.$queryid;
4235: }
4236:
4237: sub courselog_query {
4238: #
4239: # possible filters:
4240: # url: url or symb
4241: # username
4242: # domain
4243: # action: view, submit, grade
4244: # start: timestamp
4245: # end: timestamp
4246: #
4247: my (%filters)=@_;
4248: unless ($env{'request.course.id'}) { return 'no_course'; }
4249: if ($filters{'url'}) {
4250: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4251: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4252: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4253: }
4254: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4255: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4256: return &log_query($cname,$cdom,'courselog',%filters);
4257: }
4258:
4259: sub userlog_query {
4260: my ($uname,$udom,%filters)=@_;
4261: return &log_query($uname,$udom,'userlog',%filters);
4262: }
4263:
4264: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4265:
4266: sub auto_run {
4267: my ($cnum,$cdom) = @_;
4268: my $homeserver = &homeserver($cnum,$cdom);
4269: my $response = &reply('autorun:'.$cdom,$homeserver);
4270: return $response;
4271: }
4272:
4273: sub auto_get_sections {
4274: my ($cnum,$cdom,$inst_coursecode) = @_;
4275: my $homeserver = &homeserver($cnum,$cdom);
4276: my @secs = ();
4277: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
4278: unless ($response eq 'refused') {
4279: @secs = split/:/,$response;
4280: }
4281: return @secs;
4282: }
4283:
4284: sub auto_new_course {
4285: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4286: my $homeserver = &homeserver($cnum,$cdom);
4287: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
4288: return $response;
4289: }
4290:
4291: sub auto_validate_courseID {
4292: my ($cnum,$cdom,$inst_course_id) = @_;
4293: my $homeserver = &homeserver($cnum,$cdom);
4294: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
4295: return $response;
4296: }
4297:
4298: sub auto_create_password {
4299: my ($cnum,$cdom,$authparam) = @_;
4300: my $homeserver = &homeserver($cnum,$cdom);
4301: my $create_passwd = 0;
4302: my $authchk = '';
4303: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4304: if ($response eq 'refused') {
4305: $authchk = 'refused';
4306: } else {
4307: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4308: }
4309: return ($authparam,$create_passwd,$authchk);
4310: }
4311:
4312: sub auto_photo_permission {
4313: my ($cnum,$cdom,$students) = @_;
4314: my $homeserver = &homeserver($cnum,$cdom);
4315: my ($outcome,$perm_reqd,$conditions) =
4316: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
4317: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4318: return (undef,undef);
4319: }
4320: return ($outcome,$perm_reqd,$conditions);
4321: }
4322:
4323: sub auto_checkphotos {
4324: my ($uname,$udom,$pid) = @_;
4325: my $homeserver = &homeserver($uname,$udom);
4326: my ($result,$resulttype);
4327: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
4328: &escape($uname).':'.&escape($pid),
4329: $homeserver));
4330: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4331: return (undef,undef);
4332: }
4333: if ($outcome) {
4334: ($result,$resulttype) = split(/:/,$outcome);
4335: }
4336: return ($result,$resulttype);
4337: }
4338:
4339: sub auto_photochoice {
4340: my ($cnum,$cdom) = @_;
4341: my $homeserver = &homeserver($cnum,$cdom);
4342: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
4343: &escape($cdom),
4344: $homeserver)));
4345: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4346: return (undef,undef);
4347: }
4348: return ($update,$comment);
4349: }
4350:
4351: sub auto_photoupdate {
4352: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4353: my $homeserver = &homeserver($cnum,$dom);
4354: my $host=$hostname{$homeserver};
4355: my $cmd = '';
4356: my $maxtries = 1;
4357: foreach my $affiliate (keys(%{$affiliatesref})) {
4358: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4359: }
4360: $cmd =~ s/%%$//;
4361: $cmd = &escape($cmd);
4362: my $query = 'institutionalphotos';
4363: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4364: unless ($queryid=~/^\Q$host\E\_/) {
4365: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4366: return 'error: '.$queryid;
4367: }
4368: my $reply = &get_query_reply($queryid);
4369: my $tries = 1;
4370: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4371: $reply = &get_query_reply($queryid);
4372: $tries ++;
4373: }
4374: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4375: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4376: } else {
4377: my @responses = split(/:/,$reply);
4378: my $outcome = shift(@responses);
4379: foreach my $item (@responses) {
4380: my ($key,$value) = split(/=/,$item);
4381: $$photo{$key} = $value;
4382: }
4383: return $outcome;
4384: }
4385: return 'error';
4386: }
4387:
4388: sub auto_instcode_format {
4389: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4390: $cat_order) = @_;
4391: my $courses = '';
4392: my @homeservers;
4393: if ($caller eq 'global') {
4394: foreach my $tryserver (keys(%libserv)) {
4395: if ($hostdom{$tryserver} eq $codedom) {
4396: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4397: push(@homeservers,$tryserver);
4398: }
4399: }
4400: }
4401: } else {
4402: push(@homeservers,&homeserver($caller,$codedom));
4403: }
4404: foreach my $code (keys(%{$instcodes})) {
4405: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
4406: }
4407: chop($courses);
4408: my $ok_response = 0;
4409: my $response;
4410: while (@homeservers > 0 && $ok_response == 0) {
4411: my $server = shift(@homeservers);
4412: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4413: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4414: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
4415: split/:/,$response;
4416: %{$codes} = (%{$codes},&str2hash($codes_str));
4417: push(@{$codetitles},&str2array($codetitles_str));
4418: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4419: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4420: $ok_response = 1;
4421: }
4422: }
4423: if ($ok_response) {
4424: return 'ok';
4425: } else {
4426: return $response;
4427: }
4428: }
4429:
4430: sub auto_instcode_defaults {
4431: my ($domain,$returnhash,$code_order) = @_;
4432: my @homeservers;
4433: foreach my $tryserver (keys(%libserv)) {
4434: if ($hostdom{$tryserver} eq $domain) {
4435: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4436: push(@homeservers,$tryserver);
4437: }
4438: }
4439: }
4440: my $ok_response = 0;
4441: my $response;
4442: while (@homeservers > 0 && $ok_response == 0) {
4443: my $server = shift(@homeservers);
4444: $response=&reply('autoinstcodedefaults:'.$domain,$server);
4445: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4446: foreach my $pair (split(/\&/,$response)) {
4447: my ($name,$value)=split(/\=/,$pair);
4448: if ($name eq 'code_order') {
4449: @{$code_order} = split(/\&/,&unescape($value));
4450: } else {
4451: $returnhash->{&unescape($name)}=&unescape($value);
4452: }
4453: }
4454: $ok_response = 1;
4455: }
4456: }
4457: if ($ok_response) {
4458: return 'ok';
4459: } else {
4460: return $response;
4461: }
4462: }
4463:
4464: sub auto_validate_class_sec {
4465: my ($cdom,$cnum,$owner,$inst_class) = @_;
4466: my $homeserver = &homeserver($cnum,$cdom);
4467: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
4468: &escape($owner).':'.$cdom,$homeserver);
4469: return $response;
4470: }
4471:
4472: # ------------------------------------------------------- Course Group routines
4473:
4474: sub get_coursegroups {
4475: my ($cdom,$cnum,$group,$namespace) = @_;
4476: return(&dump($namespace,$cdom,$cnum,$group));
4477: }
4478:
4479: sub modify_coursegroup {
4480: my ($cdom,$cnum,$groupsettings) = @_;
4481: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4482: }
4483:
4484: sub toggle_coursegroup_status {
4485: my ($cdom,$cnum,$group,$action) = @_;
4486: my ($from_namespace,$to_namespace);
4487: if ($action eq 'delete') {
4488: $from_namespace = 'coursegroups';
4489: $to_namespace = 'deleted_groups';
4490: } else {
4491: $from_namespace = 'deleted_groups';
4492: $to_namespace = 'coursegroups';
4493: }
4494: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
4495: if (my $tmp = &error(%curr_group)) {
4496: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4497: return ('read error',$tmp);
4498: } else {
4499: my %savedsettings = %curr_group;
4500: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
4501: my $deloutcome;
4502: if ($result eq 'ok') {
4503: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
4504: } else {
4505: return ('write error',$result);
4506: }
4507: if ($deloutcome eq 'ok') {
4508: return 'ok';
4509: } else {
4510: return ('delete error',$deloutcome);
4511: }
4512: }
4513: }
4514:
4515: sub modify_group_roles {
4516: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4517: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4518: my $role = 'gr/'.&escape($userprivs);
4519: my ($uname,$udom) = split(/:/,$user);
4520: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
4521: if ($result eq 'ok') {
4522: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4523: }
4524: return $result;
4525: }
4526:
4527: sub modify_coursegroup_membership {
4528: my ($cdom,$cnum,$membership) = @_;
4529: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4530: return $result;
4531: }
4532:
4533: sub get_active_groups {
4534: my ($udom,$uname,$cdom,$cnum) = @_;
4535: my $now = time;
4536: my %groups = ();
4537: foreach my $key (keys(%env)) {
4538: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
4539: my ($start,$end) = split(/\./,$env{$key});
4540: if (($end!=0) && ($end<$now)) { next; }
4541: if (($start!=0) && ($start>$now)) { next; }
4542: if ($1 eq $cdom && $2 eq $cnum) {
4543: $groups{$3} = $env{$key} ;
4544: }
4545: }
4546: }
4547: return %groups;
4548: }
4549:
4550: sub get_group_membership {
4551: my ($cdom,$cnum,$group) = @_;
4552: return(&dump('groupmembership',$cdom,$cnum,$group));
4553: }
4554:
4555: sub get_users_groups {
4556: my ($udom,$uname,$courseid) = @_;
4557: my @usersgroups;
4558: my $cachetime=1800;
4559:
4560: my $hashid="$udom:$uname:$courseid";
4561: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4562: if (defined($cached)) {
4563: @usersgroups = split(/:/,$grouplist);
4564: } else {
4565: $grouplist = '';
4566: my $courseurl = &courseid_to_courseurl($courseid);
4567: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
4568: my $access_end = $env{'course.'.$courseid.
4569: '.default_enrollment_end_date'};
4570: my $now = time;
4571: foreach my $key (keys(%roleshash)) {
4572: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4573: my $group = $1;
4574: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4575: my $start = $2;
4576: my $end = $1;
4577: if ($start == -1) { next; } # deleted from group
4578: if (($start!=0) && ($start>$now)) { next; }
4579: if (($end!=0) && ($end<$now)) {
4580: if ($access_end && $access_end < $now) {
4581: if ($access_end - $end < 86400) {
4582: push(@usersgroups,$group);
4583: }
4584: }
4585: next;
4586: }
4587: push(@usersgroups,$group);
4588: }
4589: }
4590: }
4591: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4592: $grouplist = join(':',@usersgroups);
4593: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4594: }
4595: return @usersgroups;
4596: }
4597:
4598: sub devalidate_getgroups_cache {
4599: my ($udom,$uname,$cdom,$cnum)=@_;
4600: my $courseid = $cdom.'_'.$cnum;
4601:
4602: my $hashid="$udom:$uname:$courseid";
4603: &devalidate_cache_new('getgroups',$hashid);
4604: }
4605:
4606: # ------------------------------------------------------------------ Plain Text
4607:
4608: sub plaintext {
4609: my ($short,$type,$cid) = @_;
4610: if ($short =~ /^cr/) {
4611: return (split('/',$short))[-1];
4612: }
4613: if (!defined($cid)) {
4614: $cid = $env{'request.course.id'};
4615: }
4616: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4617: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4618: '.plaintext'});
4619: }
4620: my %rolenames = (
4621: Course => 'std',
4622: Group => 'alt1',
4623: );
4624: if (defined($type) &&
4625: defined($rolenames{$type}) &&
4626: defined($prp{$short}{$rolenames{$type}})) {
4627: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4628: } else {
4629: return &Apache::lonlocal::mt($prp{$short}{'std'});
4630: }
4631: }
4632:
4633: # ----------------------------------------------------------------- Assign Role
4634:
4635: sub assignrole {
4636: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4637: my $mrole;
4638: if ($role =~ /^cr\//) {
4639: my $cwosec=$url;
4640: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4641: unless (&allowed('ccr',$cwosec)) {
4642: &logthis('Refused custom assignrole: '.
4643: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4644: $env{'user.name'}.' at '.$env{'user.domain'});
4645: return 'refused';
4646: }
4647: $mrole='cr';
4648: } elsif ($role =~ /^gr\//) {
4649: my $cwogrp=$url;
4650: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
4651: unless (&allowed('mdg',$cwogrp)) {
4652: &logthis('Refused group assignrole: '.
4653: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4654: $env{'user.name'}.' at '.$env{'user.domain'});
4655: return 'refused';
4656: }
4657: $mrole='gr';
4658: } else {
4659: my $cwosec=$url;
4660: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4661: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4662: &logthis('Refused assignrole: '.
4663: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4664: $env{'user.name'}.' at '.$env{'user.domain'});
4665: return 'refused';
4666: }
4667: $mrole=$role;
4668: }
4669: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4670: "$udom:$uname:$url".'_'."$mrole=$role";
4671: if ($end) { $command.='_'.$end; }
4672: if ($start) {
4673: if ($end) {
4674: $command.='_'.$start;
4675: } else {
4676: $command.='_0_'.$start;
4677: }
4678: }
4679: my $origstart = $start;
4680: my $origend = $end;
4681: # actually delete
4682: if ($deleteflag) {
4683: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4684: # modify command to delete the role
4685: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4686: "$udom:$uname:$url".'_'."$mrole";
4687: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4688: # set start and finish to negative values for userrolelog
4689: $start=-1;
4690: $end=-1;
4691: }
4692: }
4693: # send command
4694: my $answer=&reply($command,&homeserver($uname,$udom));
4695: # log new user role if status is ok
4696: if ($answer eq 'ok') {
4697: &userrolelog($role,$uname,$udom,$url,$start,$end);
4698: # for course roles, perform group memberships changes triggered by role change.
4699: unless ($role =~ /^gr/) {
4700: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4701: $origstart);
4702: }
4703: }
4704: return $answer;
4705: }
4706:
4707: # -------------------------------------------------- Modify user authentication
4708: # Overrides without validation
4709:
4710: sub modifyuserauth {
4711: my ($udom,$uname,$umode,$upass)=@_;
4712: my $uhome=&homeserver($uname,$udom);
4713: unless (&allowed('mau',$udom)) { return 'refused'; }
4714: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4715: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4716: ' in domain '.$env{'request.role.domain'});
4717: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4718: &escape($upass),$uhome);
4719: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4720: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4721: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4722: &log($udom,,$uname,$uhome,
4723: 'Authentication changed by '.$env{'user.domain'}.', '.
4724: $env{'user.name'}.', '.$umode.
4725: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4726: unless ($reply eq 'ok') {
4727: &logthis('Authentication mode error: '.$reply);
4728: return 'error: '.$reply;
4729: }
4730: return 'ok';
4731: }
4732:
4733: # --------------------------------------------------------------- Modify a user
4734:
4735: sub modifyuser {
4736: my ($udom, $uname, $uid,
4737: $umode, $upass, $first,
4738: $middle, $last, $gene,
4739: $forceid, $desiredhome, $email)=@_;
4740: $udom= &LONCAPA::clean_domain($udom);
4741: $uname=&LONCAPA::clean_username($uname);
4742: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4743: $umode.', '.$first.', '.$middle.', '.
4744: $last.', '.$gene.'(forceid: '.$forceid.')'.
4745: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4746: ' desiredhome not specified').
4747: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4748: ' in domain '.$env{'request.role.domain'});
4749: my $uhome=&homeserver($uname,$udom,'true');
4750: # ----------------------------------------------------------------- Create User
4751: if (($uhome eq 'no_host') &&
4752: (($umode && $upass) || ($umode eq 'localauth'))) {
4753: my $unhome='';
4754: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
4755: $unhome = $desiredhome;
4756: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4757: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4758: } else { # load balancing routine for determining $unhome
4759: my $tryserver;
4760: my $loadm=10000000;
4761: foreach $tryserver (keys %libserv) {
4762: if ($hostdom{$tryserver} eq $udom) {
4763: my $answer=reply('load',$tryserver);
4764: if (($answer=~/\d+/) && ($answer<$loadm)) {
4765: $loadm=$answer;
4766: $unhome=$tryserver;
4767: }
4768: }
4769: }
4770: }
4771: if (($unhome eq '') || ($unhome eq 'no_host')) {
4772: return 'error: unable to find a home server for '.$uname.
4773: ' in domain '.$udom;
4774: }
4775: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4776: &escape($upass),$unhome);
4777: unless ($reply eq 'ok') {
4778: return 'error: '.$reply;
4779: }
4780: $uhome=&homeserver($uname,$udom,'true');
4781: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4782: return 'error: unable verify users home machine.';
4783: }
4784: } # End of creation of new user
4785: # ---------------------------------------------------------------------- Add ID
4786: if ($uid) {
4787: $uid=~tr/A-Z/a-z/;
4788: my %uidhash=&idrget($udom,$uname);
4789: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4790: && (!$forceid)) {
4791: unless ($uid eq $uidhash{$uname}) {
4792: return 'error: user id "'.$uid.'" does not match '.
4793: 'current user id "'.$uidhash{$uname}.'".';
4794: }
4795: } else {
4796: &idput($udom,($uname => $uid));
4797: }
4798: }
4799: # -------------------------------------------------------------- Add names, etc
4800: my @tmp=&get('environment',
4801: ['firstname','middlename','lastname','generation'],
4802: $udom,$uname);
4803: my %names;
4804: if ($tmp[0] =~ m/^error:.*/) {
4805: %names=();
4806: } else {
4807: %names = @tmp;
4808: }
4809: #
4810: # Make sure to not trash student environment if instructor does not bother
4811: # to supply name and email information
4812: #
4813: if ($first) { $names{'firstname'} = $first; }
4814: if (defined($middle)) { $names{'middlename'} = $middle; }
4815: if ($last) { $names{'lastname'} = $last; }
4816: if (defined($gene)) { $names{'generation'} = $gene; }
4817: if ($email) {
4818: $email=~s/[^\w\@\.\-\,]//gs;
4819: if ($email=~/\@/) { $names{'notification'} = $email;
4820: $names{'critnotification'} = $email;
4821: $names{'permanentemail'} = $email; }
4822: }
4823: my $reply = &put('environment', \%names, $udom,$uname);
4824: if ($reply ne 'ok') { return 'error: '.$reply; }
4825: &devalidate_cache_new('namescache',$uname.':'.$udom);
4826: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
4827: $umode.', '.$first.', '.$middle.', '.
4828: $last.', '.$gene.' by '.
4829: $env{'user.name'}.' at '.$env{'user.domain'});
4830: return 'ok';
4831: }
4832:
4833: # -------------------------------------------------------------- Modify student
4834:
4835: sub modifystudent {
4836: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
4837: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
4838: if (!$cid) {
4839: unless ($cid=$env{'request.course.id'}) {
4840: return 'not_in_class';
4841: }
4842: }
4843: # --------------------------------------------------------------- Make the user
4844: my $reply=&modifyuser
4845: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
4846: $desiredhome,$email);
4847: unless ($reply eq 'ok') { return $reply; }
4848: # This will cause &modify_student_enrollment to get the uid from the
4849: # students environment
4850: $uid = undef if (!$forceid);
4851: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
4852: $gene,$usec,$end,$start,$type,$locktype,$cid);
4853: return $reply;
4854: }
4855:
4856: sub modify_student_enrollment {
4857: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
4858: my ($cdom,$cnum,$chome);
4859: if (!$cid) {
4860: unless ($cid=$env{'request.course.id'}) {
4861: return 'not_in_class';
4862: }
4863: $cdom=$env{'course.'.$cid.'.domain'};
4864: $cnum=$env{'course.'.$cid.'.num'};
4865: } else {
4866: ($cdom,$cnum)=split(/_/,$cid);
4867: }
4868: $chome=$env{'course.'.$cid.'.home'};
4869: if (!$chome) {
4870: $chome=&homeserver($cnum,$cdom);
4871: }
4872: if (!$chome) { return 'unknown_course'; }
4873: # Make sure the user exists
4874: my $uhome=&homeserver($uname,$udom);
4875: if (($uhome eq '') || ($uhome eq 'no_host')) {
4876: return 'error: no such user';
4877: }
4878: # Get student data if we were not given enough information
4879: if (!defined($first) || $first eq '' ||
4880: !defined($last) || $last eq '' ||
4881: !defined($uid) || $uid eq '' ||
4882: !defined($middle) || $middle eq '' ||
4883: !defined($gene) || $gene eq '') {
4884: # They did not supply us with enough data to enroll the student, so
4885: # we need to pick up more information.
4886: my %tmp = &get('environment',
4887: ['firstname','middlename','lastname', 'generation','id']
4888: ,$udom,$uname);
4889:
4890: #foreach my $key (keys(%tmp)) {
4891: # &logthis("key $key = ".$tmp{$key});
4892: #}
4893: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4894: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4895: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
4896: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
4897: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4898: }
4899: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
4900: my $reply=cput('classlist',
4901: {"$uname:$udom" =>
4902: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
4903: $cdom,$cnum);
4904: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4905: return 'error: '.$reply;
4906: } else {
4907: &devalidate_getsection_cache($udom,$uname,$cid);
4908: }
4909: # Add student role to user
4910: my $uurl='/'.$cid;
4911: $uurl=~s/\_/\//g;
4912: if ($usec) {
4913: $uurl.='/'.$usec;
4914: }
4915: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
4916: }
4917:
4918: sub format_name {
4919: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
4920: my $name;
4921: if ($first ne 'lastname') {
4922: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
4923: } else {
4924: if ($lastname=~/\S/) {
4925: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
4926: $name=~s/\s+,/,/;
4927: } else {
4928: $name.= $firstname.' '.$middlename.' '.$generation;
4929: }
4930: }
4931: $name=~s/^\s+//;
4932: $name=~s/\s+$//;
4933: $name=~s/\s+/ /g;
4934: return $name;
4935: }
4936:
4937: # ------------------------------------------------- Write to course preferences
4938:
4939: sub writecoursepref {
4940: my ($courseid,%prefs)=@_;
4941: $courseid=~s/^\///;
4942: $courseid=~s/\_/\//g;
4943: my ($cdomain,$cnum)=split(/\//,$courseid);
4944: my $chome=homeserver($cnum,$cdomain);
4945: if (($chome eq '') || ($chome eq 'no_host')) {
4946: return 'error: no such course';
4947: }
4948: my $cstring='';
4949: foreach my $pref (keys(%prefs)) {
4950: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
4951: }
4952: $cstring=~s/\&$//;
4953: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
4954: }
4955:
4956: # ---------------------------------------------------------- Make/modify course
4957:
4958: sub createcourse {
4959: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
4960: $course_owner,$crstype)=@_;
4961: $url=&declutter($url);
4962: my $cid='';
4963: unless (&allowed('ccc',$udom)) {
4964: return 'refused';
4965: }
4966: # ------------------------------------------------------------------- Create ID
4967: my $uname=int(1+rand(9)).
4968: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
4969: substr($$.time,0,5).unpack("H8",pack("I32",time)).
4970: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4971: # ----------------------------------------------- Make sure that does not exist
4972: my $uhome=&homeserver($uname,$udom,'true');
4973: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4974: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
4975: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4976: $uhome=&homeserver($uname,$udom,'true');
4977: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4978: return 'error: unable to generate unique course-ID';
4979: }
4980: }
4981: # ------------------------------------------------ Check supplied server name
4982: $course_server = $env{'user.homeserver'} if (! defined($course_server));
4983: if (! exists($libserv{$course_server})) {
4984: return 'error:bad server name '.$course_server;
4985: }
4986: # ------------------------------------------------------------- Make the course
4987: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
4988: $course_server);
4989: unless ($reply eq 'ok') { return 'error: '.$reply; }
4990: $uhome=&homeserver($uname,$udom,'true');
4991: if (($uhome eq '') || ($uhome eq 'no_host')) {
4992: return 'error: no such course';
4993: }
4994: # ----------------------------------------------------------------- Course made
4995: # log existence
4996: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
4997: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
4998: &escape($crstype),$uhome);
4999: &flushcourselogs();
5000: # set toplevel url
5001: my $topurl=$url;
5002: unless ($nonstandard) {
5003: # ------------------------------------------ For standard courses, make top url
5004: my $mapurl=&clutter($url);
5005: if ($mapurl eq '/res/') { $mapurl=''; }
5006: $env{'form.initmap'}=(<<ENDINITMAP);
5007: <map>
5008: <resource id="1" type="start"></resource>
5009: <resource id="2" src="$mapurl"></resource>
5010: <resource id="3" type="finish"></resource>
5011: <link index="1" from="1" to="2"></link>
5012: <link index="2" from="2" to="3"></link>
5013: </map>
5014: ENDINITMAP
5015: $topurl=&declutter(
5016: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
5017: );
5018: }
5019: # ----------------------------------------------------------- Write preferences
5020: &writecoursepref($udom.'_'.$uname,
5021: ('description' => $description,
5022: 'url' => $topurl));
5023: return '/'.$udom.'/'.$uname;
5024: }
5025:
5026: sub is_course {
5027: my ($cdom,$cnum) = @_;
5028: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5029: undef,'.');
5030: if (exists($courses{$cdom.'_'.$cnum})) {
5031: return 1;
5032: }
5033: return 0;
5034: }
5035:
5036: # ---------------------------------------------------------- Assign Custom Role
5037:
5038: sub assigncustomrole {
5039: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
5040: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
5041: $end,$start,$deleteflag);
5042: }
5043:
5044: # ----------------------------------------------------------------- Revoke Role
5045:
5046: sub revokerole {
5047: my ($udom,$uname,$url,$role,$deleteflag)=@_;
5048: my $now=time;
5049: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
5050: }
5051:
5052: # ---------------------------------------------------------- Revoke Custom Role
5053:
5054: sub revokecustomrole {
5055: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
5056: my $now=time;
5057: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5058: $deleteflag);
5059: }
5060:
5061: # ------------------------------------------------------------ Disk usage
5062: sub diskusage {
5063: my ($udom,$uname,$directoryRoot)=@_;
5064: $directoryRoot =~ s/\/$//;
5065: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
5066: return $listing;
5067: }
5068:
5069: sub is_locked {
5070: my ($file_name, $domain, $user) = @_;
5071: my @check;
5072: my $is_locked;
5073: push @check, $file_name;
5074: my %locked = &get('file_permissions',\@check,
5075: $env{'user.domain'},$env{'user.name'});
5076: my ($tmp)=keys(%locked);
5077: if ($tmp=~/^error:/) { undef(%locked); }
5078:
5079: if (ref($locked{$file_name}) eq 'ARRAY') {
5080: $is_locked = 'false';
5081: foreach my $entry (@{$locked{$file_name}}) {
5082: if (ref($entry) eq 'ARRAY') {
5083: $is_locked = 'true';
5084: last;
5085: }
5086: }
5087: } else {
5088: $is_locked = 'false';
5089: }
5090: }
5091:
5092: sub declutter_portfile {
5093: my ($file) = @_;
5094: &logthis("got $file");
5095: $file =~ s-^(/portfolio/|portfolio/)-/-;
5096: &logthis("ret $file");
5097: return $file;
5098: }
5099:
5100: # ------------------------------------------------------------- Mark as Read Only
5101:
5102: sub mark_as_readonly {
5103: my ($domain,$user,$files,$what) = @_;
5104: my %current_permissions = &dump('file_permissions',$domain,$user);
5105: my ($tmp)=keys(%current_permissions);
5106: if ($tmp=~/^error:/) { undef(%current_permissions); }
5107: foreach my $file (@{$files}) {
5108: $file = &declutter_portfile($file);
5109: push(@{$current_permissions{$file}},$what);
5110: }
5111: &put('file_permissions',\%current_permissions,$domain,$user);
5112: return;
5113: }
5114:
5115: # ------------------------------------------------------------Save Selected Files
5116:
5117: sub save_selected_files {
5118: my ($user, $path, @files) = @_;
5119: my $filename = $user."savedfiles";
5120: my @other_files = &files_not_in_path($user, $path);
5121: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5122: foreach my $file (@files) {
5123: print (OUT $env{'form.currentpath'}.$file."\n");
5124: }
5125: foreach my $file (@other_files) {
5126: print (OUT $file."\n");
5127: }
5128: close (OUT);
5129: return 'ok';
5130: }
5131:
5132: sub clear_selected_files {
5133: my ($user) = @_;
5134: my $filename = $user."savedfiles";
5135: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5136: print (OUT undef);
5137: close (OUT);
5138: return ("ok");
5139: }
5140:
5141: sub files_in_path {
5142: my ($user, $path) = @_;
5143: my $filename = $user."savedfiles";
5144: my %return_files;
5145: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5146: while (my $line_in = <IN>) {
5147: chomp ($line_in);
5148: my @paths_and_file = split (m!/!, $line_in);
5149: my $file_part = pop (@paths_and_file);
5150: my $path_part = join ('/', @paths_and_file);
5151: $path_part.='/';
5152: my $path_and_file = $path_part.$file_part;
5153: if ($path_part eq $path) {
5154: $return_files{$file_part}= 'selected';
5155: }
5156: }
5157: close (IN);
5158: return (\%return_files);
5159: }
5160:
5161: # called in portfolio select mode, to show files selected NOT in current directory
5162: sub files_not_in_path {
5163: my ($user, $path) = @_;
5164: my $filename = $user."savedfiles";
5165: my @return_files;
5166: my $path_part;
5167: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5168: while (my $line = <IN>) {
5169: #ok, I know it's clunky, but I want it to work
5170: my @paths_and_file = split(m|/|, $line);
5171: my $file_part = pop(@paths_and_file);
5172: chomp($file_part);
5173: my $path_part = join('/', @paths_and_file);
5174: $path_part .= '/';
5175: my $path_and_file = $path_part.$file_part;
5176: if ($path_part ne $path) {
5177: push(@return_files, ($path_and_file));
5178: }
5179: }
5180: close(OUT);
5181: return (@return_files);
5182: }
5183:
5184: #----------------------------------------------Get portfolio file permissions
5185:
5186: sub get_portfile_permissions {
5187: my ($domain,$user) = @_;
5188: my %current_permissions = &dump('file_permissions',$domain,$user);
5189: my ($tmp)=keys(%current_permissions);
5190: if ($tmp=~/^error:/) { undef(%current_permissions); }
5191: return \%current_permissions;
5192: }
5193:
5194: #---------------------------------------------Get portfolio file access controls
5195:
5196: sub get_access_controls {
5197: my ($current_permissions,$group,$file) = @_;
5198: my %access;
5199: my $real_file = $file;
5200: $file =~ s/\.meta$//;
5201: if (defined($file)) {
5202: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5203: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
5204: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
5205: }
5206: }
5207: } else {
5208: foreach my $key (keys(%{$current_permissions})) {
5209: if ($key =~ /\0accesscontrol$/) {
5210: if (defined($group)) {
5211: if ($key !~ m-^\Q$group\E/-) {
5212: next;
5213: }
5214: }
5215: my ($fullpath) = split(/\0/,$key);
5216: if (ref($$current_permissions{$key}) eq 'HASH') {
5217: foreach my $control (keys(%{$$current_permissions{$key}})) {
5218: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5219: }
5220: }
5221: }
5222: }
5223: }
5224: return %access;
5225: }
5226:
5227: sub modify_access_controls {
5228: my ($file_name,$changes,$domain,$user)=@_;
5229: my ($outcome,$deloutcome);
5230: my %store_permissions;
5231: my %new_values;
5232: my %new_control;
5233: my %translation;
5234: my @deletions = ();
5235: my $now = time;
5236: if (exists($$changes{'activate'})) {
5237: if (ref($$changes{'activate'}) eq 'HASH') {
5238: my @newitems = sort(keys(%{$$changes{'activate'}}));
5239: my $numnew = scalar(@newitems);
5240: for (my $i=0; $i<$numnew; $i++) {
5241: my $newkey = $newitems[$i];
5242: my $newid = &Apache::loncommon::get_cgi_id();
5243: if ($newkey =~ /^\d+:/) {
5244: $newkey =~ s/^(\d+)/$newid/;
5245: $translation{$1} = $newid;
5246: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5247: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5248: $translation{$1} = $newid;
5249: }
5250: $new_values{$file_name."\0".$newkey} =
5251: $$changes{'activate'}{$newitems[$i]};
5252: $new_control{$newkey} = $now;
5253: }
5254: }
5255: }
5256: my %todelete;
5257: my %changed_items;
5258: foreach my $action ('delete','update') {
5259: if (exists($$changes{$action})) {
5260: if (ref($$changes{$action}) eq 'HASH') {
5261: foreach my $key (keys(%{$$changes{$action}})) {
5262: my ($itemnum) = ($key =~ /^([^:]+):/);
5263: if ($action eq 'delete') {
5264: $todelete{$itemnum} = 1;
5265: } else {
5266: $changed_items{$itemnum} = $key;
5267: }
5268: }
5269: }
5270: }
5271: }
5272: # get lock on access controls for file.
5273: my $lockhash = {
5274: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5275: ':'.$env{'user.domain'},
5276: };
5277: my $tries = 0;
5278: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5279:
5280: while (($gotlock ne 'ok') && $tries <3) {
5281: $tries ++;
5282: sleep 1;
5283: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5284: }
5285: if ($gotlock eq 'ok') {
5286: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5287: my ($tmp)=keys(%curr_permissions);
5288: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5289: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5290: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5291: if (ref($curr_controls) eq 'HASH') {
5292: foreach my $control_item (keys(%{$curr_controls})) {
5293: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5294: if (defined($todelete{$itemnum})) {
5295: push(@deletions,$file_name."\0".$control_item);
5296: } else {
5297: if (defined($changed_items{$itemnum})) {
5298: $new_control{$changed_items{$itemnum}} = $now;
5299: push(@deletions,$file_name."\0".$control_item);
5300: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5301: } else {
5302: $new_control{$control_item} = $$curr_controls{$control_item};
5303: }
5304: }
5305: }
5306: }
5307: }
5308: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5309: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5310: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5311: # remove lock
5312: my @del_lock = ($file_name."\0".'locked_access_records');
5313: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5314: my ($file,$group);
5315: if (&is_course($domain,$user)) {
5316: ($group,$file) = split(/\//,$file_name,2);
5317: } else {
5318: $file = $file_name;
5319: }
5320: my $sqlresult =
5321: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5322: $group);
5323: } else {
5324: $outcome = "error: could not obtain lockfile\n";
5325: }
5326: return ($outcome,$deloutcome,\%new_values,\%translation);
5327: }
5328:
5329: #------------------------------------------------------Get Marked as Read Only
5330:
5331: sub get_marked_as_readonly {
5332: my ($domain,$user,$what,$group) = @_;
5333: my $current_permissions = &get_portfile_permissions($domain,$user);
5334: my @readonly_files;
5335: my $cmp1=$what;
5336: if (ref($what)) { $cmp1=join('',@{$what}) };
5337: while (my ($file_name,$value) = each(%{$current_permissions})) {
5338: if (defined($group)) {
5339: if ($file_name !~ m-^\Q$group\E/-) {
5340: next;
5341: }
5342: }
5343: if (ref($value) eq "ARRAY"){
5344: foreach my $stored_what (@{$value}) {
5345: my $cmp2=$stored_what;
5346: if (ref($stored_what) eq 'ARRAY') {
5347: $cmp2=join('',@{$stored_what});
5348: }
5349: if ($cmp1 eq $cmp2) {
5350: push(@readonly_files, $file_name);
5351: last;
5352: } elsif (!defined($what)) {
5353: push(@readonly_files, $file_name);
5354: last;
5355: }
5356: }
5357: }
5358: }
5359: return @readonly_files;
5360: }
5361: #-----------------------------------------------------------Get Marked as Read Only Hash
5362:
5363: sub get_marked_as_readonly_hash {
5364: my ($current_permissions,$group,$what) = @_;
5365: my %readonly_files;
5366: while (my ($file_name,$value) = each(%{$current_permissions})) {
5367: if (defined($group)) {
5368: if ($file_name !~ m-^\Q$group\E/-) {
5369: next;
5370: }
5371: }
5372: if (ref($value) eq "ARRAY"){
5373: foreach my $stored_what (@{$value}) {
5374: if (ref($stored_what) eq 'ARRAY') {
5375: foreach my $lock_descriptor(@{$stored_what}) {
5376: if ($lock_descriptor eq 'graded') {
5377: $readonly_files{$file_name} = 'graded';
5378: } elsif ($lock_descriptor eq 'handback') {
5379: $readonly_files{$file_name} = 'handback';
5380: } else {
5381: if (!exists($readonly_files{$file_name})) {
5382: $readonly_files{$file_name} = 'locked';
5383: }
5384: }
5385: }
5386: }
5387: }
5388: }
5389: }
5390: return %readonly_files;
5391: }
5392: # ------------------------------------------------------------ Unmark as Read Only
5393:
5394: sub unmark_as_readonly {
5395: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5396: # for portfolio submissions, $what contains [$symb,$crsid]
5397: my ($domain,$user,$what,$file_name,$group) = @_;
5398: $file_name = &declutter_portfile($file_name);
5399: my $symb_crs = $what;
5400: if (ref($what)) { $symb_crs=join('',@$what); }
5401: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
5402: my ($tmp)=keys(%current_permissions);
5403: if ($tmp=~/^error:/) { undef(%current_permissions); }
5404: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
5405: foreach my $file (@readonly_files) {
5406: my $clean_file = &declutter_portfile($file);
5407: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
5408: my $current_locks = $current_permissions{$file};
5409: my @new_locks;
5410: my @del_keys;
5411: if (ref($current_locks) eq "ARRAY"){
5412: foreach my $locker (@{$current_locks}) {
5413: my $compare=$locker;
5414: if (ref($locker) eq 'ARRAY') {
5415: $compare=join('',@{$locker});
5416: if ($compare ne $symb_crs) {
5417: push(@new_locks, $locker);
5418: }
5419: }
5420: }
5421: if (scalar(@new_locks) > 0) {
5422: $current_permissions{$file} = \@new_locks;
5423: } else {
5424: push(@del_keys, $file);
5425: &del('file_permissions',\@del_keys, $domain, $user);
5426: delete($current_permissions{$file});
5427: }
5428: }
5429: }
5430: &put('file_permissions',\%current_permissions,$domain,$user);
5431: return;
5432: }
5433:
5434: # ------------------------------------------------------------ Directory lister
5435:
5436: sub dirlist {
5437: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5438:
5439: $uri=~s/^\///;
5440: $uri=~s/\/$//;
5441: my ($udom, $uname);
5442: (undef,$udom,$uname)=split(/\//,$uri);
5443: if(defined($userdomain)) {
5444: $udom = $userdomain;
5445: }
5446: if(defined($username)) {
5447: $uname = $username;
5448: }
5449:
5450: my $dirRoot = $perlvar{'lonDocRoot'};
5451: if(defined($alternateDirectoryRoot)) {
5452: $dirRoot = $alternateDirectoryRoot;
5453: $dirRoot =~ s/\/$//;
5454: }
5455:
5456: if($udom) {
5457: if($uname) {
5458: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5459: &homeserver($uname,$udom));
5460: my @listing_results;
5461: if ($listing eq 'unknown_cmd') {
5462: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5463: &homeserver($uname,$udom));
5464: @listing_results = split(/:/,$listing);
5465: } else {
5466: @listing_results = map { &unescape($_); } split(/:/,$listing);
5467: }
5468: return @listing_results;
5469: } elsif(!defined($alternateDirectoryRoot)) {
5470: my %allusers;
5471: foreach my $tryserver (keys(%libserv)) {
5472: if($hostdom{$tryserver} eq $udom) {
5473: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5474: $udom, $tryserver);
5475: my @listing_results;
5476: if ($listing eq 'unknown_cmd') {
5477: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5478: $udom, $tryserver);
5479: @listing_results = split(/:/,$listing);
5480: } else {
5481: @listing_results =
5482: map { &unescape($_); } split(/:/,$listing);
5483: }
5484: if ($listing_results[0] ne 'no_such_dir' &&
5485: $listing_results[0] ne 'empty' &&
5486: $listing_results[0] ne 'con_lost') {
5487: foreach my $line (@listing_results) {
5488: my ($entry) = split(/&/,$line,2);
5489: $allusers{$entry} = 1;
5490: }
5491: }
5492: }
5493: }
5494: my $alluserstr='';
5495: foreach my $user (sort(keys(%allusers))) {
5496: $alluserstr.=$user.'&user:';
5497: }
5498: $alluserstr=~s/:$//;
5499: return split(/:/,$alluserstr);
5500: } else {
5501: return ('missing user name');
5502: }
5503: } elsif(!defined($alternateDirectoryRoot)) {
5504: my $tryserver;
5505: my %alldom=();
5506: foreach $tryserver (keys(%libserv)) {
5507: $alldom{$hostdom{$tryserver}}=1;
5508: }
5509: my $alldomstr='';
5510: foreach my $domain (sort(keys(%alldom))) {
5511: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
5512: }
5513: $alldomstr=~s/:$//;
5514: return split(/:/,$alldomstr);
5515: } else {
5516: return ('missing domain');
5517: }
5518: }
5519:
5520: # --------------------------------------------- GetFileTimestamp
5521: # This function utilizes dirlist and returns the date stamp for
5522: # when it was last modified. It will also return an error of -1
5523: # if an error occurs
5524:
5525: ##
5526: ## FIXME: This subroutine assumes its caller knows something about the
5527: ## directory structure of the home server for the student ($root).
5528: ## Not a good assumption to make. Since this is for looking up files
5529: ## in user directories, the full path should be constructed by lond, not
5530: ## whatever machine we request data from.
5531: ##
5532: sub GetFileTimestamp {
5533: my ($studentDomain,$studentName,$filename,$root)=@_;
5534: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5535: $studentName = &LONCAPA::clean_username($studentName);
5536: my $subdir=$studentName.'__';
5537: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5538: my $proname="$studentDomain/$subdir/$studentName";
5539: $proname .= '/'.$filename;
5540: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5541: $studentName, $root);
5542: my @stats = split('&', $fileStat);
5543: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5544: # @stats contains first the filename, then the stat output
5545: return $stats[10]; # so this is 10 instead of 9.
5546: } else {
5547: return -1;
5548: }
5549: }
5550:
5551: sub stat_file {
5552: my ($uri) = @_;
5553: $uri = &clutter_with_no_wrapper($uri);
5554:
5555: my ($udom,$uname,$file,$dir);
5556: if ($uri =~ m-^/(uploaded|editupload)/-) {
5557: ($udom,$uname,$file) =
5558: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
5559: $file = 'userfiles/'.$file;
5560: $dir = &propath($udom,$uname);
5561: }
5562: if ($uri =~ m-^/res/-) {
5563: ($udom,$uname) =
5564: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
5565: $file = $uri;
5566: }
5567:
5568: if (!$udom || !$uname || !$file) {
5569: # unable to handle the uri
5570: return ();
5571: }
5572:
5573: my ($result) = &dirlist($file,$udom,$uname,$dir);
5574: my @stats = split('&', $result);
5575:
5576: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5577: shift(@stats); #filename is first
5578: return @stats;
5579: }
5580: return ();
5581: }
5582:
5583: # -------------------------------------------------------- Value of a Condition
5584:
5585: # gets the value of a specific preevaluated condition
5586: # stored in the string $env{user.state.<cid>}
5587: # or looks up a condition reference in the bighash and if if hasn't
5588: # already been evaluated recurses into docondval to get the value of
5589: # the condition, then memoizing it to
5590: # $env{user.state.<cid>.<condition>}
5591: sub directcondval {
5592: my $number=shift;
5593: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5594: &Apache::lonuserstate::evalstate();
5595: }
5596: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5597: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5598: } elsif ($number =~ /^_/) {
5599: my $sub_condition;
5600: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5601: &GDBM_READER(),0640)) {
5602: $sub_condition=$bighash{'conditions'.$number};
5603: untie(%bighash);
5604: }
5605: my $value = &docondval($sub_condition);
5606: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5607: return $value;
5608: }
5609: if ($env{'user.state.'.$env{'request.course.id'}}) {
5610: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5611: } else {
5612: return 2;
5613: }
5614: }
5615:
5616: # get the collection of conditions for this resource
5617: sub condval {
5618: my $condidx=shift;
5619: my $allpathcond='';
5620: foreach my $cond (split(/\|/,$condidx)) {
5621: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5622: $allpathcond.=
5623: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5624: }
5625: }
5626: $allpathcond=~s/\|$//;
5627: return &docondval($allpathcond);
5628: }
5629:
5630: #evaluates an expression of conditions
5631: sub docondval {
5632: my ($allpathcond) = @_;
5633: my $result=0;
5634: if ($env{'request.course.id'}
5635: && defined($allpathcond)) {
5636: my $operand='|';
5637: my @stack;
5638: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5639: if ($chunk eq '(') {
5640: push @stack,($operand,$result);
5641: } elsif ($chunk eq ')') {
5642: my $before=pop @stack;
5643: if (pop @stack eq '&') {
5644: $result=$result>$before?$before:$result;
5645: } else {
5646: $result=$result>$before?$result:$before;
5647: }
5648: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5649: $operand=$chunk;
5650: } else {
5651: my $new=directcondval($chunk);
5652: if ($operand eq '&') {
5653: $result=$result>$new?$new:$result;
5654: } else {
5655: $result=$result>$new?$result:$new;
5656: }
5657: }
5658: }
5659: }
5660: return $result;
5661: }
5662:
5663: # ---------------------------------------------------- Devalidate courseresdata
5664:
5665: sub devalidatecourseresdata {
5666: my ($coursenum,$coursedomain)=@_;
5667: my $hashid=$coursenum.':'.$coursedomain;
5668: &devalidate_cache_new('courseres',$hashid);
5669: }
5670:
5671:
5672: # --------------------------------------------------- Course Resourcedata Query
5673:
5674: sub get_courseresdata {
5675: my ($coursenum,$coursedomain)=@_;
5676: my $coursehom=&homeserver($coursenum,$coursedomain);
5677: my $hashid=$coursenum.':'.$coursedomain;
5678: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5679: my %dumpreply;
5680: unless (defined($cached)) {
5681: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5682: $result=\%dumpreply;
5683: my ($tmp) = keys(%dumpreply);
5684: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5685: &do_cache_new('courseres',$hashid,$result,600);
5686: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5687: return $tmp;
5688: } elsif ($tmp =~ /^(error)/) {
5689: $result=undef;
5690: &do_cache_new('courseres',$hashid,$result,600);
5691: }
5692: }
5693: return $result;
5694: }
5695:
5696: sub devalidateuserresdata {
5697: my ($uname,$udom)=@_;
5698: my $hashid="$udom:$uname";
5699: &devalidate_cache_new('userres',$hashid);
5700: }
5701:
5702: sub get_userresdata {
5703: my ($uname,$udom)=@_;
5704: #most student don\'t have any data set, check if there is some data
5705: if (&EXT_cache_status($udom,$uname)) { return undef; }
5706:
5707: my $hashid="$udom:$uname";
5708: my ($result,$cached)=&is_cached_new('userres',$hashid);
5709: if (!defined($cached)) {
5710: my %resourcedata=&dump('resourcedata',$udom,$uname);
5711: $result=\%resourcedata;
5712: &do_cache_new('userres',$hashid,$result,600);
5713: }
5714: my ($tmp)=keys(%$result);
5715: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5716: return $result;
5717: }
5718: #error 2 occurs when the .db doesn't exist
5719: if ($tmp!~/error: 2 /) {
5720: &logthis("<font color=\"blue\">WARNING:".
5721: " Trying to get resource data for ".
5722: $uname." at ".$udom.": ".
5723: $tmp."</font>");
5724: } elsif ($tmp=~/error: 2 /) {
5725: #&EXT_cache_set($udom,$uname);
5726: &do_cache_new('userres',$hashid,undef,600);
5727: undef($tmp); # not really an error so don't send it back
5728: }
5729: return $tmp;
5730: }
5731:
5732: sub resdata {
5733: my ($name,$domain,$type,@which)=@_;
5734: my $result;
5735: if ($type eq 'course') {
5736: $result=&get_courseresdata($name,$domain);
5737: } elsif ($type eq 'user') {
5738: $result=&get_userresdata($name,$domain);
5739: }
5740: if (!ref($result)) { return $result; }
5741: foreach my $item (@which) {
5742: if (defined($result->{$item})) {
5743: return $result->{$item};
5744: }
5745: }
5746: return undef;
5747: }
5748:
5749: #
5750: # EXT resource caching routines
5751: #
5752:
5753: sub clear_EXT_cache_status {
5754: &delenv('cache.EXT.');
5755: }
5756:
5757: sub EXT_cache_status {
5758: my ($target_domain,$target_user) = @_;
5759: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5760: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
5761: # We know already the user has no data
5762: return 1;
5763: } else {
5764: return 0;
5765: }
5766: }
5767:
5768: sub EXT_cache_set {
5769: my ($target_domain,$target_user) = @_;
5770: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5771: #&appenv($cachename => time);
5772: }
5773:
5774: # --------------------------------------------------------- Value of a Variable
5775: sub EXT {
5776:
5777: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5778: unless ($varname) { return ''; }
5779: #get real user name/domain, courseid and symb
5780: my $courseid;
5781: my $publicuser;
5782: if ($symbparm) {
5783: $symbparm=&get_symb_from_alias($symbparm);
5784: }
5785: if (!($uname && $udom)) {
5786: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
5787: if (!$symbparm) { $symbparm=$cursymb; }
5788: } else {
5789: $courseid=$env{'request.course.id'};
5790: }
5791: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5792: my $rest;
5793: if (defined($therest[0])) {
5794: $rest=join('.',@therest);
5795: } else {
5796: $rest='';
5797: }
5798:
5799: my $qualifierrest=$qualifier;
5800: if ($rest) { $qualifierrest.='.'.$rest; }
5801: my $spacequalifierrest=$space;
5802: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
5803: if ($realm eq 'user') {
5804: # --------------------------------------------------------------- user.resource
5805: if ($space eq 'resource') {
5806: if ( (defined($Apache::lonhomework::parsing_a_problem)
5807: || defined($Apache::lonhomework::parsing_a_task))
5808: &&
5809: ($symbparm eq &symbread()) ) {
5810: # if we are in the middle of processing the resource the
5811: # get the value we are planning on committing
5812: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5813: return $Apache::lonhomework::results{$qualifierrest};
5814: } else {
5815: return $Apache::lonhomework::history{$qualifierrest};
5816: }
5817: } else {
5818: my %restored;
5819: if ($publicuser || $env{'request.state'} eq 'construct') {
5820: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5821: } else {
5822: %restored=&restore($symbparm,$courseid,$udom,$uname);
5823: }
5824: return $restored{$qualifierrest};
5825: }
5826: # ----------------------------------------------------------------- user.access
5827: } elsif ($space eq 'access') {
5828: # FIXME - not supporting calls for a specific user
5829: return &allowed($qualifier,$rest);
5830: # ------------------------------------------ user.preferences, user.environment
5831: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
5832: if (($uname eq $env{'user.name'}) &&
5833: ($udom eq $env{'user.domain'})) {
5834: return $env{join('.',('environment',$qualifierrest))};
5835: } else {
5836: my %returnhash;
5837: if (!$publicuser) {
5838: %returnhash=&userenvironment($udom,$uname,
5839: $qualifierrest);
5840: }
5841: return $returnhash{$qualifierrest};
5842: }
5843: # ----------------------------------------------------------------- user.course
5844: } elsif ($space eq 'course') {
5845: # FIXME - not supporting calls for a specific user
5846: return $env{join('.',('request.course',$qualifier))};
5847: # ------------------------------------------------------------------- user.role
5848: } elsif ($space eq 'role') {
5849: # FIXME - not supporting calls for a specific user
5850: my ($role,$where)=split(/\./,$env{'request.role'});
5851: if ($qualifier eq 'value') {
5852: return $role;
5853: } elsif ($qualifier eq 'extent') {
5854: return $where;
5855: }
5856: # ----------------------------------------------------------------- user.domain
5857: } elsif ($space eq 'domain') {
5858: return $udom;
5859: # ------------------------------------------------------------------- user.name
5860: } elsif ($space eq 'name') {
5861: return $uname;
5862: # ---------------------------------------------------- Any other user namespace
5863: } else {
5864: my %reply;
5865: if (!$publicuser) {
5866: %reply=&get($space,[$qualifierrest],$udom,$uname);
5867: }
5868: return $reply{$qualifierrest};
5869: }
5870: } elsif ($realm eq 'query') {
5871: # ---------------------------------------------- pull stuff out of query string
5872: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5873: [$spacequalifierrest]);
5874: return $env{'form.'.$spacequalifierrest};
5875: } elsif ($realm eq 'request') {
5876: # ------------------------------------------------------------- request.browser
5877: if ($space eq 'browser') {
5878: if ($qualifier eq 'textremote') {
5879: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
5880: return 1;
5881: } else {
5882: return 0;
5883: }
5884: } else {
5885: return $env{'browser.'.$qualifier};
5886: }
5887: # ------------------------------------------------------------ request.filename
5888: } else {
5889: return $env{'request.'.$spacequalifierrest};
5890: }
5891: } elsif ($realm eq 'course') {
5892: # ---------------------------------------------------------- course.description
5893: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
5894: } elsif ($realm eq 'resource') {
5895:
5896: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
5897: if (!$symbparm) { $symbparm=&symbread(); }
5898: }
5899:
5900: if ($space eq 'title') {
5901: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
5902: return &gettitle($symbparm);
5903: }
5904:
5905: if ($space eq 'map') {
5906: my ($map) = &decode_symb($symbparm);
5907: return &symbread($map);
5908: }
5909:
5910: my ($section, $group, @groups);
5911: my ($courselevelm,$courselevel);
5912: if ($symbparm && defined($courseid) &&
5913: $courseid eq $env{'request.course.id'}) {
5914:
5915: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
5916:
5917: # ----------------------------------------------------- Cascading lookup scheme
5918: my $symbp=$symbparm;
5919: my $mapp=&deversion((&decode_symb($symbp))[0]);
5920:
5921: my $symbparm=$symbp.'.'.$spacequalifierrest;
5922: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
5923:
5924: if (($env{'user.name'} eq $uname) &&
5925: ($env{'user.domain'} eq $udom)) {
5926: $section=$env{'request.course.sec'};
5927: @groups = split(/:/,$env{'request.course.groups'});
5928: @groups=&sort_course_groups($courseid,@groups);
5929: } else {
5930: if (! defined($usection)) {
5931: $section=&getsection($udom,$uname,$courseid);
5932: } else {
5933: $section = $usection;
5934: }
5935: @groups = &get_users_groups($udom,$uname,$courseid);
5936: }
5937:
5938: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
5939: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
5940: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
5941:
5942: $courselevel=$courseid.'.'.$spacequalifierrest;
5943: my $courselevelr=$courseid.'.'.$symbparm;
5944: $courselevelm=$courseid.'.'.$mapparm;
5945:
5946: # ----------------------------------------------------------- first, check user
5947:
5948: my $userreply=&resdata($uname,$udom,'user',
5949: ($courselevelr,$courselevelm,
5950: $courselevel));
5951: if (defined($userreply)) { return $userreply; }
5952:
5953: # ------------------------------------------------ second, check some of course
5954: my $coursereply;
5955: if (@groups > 0) {
5956: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
5957: $mapparm,$spacequalifierrest);
5958: if (defined($coursereply)) { return $coursereply; }
5959: }
5960:
5961: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5962: $env{'course.'.$courseid.'.domain'},
5963: 'course',
5964: ($seclevelr,$seclevelm,$seclevel,
5965: $courselevelr));
5966: if (defined($coursereply)) { return $coursereply; }
5967:
5968: # ------------------------------------------------------ third, check map parms
5969: my %parmhash=();
5970: my $thisparm='';
5971: if (tie(%parmhash,'GDBM_File',
5972: $env{'request.course.fn'}.'_parms.db',
5973: &GDBM_READER(),0640)) {
5974: $thisparm=$parmhash{$symbparm};
5975: untie(%parmhash);
5976: }
5977: if ($thisparm) { return $thisparm; }
5978: }
5979: # ------------------------------------------ fourth, look in resource metadata
5980:
5981: $spacequalifierrest=~s/\./\_/;
5982: my $filename;
5983: if (!$symbparm) { $symbparm=&symbread(); }
5984: if ($symbparm) {
5985: $filename=(&decode_symb($symbparm))[2];
5986: } else {
5987: $filename=$env{'request.filename'};
5988: }
5989: my $metadata=&metadata($filename,$spacequalifierrest);
5990: if (defined($metadata)) { return $metadata; }
5991: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
5992: if (defined($metadata)) { return $metadata; }
5993:
5994: # ---------------------------------------------- fourth, look in rest pf course
5995: if ($symbparm && defined($courseid) &&
5996: $courseid eq $env{'request.course.id'}) {
5997: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5998: $env{'course.'.$courseid.'.domain'},
5999: 'course',
6000: ($courselevelm,$courselevel));
6001: if (defined($coursereply)) { return $coursereply; }
6002: }
6003: # ------------------------------------------------------------------ Cascade up
6004: unless ($space eq '0') {
6005: my @parts=split(/_/,$space);
6006: my $id=pop(@parts);
6007: my $part=join('_',@parts);
6008: if ($part eq '') { $part='0'; }
6009: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
6010: $symbparm,$udom,$uname,$section,1);
6011: if (defined($partgeneral)) { return $partgeneral; }
6012: }
6013: if ($recurse) { return undef; }
6014: my $pack_def=&packages_tab_default($filename,$varname);
6015: if (defined($pack_def)) { return $pack_def; }
6016:
6017: # ---------------------------------------------------- Any other user namespace
6018: } elsif ($realm eq 'environment') {
6019: # ----------------------------------------------------------------- environment
6020: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6021: return $env{'environment.'.$spacequalifierrest};
6022: } else {
6023: if ($uname eq 'anonymous' && $udom eq '') {
6024: return '';
6025: }
6026: my %returnhash=&userenvironment($udom,$uname,
6027: $spacequalifierrest);
6028: return $returnhash{$spacequalifierrest};
6029: }
6030: } elsif ($realm eq 'system') {
6031: # ----------------------------------------------------------------- system.time
6032: if ($space eq 'time') {
6033: return time;
6034: }
6035: } elsif ($realm eq 'server') {
6036: # ----------------------------------------------------------------- system.time
6037: if ($space eq 'name') {
6038: return $ENV{'SERVER_NAME'};
6039: }
6040: }
6041: return '';
6042: }
6043:
6044: sub check_group_parms {
6045: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6046: my @groupitems = ();
6047: my $resultitem;
6048: my @levels = ($symbparm,$mapparm,$what);
6049: foreach my $group (@{$groups}) {
6050: foreach my $level (@levels) {
6051: my $item = $courseid.'.['.$group.'].'.$level;
6052: push(@groupitems,$item);
6053: }
6054: }
6055: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6056: $env{'course.'.$courseid.'.domain'},
6057: 'course',@groupitems);
6058: return $coursereply;
6059: }
6060:
6061: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
6062: my ($courseid,@groups) = @_;
6063: @groups = sort(@groups);
6064: return @groups;
6065: }
6066:
6067: sub packages_tab_default {
6068: my ($uri,$varname)=@_;
6069: my (undef,$part,$name)=split(/\./,$varname);
6070:
6071: my (@extension,@specifics,$do_default);
6072: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
6073: my ($pack_type,$pack_part)=split(/_/,$package,2);
6074: if ($pack_type eq 'default') {
6075: $do_default=1;
6076: } elsif ($pack_type eq 'extension') {
6077: push(@extension,[$package,$pack_type,$pack_part]);
6078: } else {
6079: push(@specifics,[$package,$pack_type,$pack_part]);
6080: }
6081: }
6082: # first look for a package that matches the requested part id
6083: foreach my $package (@specifics) {
6084: my (undef,$pack_type,$pack_part)=@{$package};
6085: next if ($pack_part ne $part);
6086: if (defined($packagetab{"$pack_type&$name&default"})) {
6087: return $packagetab{"$pack_type&$name&default"};
6088: }
6089: }
6090: # look for any possible matching non extension_ package
6091: foreach my $package (@specifics) {
6092: my (undef,$pack_type,$pack_part)=@{$package};
6093: if (defined($packagetab{"$pack_type&$name&default"})) {
6094: return $packagetab{"$pack_type&$name&default"};
6095: }
6096: if ($pack_type eq 'part') { $pack_part='0'; }
6097: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6098: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
6099: }
6100: }
6101: # look for any posible extension_ match
6102: foreach my $package (@extension) {
6103: my ($package,$pack_type)=@{$package};
6104: if (defined($packagetab{"$pack_type&$name&default"})) {
6105: return $packagetab{"$pack_type&$name&default"};
6106: }
6107: if (defined($packagetab{$package."&$name&default"})) {
6108: return $packagetab{$package."&$name&default"};
6109: }
6110: }
6111: # look for a global default setting
6112: if ($do_default && defined($packagetab{"default&$name&default"})) {
6113: return $packagetab{"default&$name&default"};
6114: }
6115: return undef;
6116: }
6117:
6118: sub add_prefix_and_part {
6119: my ($prefix,$part)=@_;
6120: my $keyroot;
6121: if (defined($prefix) && $prefix !~ /^__/) {
6122: # prefix that has a part already
6123: $keyroot=$prefix;
6124: } elsif (defined($prefix)) {
6125: # prefix that is missing a part
6126: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6127: } else {
6128: # no prefix at all
6129: if (defined($part)) { $keyroot='_'.$part; }
6130: }
6131: return $keyroot;
6132: }
6133:
6134: # ---------------------------------------------------------------- Get metadata
6135:
6136: my %metaentry;
6137: sub metadata {
6138: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
6139: $uri=&declutter($uri);
6140: # if it is a non metadata possible uri return quickly
6141: if (($uri eq '') ||
6142: (($uri =~ m|^/*adm/|) &&
6143: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
6144: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
6145: ($uri =~ m|home/$match_username/public_html/|)) {
6146: return undef;
6147: }
6148: my $filename=$uri;
6149: $uri=~s/\.meta$//;
6150: #
6151: # Is the metadata already cached?
6152: # Look at timestamp of caching
6153: # Everything is cached by the main uri, libraries are never directly cached
6154: #
6155: if (!defined($liburi)) {
6156: my ($result,$cached)=&is_cached_new('meta',$uri);
6157: if (defined($cached)) { return $result->{':'.$what}; }
6158: }
6159: {
6160: #
6161: # Is this a recursive call for a library?
6162: #
6163: # if (! exists($metacache{$uri})) {
6164: # $metacache{$uri}={};
6165: # }
6166: if ($liburi) {
6167: $liburi=&declutter($liburi);
6168: $filename=$liburi;
6169: } else {
6170: &devalidate_cache_new('meta',$uri);
6171: undef(%metaentry);
6172: }
6173: my %metathesekeys=();
6174: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
6175: my $metastring;
6176: if ($uri !~ m -^(editupload)/-) {
6177: my $file=&filelocation('',&clutter($filename));
6178: #push(@{$metaentry{$uri.'.file'}},$file);
6179: $metastring=&getfile($file);
6180: }
6181: my $parser=HTML::LCParser->new(\$metastring);
6182: my $token;
6183: undef %metathesekeys;
6184: while ($token=$parser->get_token) {
6185: if ($token->[0] eq 'S') {
6186: if (defined($token->[2]->{'package'})) {
6187: #
6188: # This is a package - get package info
6189: #
6190: my $package=$token->[2]->{'package'};
6191: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6192: if (defined($token->[2]->{'id'})) {
6193: $keyroot.='_'.$token->[2]->{'id'};
6194: }
6195: if ($metaentry{':packages'}) {
6196: $metaentry{':packages'}.=','.$package.$keyroot;
6197: } else {
6198: $metaentry{':packages'}=$package.$keyroot;
6199: }
6200: foreach my $pack_entry (keys(%packagetab)) {
6201: my $part=$keyroot;
6202: $part=~s/^\_//;
6203: if ($pack_entry=~/^\Q$package\E\&/ ||
6204: $pack_entry=~/^\Q$package\E_0\&/) {
6205: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
6206: # ignore package.tab specified default values
6207: # here &package_tab_default() will fetch those
6208: if ($subp eq 'default') { next; }
6209: my $value=$packagetab{$pack_entry};
6210: my $unikey;
6211: if ($pack =~ /_0$/) {
6212: $unikey='parameter_0_'.$name;
6213: $part=0;
6214: } else {
6215: $unikey='parameter'.$keyroot.'_'.$name;
6216: }
6217: if ($subp eq 'display') {
6218: $value.=' [Part: '.$part.']';
6219: }
6220: $metaentry{':'.$unikey.'.part'}=$part;
6221: $metathesekeys{$unikey}=1;
6222: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6223: $metaentry{':'.$unikey.'.'.$subp}=$value;
6224: }
6225: if (defined($metaentry{':'.$unikey.'.default'})) {
6226: $metaentry{':'.$unikey}=
6227: $metaentry{':'.$unikey.'.default'};
6228: }
6229: }
6230: }
6231: } else {
6232: #
6233: # This is not a package - some other kind of start tag
6234: #
6235: my $entry=$token->[1];
6236: my $unikey;
6237: if ($entry eq 'import') {
6238: $unikey='';
6239: } else {
6240: $unikey=$entry;
6241: }
6242: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6243:
6244: if (defined($token->[2]->{'id'})) {
6245: $unikey.='_'.$token->[2]->{'id'};
6246: }
6247:
6248: if ($entry eq 'import') {
6249: #
6250: # Importing a library here
6251: #
6252: if ($depthcount<20) {
6253: my $location=$parser->get_text('/import');
6254: my $dir=$filename;
6255: $dir=~s|[^/]*$||;
6256: $location=&filelocation($dir,$location);
6257: my $metadata =
6258: &metadata($uri,'keys', $location,$unikey,
6259: $depthcount+1);
6260: foreach my $meta (split(',',$metadata)) {
6261: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6262: $metathesekeys{$meta}=1;
6263: }
6264: }
6265: } else {
6266:
6267: if (defined($token->[2]->{'name'})) {
6268: $unikey.='_'.$token->[2]->{'name'};
6269: }
6270: $metathesekeys{$unikey}=1;
6271: foreach my $param (@{$token->[3]}) {
6272: $metaentry{':'.$unikey.'.'.$param} =
6273: $token->[2]->{$param};
6274: }
6275: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
6276: my $default=$metaentry{':'.$unikey.'.default'};
6277: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6278: # only ws inside the tag, and not in default, so use default
6279: # as value
6280: $metaentry{':'.$unikey}=$default;
6281: } else {
6282: # either something interesting inside the tag or default
6283: # uninteresting
6284: $metaentry{':'.$unikey}=$internaltext;
6285: }
6286: # end of not-a-package not-a-library import
6287: }
6288: # end of not-a-package start tag
6289: }
6290: # the next is the end of "start tag"
6291: }
6292: }
6293: my ($extension) = ($uri =~ /\.(\w+)$/);
6294: foreach my $key (keys(%packagetab)) {
6295: #no specific packages #how's our extension
6296: if ($key!~/^extension_\Q$extension\E&/) { next; }
6297: &metadata_create_package_def($uri,$key,'extension_'.$extension,
6298: \%metathesekeys);
6299: }
6300: if (!exists($metaentry{':packages'})) {
6301: foreach my $key (keys(%packagetab)) {
6302: #no specific packages well let's get default then
6303: if ($key!~/^default&/) { next; }
6304: &metadata_create_package_def($uri,$key,'default',
6305: \%metathesekeys);
6306: }
6307: }
6308: # are there custom rights to evaluate
6309: if ($metaentry{':copyright'} eq 'custom') {
6310:
6311: #
6312: # Importing a rights file here
6313: #
6314: unless ($depthcount) {
6315: my $location=$metaentry{':customdistributionfile'};
6316: my $dir=$filename;
6317: $dir=~s|[^/]*$||;
6318: $location=&filelocation($dir,$location);
6319: my $rights_metadata =
6320: &metadata($uri,'keys',$location,'_rights',
6321: $depthcount+1);
6322: foreach my $rights (split(',',$rights_metadata)) {
6323: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6324: $metathesekeys{$rights}=1;
6325: }
6326: }
6327: }
6328: # uniqifiy package listing
6329: my %seen;
6330: my @uniq_packages =
6331: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6332: $metaentry{':packages'} = join(',',@uniq_packages);
6333:
6334: $metaentry{':keys'} = join(',',keys(%metathesekeys));
6335: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6336: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
6337: &do_cache_new('meta',$uri,\%metaentry,60*60);
6338: # this is the end of "was not already recently cached
6339: }
6340: return $metaentry{':'.$what};
6341: }
6342:
6343: sub metadata_create_package_def {
6344: my ($uri,$key,$package,$metathesekeys)=@_;
6345: my ($pack,$name,$subp)=split(/\&/,$key);
6346: if ($subp eq 'default') { next; }
6347:
6348: if (defined($metaentry{':packages'})) {
6349: $metaentry{':packages'}.=','.$package;
6350: } else {
6351: $metaentry{':packages'}=$package;
6352: }
6353: my $value=$packagetab{$key};
6354: my $unikey;
6355: $unikey='parameter_0_'.$name;
6356: $metaentry{':'.$unikey.'.part'}=0;
6357: $$metathesekeys{$unikey}=1;
6358: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6359: $metaentry{':'.$unikey.'.'.$subp}=$value;
6360: }
6361: if (defined($metaentry{':'.$unikey.'.default'})) {
6362: $metaentry{':'.$unikey}=
6363: $metaentry{':'.$unikey.'.default'};
6364: }
6365: }
6366:
6367: sub metadata_generate_part0 {
6368: my ($metadata,$metacache,$uri) = @_;
6369: my %allnames;
6370: foreach my $metakey (keys(%$metadata)) {
6371: if ($metakey=~/^parameter\_(.*)/) {
6372: my $part=$$metacache{':'.$metakey.'.part'};
6373: my $name=$$metacache{':'.$metakey.'.name'};
6374: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
6375: $allnames{$name}=$part;
6376: }
6377: }
6378: }
6379: foreach my $name (keys(%allnames)) {
6380: $$metadata{"parameter_0_$name"}=1;
6381: my $key=":parameter_0_$name";
6382: $$metacache{"$key.part"}='0';
6383: $$metacache{"$key.name"}=$name;
6384: $$metacache{"$key.type"}=$$metacache{':parameter_'.
6385: $allnames{$name}.'_'.$name.
6386: '.type'};
6387: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
6388: '.display'};
6389: my $expr='[Part: '.$allnames{$name}.']';
6390: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
6391: $$metacache{"$key.display"}=$olddis;
6392: }
6393: }
6394:
6395: # ------------------------------------------------------ Devalidate title cache
6396:
6397: sub devalidate_title_cache {
6398: my ($url)=@_;
6399: if (!$env{'request.course.id'}) { return; }
6400: my $symb=&symbread($url);
6401: if (!$symb) { return; }
6402: my $key=$env{'request.course.id'}."\0".$symb;
6403: &devalidate_cache_new('title',$key);
6404: }
6405:
6406: # ------------------------------------------------- Get the title of a resource
6407:
6408: sub gettitle {
6409: my $urlsymb=shift;
6410: my $symb=&symbread($urlsymb);
6411: if ($symb) {
6412: my $key=$env{'request.course.id'}."\0".$symb;
6413: my ($result,$cached)=&is_cached_new('title',$key);
6414: if (defined($cached)) {
6415: return $result;
6416: }
6417: my ($map,$resid,$url)=&decode_symb($symb);
6418: my $title='';
6419: my %bighash;
6420: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6421: &GDBM_READER(),0640)) {
6422: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6423: $title=$bighash{'title_'.$mapid.'.'.$resid};
6424: untie %bighash;
6425: }
6426: $title=~s/\&colon\;/\:/gs;
6427: if ($title) {
6428: return &do_cache_new('title',$key,$title,600);
6429: }
6430: $urlsymb=$url;
6431: }
6432: my $title=&metadata($urlsymb,'title');
6433: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6434: return $title;
6435: }
6436:
6437: sub get_slot {
6438: my ($which,$cnum,$cdom)=@_;
6439: if (!$cnum || !$cdom) {
6440: (undef,my $courseid)=&whichuser();
6441: $cdom=$env{'course.'.$courseid.'.domain'};
6442: $cnum=$env{'course.'.$courseid.'.num'};
6443: }
6444: my $key=join("\0",'slots',$cdom,$cnum,$which);
6445: my %slotinfo;
6446: if (exists($remembered{$key})) {
6447: $slotinfo{$which} = $remembered{$key};
6448: } else {
6449: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6450: &Apache::lonhomework::showhash(%slotinfo);
6451: my ($tmp)=keys(%slotinfo);
6452: if ($tmp=~/^error:/) { return (); }
6453: $remembered{$key} = $slotinfo{$which};
6454: }
6455: if (ref($slotinfo{$which}) eq 'HASH') {
6456: return %{$slotinfo{$which}};
6457: }
6458: return $slotinfo{$which};
6459: }
6460: # ------------------------------------------------- Update symbolic store links
6461:
6462: sub symblist {
6463: my ($mapname,%newhash)=@_;
6464: $mapname=&deversion(&declutter($mapname));
6465: my %hash;
6466: if (($env{'request.course.fn'}) && (%newhash)) {
6467: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6468: &GDBM_WRCREAT(),0640)) {
6469: foreach my $url (keys %newhash) {
6470: next if ($url eq 'last_known'
6471: && $env{'form.no_update_last_known'});
6472: $hash{declutter($url)}=&encode_symb($mapname,
6473: $newhash{$url}->[1],
6474: $newhash{$url}->[0]);
6475: }
6476: if (untie(%hash)) {
6477: return 'ok';
6478: }
6479: }
6480: }
6481: return 'error';
6482: }
6483:
6484: # --------------------------------------------------------------- Verify a symb
6485:
6486: sub symbverify {
6487: my ($symb,$thisurl)=@_;
6488: my $thisfn=$thisurl;
6489: $thisfn=&declutter($thisfn);
6490: # direct jump to resource in page or to a sequence - will construct own symbs
6491: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6492: # check URL part
6493: my ($map,$resid,$url)=&decode_symb($symb);
6494:
6495: unless ($url eq $thisfn) { return 0; }
6496:
6497: $symb=&symbclean($symb);
6498: $thisurl=&deversion($thisurl);
6499: $thisfn=&deversion($thisfn);
6500:
6501: my %bighash;
6502: my $okay=0;
6503:
6504: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6505: &GDBM_READER(),0640)) {
6506: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6507: unless ($ids) {
6508: $ids=$bighash{'ids_/'.$thisurl};
6509: }
6510: if ($ids) {
6511: # ------------------------------------------------------------------- Has ID(s)
6512: foreach my $id (split(/\,/,$ids)) {
6513: my ($mapid,$resid)=split(/\./,$id);
6514: if (
6515: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6516: eq $symb) {
6517: if (($env{'request.role.adv'}) ||
6518: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
6519: $okay=1;
6520: }
6521: }
6522: }
6523: }
6524: untie(%bighash);
6525: }
6526: return $okay;
6527: }
6528:
6529: # --------------------------------------------------------------- Clean-up symb
6530:
6531: sub symbclean {
6532: my $symb=shift;
6533: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6534: # remove version from map
6535: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6536:
6537: # remove version from URL
6538: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6539:
6540: # remove wrapper
6541:
6542: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6543: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6544: return $symb;
6545: }
6546:
6547: # ---------------------------------------------- Split symb to find map and url
6548:
6549: sub encode_symb {
6550: my ($map,$resid,$url)=@_;
6551: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6552: }
6553:
6554: sub decode_symb {
6555: my $symb=shift;
6556: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6557: my ($map,$resid,$url)=split(/___/,$symb);
6558: return (&fixversion($map),$resid,&fixversion($url));
6559: }
6560:
6561: sub fixversion {
6562: my $fn=shift;
6563: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6564: my %bighash;
6565: my $uri=&clutter($fn);
6566: my $key=$env{'request.course.id'}.'_'.$uri;
6567: # is this cached?
6568: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6569: if (defined($cached)) { return $result; }
6570: # unfortunately not cached, or expired
6571: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6572: &GDBM_READER(),0640)) {
6573: if ($bighash{'version_'.$uri}) {
6574: my $version=$bighash{'version_'.$uri};
6575: unless (($version eq 'mostrecent') ||
6576: ($version==&getversion($uri))) {
6577: $uri=~s/\.(\w+)$/\.$version\.$1/;
6578: }
6579: }
6580: untie %bighash;
6581: }
6582: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6583: }
6584:
6585: sub deversion {
6586: my $url=shift;
6587: $url=~s/\.\d+\.(\w+)$/\.$1/;
6588: return $url;
6589: }
6590:
6591: # ------------------------------------------------------ Return symb list entry
6592:
6593: sub symbread {
6594: my ($thisfn,$donotrecurse)=@_;
6595: my $cache_str='request.symbread.cached.'.$thisfn;
6596: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6597: # no filename provided? try from environment
6598: unless ($thisfn) {
6599: if ($env{'request.symb'}) {
6600: return $env{$cache_str}=&symbclean($env{'request.symb'});
6601: }
6602: $thisfn=$env{'request.filename'};
6603: }
6604: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6605: # is that filename actually a symb? Verify, clean, and return
6606: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6607: if (&symbverify($thisfn,$1)) {
6608: return $env{$cache_str}=&symbclean($thisfn);
6609: }
6610: }
6611: $thisfn=declutter($thisfn);
6612: my %hash;
6613: my %bighash;
6614: my $syval='';
6615: if (($env{'request.course.fn'}) && ($thisfn)) {
6616: my $targetfn = $thisfn;
6617: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6618: $targetfn = 'adm/wrapper/'.$thisfn;
6619: }
6620: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6621: $targetfn=$1;
6622: }
6623: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6624: &GDBM_READER(),0640)) {
6625: $syval=$hash{$targetfn};
6626: untie(%hash);
6627: }
6628: # ---------------------------------------------------------- There was an entry
6629: if ($syval) {
6630: #unless ($syval=~/\_\d+$/) {
6631: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6632: #&appenv('request.ambiguous' => $thisfn);
6633: #return $env{$cache_str}='';
6634: #}
6635: #$syval.=$1;
6636: #}
6637: } else {
6638: # ------------------------------------------------------- Was not in symb table
6639: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6640: &GDBM_READER(),0640)) {
6641: # ---------------------------------------------- Get ID(s) for current resource
6642: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6643: unless ($ids) {
6644: $ids=$bighash{'ids_/'.$thisfn};
6645: }
6646: unless ($ids) {
6647: # alias?
6648: $ids=$bighash{'mapalias_'.$thisfn};
6649: }
6650: if ($ids) {
6651: # ------------------------------------------------------------------- Has ID(s)
6652: my @possibilities=split(/\,/,$ids);
6653: if ($#possibilities==0) {
6654: # ----------------------------------------------- There is only one possibility
6655: my ($mapid,$resid)=split(/\./,$ids);
6656: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6657: $resid,$thisfn);
6658: } elsif (!$donotrecurse) {
6659: # ------------------------------------------ There is more than one possibility
6660: my $realpossible=0;
6661: foreach my $id (@possibilities) {
6662: my $file=$bighash{'src_'.$id};
6663: if (&allowed('bre',$file)) {
6664: my ($mapid,$resid)=split(/\./,$id);
6665: if ($bighash{'map_type_'.$mapid} ne 'page') {
6666: $realpossible++;
6667: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6668: $resid,$thisfn);
6669: }
6670: }
6671: }
6672: if ($realpossible!=1) { $syval=''; }
6673: } else {
6674: $syval='';
6675: }
6676: }
6677: untie(%bighash)
6678: }
6679: }
6680: if ($syval) {
6681: return $env{$cache_str}=$syval;
6682: }
6683: }
6684: &appenv('request.ambiguous' => $thisfn);
6685: return $env{$cache_str}='';
6686: }
6687:
6688: # ---------------------------------------------------------- Return random seed
6689:
6690: sub numval {
6691: my $txt=shift;
6692: $txt=~tr/A-J/0-9/;
6693: $txt=~tr/a-j/0-9/;
6694: $txt=~tr/K-T/0-9/;
6695: $txt=~tr/k-t/0-9/;
6696: $txt=~tr/U-Z/0-5/;
6697: $txt=~tr/u-z/0-5/;
6698: $txt=~s/\D//g;
6699: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6700: return int($txt);
6701: }
6702:
6703: sub numval2 {
6704: my $txt=shift;
6705: $txt=~tr/A-J/0-9/;
6706: $txt=~tr/a-j/0-9/;
6707: $txt=~tr/K-T/0-9/;
6708: $txt=~tr/k-t/0-9/;
6709: $txt=~tr/U-Z/0-5/;
6710: $txt=~tr/u-z/0-5/;
6711: $txt=~s/\D//g;
6712: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6713: my $total;
6714: foreach my $val (@txts) { $total+=$val; }
6715: if ($_64bit) { if ($total > 2**32) { return -1; } }
6716: return int($total);
6717: }
6718:
6719: sub numval3 {
6720: use integer;
6721: my $txt=shift;
6722: $txt=~tr/A-J/0-9/;
6723: $txt=~tr/a-j/0-9/;
6724: $txt=~tr/K-T/0-9/;
6725: $txt=~tr/k-t/0-9/;
6726: $txt=~tr/U-Z/0-5/;
6727: $txt=~tr/u-z/0-5/;
6728: $txt=~s/\D//g;
6729: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6730: my $total;
6731: foreach my $val (@txts) { $total+=$val; }
6732: if ($_64bit) { $total=(($total<<32)>>32); }
6733: return $total;
6734: }
6735:
6736: sub digest {
6737: my ($data)=@_;
6738: my $digest=&Digest::MD5::md5($data);
6739: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6740: my ($e,$f);
6741: {
6742: use integer;
6743: $e=($a+$b);
6744: $f=($c+$d);
6745: if ($_64bit) {
6746: $e=(($e<<32)>>32);
6747: $f=(($f<<32)>>32);
6748: }
6749: }
6750: if (wantarray) {
6751: return ($e,$f);
6752: } else {
6753: my $g;
6754: {
6755: use integer;
6756: $g=($e+$f);
6757: if ($_64bit) {
6758: $g=(($g<<32)>>32);
6759: }
6760: }
6761: return $g;
6762: }
6763: }
6764:
6765: sub latest_rnd_algorithm_id {
6766: return '64bit5';
6767: }
6768:
6769: sub get_rand_alg {
6770: my ($courseid)=@_;
6771: if (!$courseid) { $courseid=(&whichuser())[1]; }
6772: if ($courseid) {
6773: return $env{"course.$courseid.rndseed"};
6774: }
6775: return &latest_rnd_algorithm_id();
6776: }
6777:
6778: sub validCODE {
6779: my ($CODE)=@_;
6780: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6781: return 0;
6782: }
6783:
6784: sub getCODE {
6785: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
6786: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6787: defined($Apache::lonhomework::parsing_a_task) ) &&
6788: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
6789: return $Apache::lonhomework::history{'resource.CODE'};
6790: }
6791: return undef;
6792: }
6793:
6794: sub rndseed {
6795: my ($symb,$courseid,$domain,$username)=@_;
6796:
6797: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
6798: if (!$symb) {
6799: unless ($symb=$wsymb) { return time; }
6800: }
6801: if (!$courseid) { $courseid=$wcourseid; }
6802: if (!$domain) { $domain=$wdomain; }
6803: if (!$username) { $username=$wusername }
6804: my $which=&get_rand_alg();
6805:
6806: if (defined(&getCODE())) {
6807: if ($which eq '64bit5') {
6808: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6809: } elsif ($which eq '64bit4') {
6810: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6811: } else {
6812: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6813: }
6814: } elsif ($which eq '64bit5') {
6815: return &rndseed_64bit5($symb,$courseid,$domain,$username);
6816: } elsif ($which eq '64bit4') {
6817: return &rndseed_64bit4($symb,$courseid,$domain,$username);
6818: } elsif ($which eq '64bit3') {
6819: return &rndseed_64bit3($symb,$courseid,$domain,$username);
6820: } elsif ($which eq '64bit2') {
6821: return &rndseed_64bit2($symb,$courseid,$domain,$username);
6822: } elsif ($which eq '64bit') {
6823: return &rndseed_64bit($symb,$courseid,$domain,$username);
6824: }
6825: return &rndseed_32bit($symb,$courseid,$domain,$username);
6826: }
6827:
6828: sub rndseed_32bit {
6829: my ($symb,$courseid,$domain,$username)=@_;
6830: {
6831: use integer;
6832: my $symbchck=unpack("%32C*",$symb) << 27;
6833: my $symbseed=numval($symb) << 22;
6834: my $namechck=unpack("%32C*",$username) << 17;
6835: my $nameseed=numval($username) << 12;
6836: my $domainseed=unpack("%32C*",$domain) << 7;
6837: my $courseseed=unpack("%32C*",$courseid);
6838: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6839: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6840: #&logthis("rndseed :$num:$symb");
6841: if ($_64bit) { $num=(($num<<32)>>32); }
6842: return $num;
6843: }
6844: }
6845:
6846: sub rndseed_64bit {
6847: my ($symb,$courseid,$domain,$username)=@_;
6848: {
6849: use integer;
6850: my $symbchck=unpack("%32S*",$symb) << 21;
6851: my $symbseed=numval($symb) << 10;
6852: my $namechck=unpack("%32S*",$username);
6853:
6854: my $nameseed=numval($username) << 21;
6855: my $domainseed=unpack("%32S*",$domain) << 10;
6856: my $courseseed=unpack("%32S*",$courseid);
6857:
6858: my $num1=$symbchck+$symbseed+$namechck;
6859: my $num2=$nameseed+$domainseed+$courseseed;
6860: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6861: #&logthis("rndseed :$num:$symb");
6862: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6863: return "$num1,$num2";
6864: }
6865: }
6866:
6867: sub rndseed_64bit2 {
6868: my ($symb,$courseid,$domain,$username)=@_;
6869: {
6870: use integer;
6871: # strings need to be an even # of cahracters long, it it is odd the
6872: # last characters gets thrown away
6873: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6874: my $symbseed=numval($symb) << 10;
6875: my $namechck=unpack("%32S*",$username.' ');
6876:
6877: my $nameseed=numval($username) << 21;
6878: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6879: my $courseseed=unpack("%32S*",$courseid.' ');
6880:
6881: my $num1=$symbchck+$symbseed+$namechck;
6882: my $num2=$nameseed+$domainseed+$courseseed;
6883: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6884: #&logthis("rndseed :$num:$symb");
6885: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6886: return "$num1,$num2";
6887: }
6888: }
6889:
6890: sub rndseed_64bit3 {
6891: my ($symb,$courseid,$domain,$username)=@_;
6892: {
6893: use integer;
6894: # strings need to be an even # of cahracters long, it it is odd the
6895: # last characters gets thrown away
6896: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6897: my $symbseed=numval2($symb) << 10;
6898: my $namechck=unpack("%32S*",$username.' ');
6899:
6900: my $nameseed=numval2($username) << 21;
6901: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6902: my $courseseed=unpack("%32S*",$courseid.' ');
6903:
6904: my $num1=$symbchck+$symbseed+$namechck;
6905: my $num2=$nameseed+$domainseed+$courseseed;
6906: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6907: #&logthis("rndseed :$num1:$num2:$_64bit");
6908: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6909:
6910: return "$num1:$num2";
6911: }
6912: }
6913:
6914: sub rndseed_64bit4 {
6915: my ($symb,$courseid,$domain,$username)=@_;
6916: {
6917: use integer;
6918: # strings need to be an even # of cahracters long, it it is odd the
6919: # last characters gets thrown away
6920: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6921: my $symbseed=numval3($symb) << 10;
6922: my $namechck=unpack("%32S*",$username.' ');
6923:
6924: my $nameseed=numval3($username) << 21;
6925: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6926: my $courseseed=unpack("%32S*",$courseid.' ');
6927:
6928: my $num1=$symbchck+$symbseed+$namechck;
6929: my $num2=$nameseed+$domainseed+$courseseed;
6930: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6931: #&logthis("rndseed :$num1:$num2:$_64bit");
6932: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6933:
6934: return "$num1:$num2";
6935: }
6936: }
6937:
6938: sub rndseed_64bit5 {
6939: my ($symb,$courseid,$domain,$username)=@_;
6940: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
6941: return "$num1:$num2";
6942: }
6943:
6944: sub rndseed_CODE_64bit {
6945: my ($symb,$courseid,$domain,$username)=@_;
6946: {
6947: use integer;
6948: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6949: my $symbseed=numval2($symb);
6950: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6951: my $CODEseed=numval(&getCODE());
6952: my $courseseed=unpack("%32S*",$courseid.' ');
6953: my $num1=$symbseed+$CODEchck;
6954: my $num2=$CODEseed+$courseseed+$symbchck;
6955: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6956: #&logthis("rndseed :$num1:$num2:$symb");
6957: if ($_64bit) { $num1=(($num1<<32)>>32); }
6958: if ($_64bit) { $num2=(($num2<<32)>>32); }
6959: return "$num1:$num2";
6960: }
6961: }
6962:
6963: sub rndseed_CODE_64bit4 {
6964: my ($symb,$courseid,$domain,$username)=@_;
6965: {
6966: use integer;
6967: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6968: my $symbseed=numval3($symb);
6969: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6970: my $CODEseed=numval3(&getCODE());
6971: my $courseseed=unpack("%32S*",$courseid.' ');
6972: my $num1=$symbseed+$CODEchck;
6973: my $num2=$CODEseed+$courseseed+$symbchck;
6974: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6975: #&logthis("rndseed :$num1:$num2:$symb");
6976: if ($_64bit) { $num1=(($num1<<32)>>32); }
6977: if ($_64bit) { $num2=(($num2<<32)>>32); }
6978: return "$num1:$num2";
6979: }
6980: }
6981:
6982: sub rndseed_CODE_64bit5 {
6983: my ($symb,$courseid,$domain,$username)=@_;
6984: my $code = &getCODE();
6985: my ($num1,$num2)=&digest("$symb,$courseid,$code");
6986: return "$num1:$num2";
6987: }
6988:
6989: sub setup_random_from_rndseed {
6990: my ($rndseed)=@_;
6991: if ($rndseed =~/([,:])/) {
6992: my ($num1,$num2)=split(/[,:]/,$rndseed);
6993: &Math::Random::random_set_seed(abs($num1),abs($num2));
6994: } else {
6995: &Math::Random::random_set_seed_from_phrase($rndseed);
6996: }
6997: }
6998:
6999: sub latest_receipt_algorithm_id {
7000: return 'receipt2';
7001: }
7002:
7003: sub recunique {
7004: my $fucourseid=shift;
7005: my $unique;
7006: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7007: $unique=$env{"course.$fucourseid.internal.encseed"};
7008: } else {
7009: $unique=$perlvar{'lonReceipt'};
7010: }
7011: return unpack("%32C*",$unique);
7012: }
7013:
7014: sub recprefix {
7015: my $fucourseid=shift;
7016: my $prefix;
7017: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7018: $prefix=$env{"course.$fucourseid.internal.encpref"};
7019: } else {
7020: $prefix=$perlvar{'lonHostID'};
7021: }
7022: return unpack("%32C*",$prefix);
7023: }
7024:
7025: sub ireceipt {
7026: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
7027: my $cuname=unpack("%32C*",$funame);
7028: my $cudom=unpack("%32C*",$fudom);
7029: my $cucourseid=unpack("%32C*",$fucourseid);
7030: my $cusymb=unpack("%32C*",$fusymb);
7031: my $cunique=&recunique($fucourseid);
7032: my $cpart=unpack("%32S*",$part);
7033: my $return =&recprefix($fucourseid).'-';
7034: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7035: $env{'request.state'} eq 'construct') {
7036: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
7037:
7038: $return.= ($cunique%$cuname+
7039: $cunique%$cudom+
7040: $cusymb%$cuname+
7041: $cusymb%$cudom+
7042: $cucourseid%$cuname+
7043: $cucourseid%$cudom+
7044: $cpart%$cuname+
7045: $cpart%$cudom);
7046: } else {
7047: $return.= ($cunique%$cuname+
7048: $cunique%$cudom+
7049: $cusymb%$cuname+
7050: $cusymb%$cudom+
7051: $cucourseid%$cuname+
7052: $cucourseid%$cudom);
7053: }
7054: return $return;
7055: }
7056:
7057: sub receipt {
7058: my ($part)=@_;
7059: my ($symb,$courseid,$domain,$name) = &whichuser();
7060: return &ireceipt($name,$domain,$courseid,$symb,$part);
7061: }
7062:
7063: sub whichuser {
7064: my ($passedsymb)=@_;
7065: my ($symb,$courseid,$domain,$name,$publicuser);
7066: if (defined($env{'form.grade_symb'})) {
7067: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7068: my $allowed=&allowed('vgr',$tmp_courseid);
7069: if (!$allowed &&
7070: exists($env{'request.course.sec'}) &&
7071: $env{'request.course.sec'} !~ /^\s*$/) {
7072: $allowed=&allowed('vgr',$tmp_courseid.
7073: '/'.$env{'request.course.sec'});
7074: }
7075: if ($allowed) {
7076: ($symb)=&get_env_multiple('form.grade_symb');
7077: $courseid=$tmp_courseid;
7078: ($domain)=&get_env_multiple('form.grade_domain');
7079: ($name)=&get_env_multiple('form.grade_username');
7080: return ($symb,$courseid,$domain,$name,$publicuser);
7081: }
7082: }
7083: if (!$passedsymb) {
7084: $symb=&symbread();
7085: } else {
7086: $symb=$passedsymb;
7087: }
7088: $courseid=$env{'request.course.id'};
7089: $domain=$env{'user.domain'};
7090: $name=$env{'user.name'};
7091: if ($name eq 'public' && $domain eq 'public') {
7092: if (!defined($env{'form.username'})) {
7093: $env{'form.username'}.=time.rand(10000000);
7094: }
7095: $name.=$env{'form.username'};
7096: }
7097: return ($symb,$courseid,$domain,$name,$publicuser);
7098:
7099: }
7100:
7101: # ------------------------------------------------------------ Serves up a file
7102: # returns either the contents of the file or
7103: # -1 if the file doesn't exist
7104: #
7105: # if the target is a file that was uploaded via DOCS,
7106: # a check will be made to see if a current copy exists on the local server,
7107: # if it does this will be served, otherwise a copy will be retrieved from
7108: # the home server for the course and stored in /home/httpd/html/userfiles on
7109: # the local server.
7110:
7111: sub getfile {
7112: my ($file) = @_;
7113: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7114: &repcopy($file);
7115: return &readfile($file);
7116: }
7117:
7118: sub repcopy_userfile {
7119: my ($file)=@_;
7120: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7121: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
7122: my ($cdom,$cnum,$filename) =
7123: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
7124: my ($info,$rtncode);
7125: my $uri="/uploaded/$cdom/$cnum/$filename";
7126: if (-e "$file") {
7127: my @fileinfo = stat($file);
7128: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
7129: if ($lwpresp ne 'ok') {
7130: if ($rtncode eq '404') {
7131: unlink($file);
7132: }
7133: #my $ua=new LWP::UserAgent;
7134: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
7135: #my $response=$ua->request($request);
7136: #if ($response->is_success()) {
7137: # return $response->content;
7138: # } else {
7139: # return -1;
7140: # }
7141: return -1;
7142: }
7143: if ($info < $fileinfo[9]) {
7144: return 'ok';
7145: }
7146: $info = '';
7147: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
7148: if ($lwpresp ne 'ok') {
7149: return -1;
7150: }
7151: } else {
7152: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
7153: if ($lwpresp ne 'ok') {
7154: my $ua=new LWP::UserAgent;
7155: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
7156: my $response=$ua->request($request);
7157: if ($response->is_success()) {
7158: $info=$response->content;
7159: } else {
7160: return -1;
7161: }
7162: }
7163: my @parts = ($cdom,$cnum);
7164: if ($filename =~ m|^(.+)/[^/]+$|) {
7165: push @parts, split(/\//,$1);
7166: }
7167: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7168: foreach my $part (@parts) {
7169: $path .= '/'.$part;
7170: if (!-e $path) {
7171: mkdir($path,0770);
7172: }
7173: }
7174: }
7175: open(FILE,">$file");
7176: print FILE $info;
7177: close(FILE);
7178: return 'ok';
7179: }
7180:
7181: sub tokenwrapper {
7182: my $uri=shift;
7183: $uri=~s|^http\://([^/]+)||;
7184: $uri=~s|^/||;
7185: $env{'user.environment'}=~/\/([^\/]+)\.id/;
7186: my $token=$1;
7187: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7188: if ($udom && $uname && $file) {
7189: $file=~s|(\?\.*)*$||;
7190: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
7191: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
7192: (($uri=~/\?/)?'&':'?').'token='.$token.
7193: '&tokenissued='.$perlvar{'lonHostID'};
7194: } else {
7195: return '/adm/notfound.html';
7196: }
7197: }
7198:
7199: sub getuploaded {
7200: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7201: $uri=~s/^\///;
7202: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
7203: my $ua=new LWP::UserAgent;
7204: my $request=new HTTP::Request($reqtype,$uri);
7205: my $response=$ua->request($request);
7206: $$rtncode = $response->code;
7207: if (! $response->is_success()) {
7208: return 'failed';
7209: }
7210: if ($reqtype eq 'HEAD') {
7211: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
7212: } elsif ($reqtype eq 'GET') {
7213: $$info = $response->content;
7214: }
7215: return 'ok';
7216: }
7217:
7218: sub readfile {
7219: my $file = shift;
7220: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7221: my $fh;
7222: open($fh,"<$file");
7223: my $a='';
7224: while (my $line = <$fh>) { $a .= $line; }
7225: return $a;
7226: }
7227:
7228: sub filelocation {
7229: my ($dir,$file) = @_;
7230: my $location;
7231: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
7232:
7233: if ($file =~ m-^/adm/-) {
7234: $file=~s-^/adm/wrapper/-/-;
7235: $file=~s-^/adm/coursedocs/showdoc/-/-;
7236: }
7237: if ($file=~m:^/~:) { # is a contruction space reference
7238: $location = $file;
7239: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
7240: } elsif ($file=~m{^/home/$match_username/public_html/}) {
7241: # is a correct contruction space reference
7242: $location = $file;
7243: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
7244: my ($udom,$uname,$filename)=
7245: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
7246: my $home=&homeserver($uname,$udom);
7247: my $is_me=0;
7248: my @ids=¤t_machine_ids();
7249: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7250: if ($is_me) {
7251: $location=&propath($udom,$uname).
7252: '/userfiles/'.$filename;
7253: } else {
7254: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7255: $udom.'/'.$uname.'/'.$filename;
7256: }
7257: } else {
7258: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7259: $file=~s:^/res/:/:;
7260: if ( !( $file =~ m:^/:) ) {
7261: $location = $dir. '/'.$file;
7262: } else {
7263: $location = '/home/httpd/html/res'.$file;
7264: }
7265: }
7266: $location=~s://+:/:g; # remove duplicate /
7267: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7268: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7269: return $location;
7270: }
7271:
7272: sub hreflocation {
7273: my ($dir,$file)=@_;
7274: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
7275: $file=filelocation($dir,$file);
7276: } elsif ($file=~m-^/adm/-) {
7277: $file=~s-^/adm/wrapper/-/-;
7278: $file=~s-^/adm/coursedocs/showdoc/-/-;
7279: }
7280: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7281: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7282: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7283: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
7284: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7285: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
7286: -/uploaded/$1/$2/-x;
7287: }
7288: return $file;
7289: }
7290:
7291: sub current_machine_domains {
7292: my $hostname=$hostname{$perlvar{'lonHostID'}};
7293: my @domains;
7294: while( my($id, $name) = each(%hostname)) {
7295: # &logthis("-$id-$name-$hostname-");
7296: if ($hostname eq $name) {
7297: push(@domains,$hostdom{$id});
7298: }
7299: }
7300: return @domains;
7301: }
7302:
7303: sub current_machine_ids {
7304: my $hostname=$hostname{$perlvar{'lonHostID'}};
7305: my @ids;
7306: while( my($id, $name) = each(%hostname)) {
7307: # &logthis("-$id-$name-$hostname-");
7308: if ($hostname eq $name) {
7309: push(@ids,$id);
7310: }
7311: }
7312: return @ids;
7313: }
7314:
7315: # ------------------------------------------------------------- Declutters URLs
7316:
7317: sub declutter {
7318: my $thisfn=shift;
7319: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7320: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7321: $thisfn=~s/^\///;
7322: $thisfn=~s|^adm/wrapper/||;
7323: $thisfn=~s|^adm/coursedocs/showdoc/||;
7324: $thisfn=~s/^res\///;
7325: $thisfn=~s/\?.+$//;
7326: return $thisfn;
7327: }
7328:
7329: # ------------------------------------------------------------- Clutter up URLs
7330:
7331: sub clutter {
7332: my $thisfn='/'.&declutter(shift);
7333: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
7334: $thisfn='/res'.$thisfn;
7335: }
7336: if ($thisfn !~m|/adm|) {
7337: if ($thisfn =~ m|/ext/|) {
7338: $thisfn='/adm/wrapper'.$thisfn;
7339: } else {
7340: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7341: my $embstyle=&Apache::loncommon::fileembstyle($ext);
7342: if ($embstyle eq 'ssi'
7343: || ($embstyle eq 'hdn')
7344: || ($embstyle eq 'rat')
7345: || ($embstyle eq 'prv')
7346: || ($embstyle eq 'ign')) {
7347: #do nothing with these
7348: } elsif (($embstyle eq 'img')
7349: || ($embstyle eq 'emb')
7350: || ($embstyle eq 'wrp')) {
7351: $thisfn='/adm/wrapper'.$thisfn;
7352: } elsif ($embstyle eq 'unk'
7353: && $thisfn!~/\.(sequence|page)$/) {
7354: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
7355: } else {
7356: # &logthis("Got a blank emb style");
7357: }
7358: }
7359: }
7360: return $thisfn;
7361: }
7362:
7363: sub clutter_with_no_wrapper {
7364: my $uri = &clutter(shift);
7365: if ($uri =~ m-^/adm/-) {
7366: $uri =~ s-^/adm/wrapper/-/-;
7367: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7368: }
7369: return $uri;
7370: }
7371:
7372: sub freeze_escape {
7373: my ($value)=@_;
7374: if (ref($value)) {
7375: $value=&nfreeze($value);
7376: return '__FROZEN__'.&escape($value);
7377: }
7378: return &escape($value);
7379: }
7380:
7381:
7382: sub thaw_unescape {
7383: my ($value)=@_;
7384: if ($value =~ /^__FROZEN__/) {
7385: substr($value,0,10,undef);
7386: $value=&unescape($value);
7387: return &thaw($value);
7388: }
7389: return &unescape($value);
7390: }
7391:
7392: sub correct_line_ends {
7393: my ($result)=@_;
7394: $$result =~s/\r\n/\n/mg;
7395: $$result =~s/\r/\n/mg;
7396: }
7397: # ================================================================ Main Program
7398:
7399: sub goodbye {
7400: &logthis("Starting Shut down");
7401: #not converted to using infrastruture and probably shouldn't be
7402: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
7403: #converted
7404: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7405: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7406: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7407: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
7408: #1.1 only
7409: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7410: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7411: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7412: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7413: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7414: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7415: &logthis(sprintf("%-20s is %s",'hits',$hits));
7416: &flushcourselogs();
7417: &logthis("Shutting down");
7418: }
7419:
7420: BEGIN {
7421: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7422: unless ($readit) {
7423: {
7424: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7425: %perlvar = (%perlvar,%{$configvars});
7426: }
7427:
7428: # ------------------------------------------------------------ Read domain file
7429: {
7430: %domaindescription = ();
7431: %domain_auth_def = ();
7432: %domain_auth_arg_def = ();
7433: my $fh;
7434: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
7435: while (my $line = <$fh>) {
7436: next if ($line =~ /^(\#|\s*$)/);
7437: # next if /^\#/;
7438: chomp $line;
7439: my ($domain, $domain_description, $def_auth, $def_auth_arg,
7440: $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
7441: $domain_auth_def{$domain}=$def_auth;
7442: $domain_auth_arg_def{$domain}=$def_auth_arg;
7443: $domaindescription{$domain}=$domain_description;
7444: $domain_lang_def{$domain}=$def_lang;
7445: $domain_city{$domain}=$city;
7446: $domain_longi{$domain}=$longi;
7447: $domain_lati{$domain}=$lati;
7448: $domain_primary{$domain}=$primary;
7449:
7450: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
7451: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
7452: }
7453: }
7454: close ($fh);
7455: }
7456:
7457:
7458: # ------------------------------------------------------------- Read hosts file
7459: {
7460: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7461:
7462: while (my $configline=<$config>) {
7463: next if ($configline =~ /^(\#|\s*$)/);
7464: chomp($configline);
7465: my ($id,$domain,$role,$name)=split(/:/,$configline);
7466: $name=~s/\s//g;
7467: if ($id && $domain && $role && $name) {
7468: $hostname{$id}=$name;
7469: $hostdom{$id}=$domain;
7470: if ($role eq 'library') { $libserv{$id}=$name; }
7471: }
7472: }
7473: close($config);
7474: # FIXME: dev server don't want this, production servers _do_ want this
7475: #&get_iphost();
7476: }
7477:
7478: sub get_iphost {
7479: if (%iphost) { return %iphost; }
7480: my %name_to_ip;
7481: foreach my $id (keys(%hostname)) {
7482: my $name=$hostname{$id};
7483: my $ip;
7484: if (!exists($name_to_ip{$name})) {
7485: $ip = gethostbyname($name);
7486: if (!$ip || length($ip) ne 4) {
7487: &logthis("Skipping host $id name $name no IP found\n");
7488: next;
7489: }
7490: $ip=inet_ntoa($ip);
7491: $name_to_ip{$name} = $ip;
7492: } else {
7493: $ip = $name_to_ip{$name};
7494: }
7495: push(@{$iphost{$ip}},$id);
7496: }
7497: return %iphost;
7498: }
7499:
7500: # ------------------------------------------------------ Read spare server file
7501: {
7502: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7503:
7504: while (my $configline=<$config>) {
7505: chomp($configline);
7506: if ($configline) {
7507: my ($host,$type) = split(':',$configline,2);
7508: if (!defined($type) || $type eq '') { $type = 'default' };
7509: push(@{ $spareid{$type} }, $host);
7510: }
7511: }
7512: close($config);
7513: }
7514: # ------------------------------------------------------------ Read permissions
7515: {
7516: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7517:
7518: while (my $configline=<$config>) {
7519: chomp($configline);
7520: if ($configline) {
7521: my ($role,$perm)=split(/ /,$configline);
7522: if ($perm ne '') { $pr{$role}=$perm; }
7523: }
7524: }
7525: close($config);
7526: }
7527:
7528: # -------------------------------------------- Read plain texts for permissions
7529: {
7530: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7531:
7532: while (my $configline=<$config>) {
7533: chomp($configline);
7534: if ($configline) {
7535: my ($short,@plain)=split(/:/,$configline);
7536: %{$prp{$short}} = ();
7537: if (@plain > 0) {
7538: $prp{$short}{'std'} = $plain[0];
7539: for (my $i=1; $i<@plain; $i++) {
7540: $prp{$short}{'alt'.$i} = $plain[$i];
7541: }
7542: }
7543: }
7544: }
7545: close($config);
7546: }
7547:
7548: # ---------------------------------------------------------- Read package table
7549: {
7550: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7551:
7552: while (my $configline=<$config>) {
7553: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
7554: chomp($configline);
7555: my ($short,$plain)=split(/:/,$configline);
7556: my ($pack,$name)=split(/\&/,$short);
7557: if ($plain ne '') {
7558: $packagetab{$pack.'&'.$name.'&name'}=$name;
7559: $packagetab{$short}=$plain;
7560: }
7561: }
7562: close($config);
7563: }
7564:
7565: # ------------- set up temporary directory
7566: {
7567: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7568:
7569: }
7570:
7571: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7572: 'compress_threshold'=> 20_000,
7573: });
7574:
7575: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7576: $dumpcount=0;
7577:
7578: &logtouch();
7579: &logthis('<font color="yellow">INFO: Read configuration</font>');
7580: $readit=1;
7581: {
7582: use integer;
7583: my $test=(2**32)+1;
7584: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
7585: &logthis(" Detected 64bit platform ($_64bit)");
7586: }
7587: }
7588: }
7589:
7590: 1;
7591: __END__
7592:
7593: =pod
7594:
7595: =head1 NAME
7596:
7597: Apache::lonnet - Subroutines to ask questions about things in the network.
7598:
7599: =head1 SYNOPSIS
7600:
7601: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
7602:
7603: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7604:
7605: Common parameters:
7606:
7607: =over 4
7608:
7609: =item *
7610:
7611: $uname : an internal username (if $cname expecting a course Id specifically)
7612:
7613: =item *
7614:
7615: $udom : a domain (if $cdom expecting a course's domain specifically)
7616:
7617: =item *
7618:
7619: $symb : a resource instance identifier
7620:
7621: =item *
7622:
7623: $namespace : the name of a .db file that contains the data needed or
7624: being set.
7625:
7626: =back
7627:
7628: =head1 OVERVIEW
7629:
7630: lonnet provides subroutines which interact with the
7631: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7632: about classes, users, and resources.
7633:
7634: For many of these objects you can also use this to store data about
7635: them or modify them in various ways.
7636:
7637: =head2 Symbs
7638:
7639: To identify a specific instance of a resource, LON-CAPA uses symbols
7640: or "symbs"X<symb>. These identifiers are built from the URL of the
7641: map, the resource number of the resource in the map, and the URL of
7642: the resource itself. The latter is somewhat redundant, but might help
7643: if maps change.
7644:
7645: An example is
7646:
7647: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7648:
7649: The respective map entry is
7650:
7651: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7652: title="Problem 2">
7653: </resource>
7654:
7655: Symbs are used by the random number generator, as well as to store and
7656: restore data specific to a certain instance of for example a problem.
7657:
7658: =head2 Storing And Retrieving Data
7659:
7660: X<store()>X<cstore()>X<restore()>Three of the most important functions
7661: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7662: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7663: is is the non-critical message twin of cstore. These functions are for
7664: handlers to store a perl hash to a user's permanent data space in an
7665: easy manner, and to retrieve it again on another call. It is expected
7666: that a handler would use this once at the beginning to retrieve data,
7667: and then again once at the end to send only the new data back.
7668:
7669: The data is stored in the user's data directory on the user's
7670: homeserver under the ID of the course.
7671:
7672: The hash that is returned by restore will have all of the previous
7673: value for all of the elements of the hash.
7674:
7675: Example:
7676:
7677: #creating a hash
7678: my %hash;
7679: $hash{'foo'}='bar';
7680:
7681: #storing it
7682: &Apache::lonnet::cstore(\%hash);
7683:
7684: #changing a value
7685: $hash{'foo'}='notbar';
7686:
7687: #adding a new value
7688: $hash{'bar'}='foo';
7689: &Apache::lonnet::cstore(\%hash);
7690:
7691: #retrieving the hash
7692: my %history=&Apache::lonnet::restore();
7693:
7694: #print the hash
7695: foreach my $key (sort(keys(%history))) {
7696: print("\%history{$key} = $history{$key}");
7697: }
7698:
7699: Will print out:
7700:
7701: %history{1:foo} = bar
7702: %history{1:keys} = foo:timestamp
7703: %history{1:timestamp} = 990455579
7704: %history{2:bar} = foo
7705: %history{2:foo} = notbar
7706: %history{2:keys} = foo:bar:timestamp
7707: %history{2:timestamp} = 990455580
7708: %history{bar} = foo
7709: %history{foo} = notbar
7710: %history{timestamp} = 990455580
7711: %history{version} = 2
7712:
7713: Note that the special hash entries C<keys>, C<version> and
7714: C<timestamp> were added to the hash. C<version> will be equal to the
7715: total number of versions of the data that have been stored. The
7716: C<timestamp> attribute will be the UNIX time the hash was
7717: stored. C<keys> is available in every historical section to list which
7718: keys were added or changed at a specific historical revision of a
7719: hash.
7720:
7721: B<Warning>: do not store the hash that restore returns directly. This
7722: will cause a mess since it will restore the historical keys as if the
7723: were new keys. I.E. 1:foo will become 1:1:foo etc.
7724:
7725: Calling convention:
7726:
7727: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
7728: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
7729:
7730: For more detailed information, see lonnet specific documentation.
7731:
7732: =head1 RETURN MESSAGES
7733:
7734: =over 4
7735:
7736: =item * B<con_lost>: unable to contact remote host
7737:
7738: =item * B<con_delayed>: unable to contact remote host, message will be delivered
7739: when the connection is brought back up
7740:
7741: =item * B<con_failed>: unable to contact remote host and unable to save message
7742: for later delivery
7743:
7744: =item * B<error:>: an error a occured, a description of the error follows the :
7745:
7746: =item * B<no_such_host>: unable to fund a host associated with the user/domain
7747: that was requested
7748:
7749: =back
7750:
7751: =head1 PUBLIC SUBROUTINES
7752:
7753: =head2 Session Environment Functions
7754:
7755: =over 4
7756:
7757: =item *
7758: X<appenv()>
7759: B<appenv(%hash)>: the value of %hash is written to
7760: the user envirnoment file, and will be restored for each access this
7761: user makes during this session, also modifies the %env for the current
7762: process
7763:
7764: =item *
7765: X<delenv()>
7766: B<delenv($regexp)>: removes all items from the session
7767: environment file that matches the regular expression in $regexp. The
7768: values are also delted from the current processes %env.
7769:
7770: =item * get_env_multiple($name)
7771:
7772: gets $name from the %env hash, it seemlessly handles the cases where multiple
7773: values may be defined and end up as an array ref.
7774:
7775: returns an array of values
7776:
7777: =back
7778:
7779: =head2 User Information
7780:
7781: =over 4
7782:
7783: =item *
7784: X<queryauthenticate()>
7785: B<queryauthenticate($uname,$udom)>: try to determine user's current
7786: authentication scheme
7787:
7788: =item *
7789: X<authenticate()>
7790: B<authenticate($uname,$upass,$udom)>: try to
7791: authenticate user from domain's lib servers (first use the current
7792: one). C<$upass> should be the users password.
7793:
7794: =item *
7795: X<homeserver()>
7796: B<homeserver($uname,$udom)>: find the server which has
7797: the user's directory and files (there must be only one), this caches
7798: the answer, and also caches if there is a borken connection.
7799:
7800: =item *
7801: X<idget()>
7802: B<idget($udom,@ids)>: find the usernames behind a list of IDs
7803: (IDs are a unique resource in a domain, there must be only 1 ID per
7804: username, and only 1 username per ID in a specific domain) (returns
7805: hash: id=>name,id=>name)
7806:
7807: =item *
7808: X<idrget()>
7809: B<idrget($udom,@unames)>: find the IDs behind a list of
7810: usernames (returns hash: name=>id,name=>id)
7811:
7812: =item *
7813: X<idput()>
7814: B<idput($udom,%ids)>: store away a list of names and associated IDs
7815:
7816: =item *
7817: X<rolesinit()>
7818: B<rolesinit($udom,$username,$authhost)>: get user privileges
7819:
7820: =item *
7821: X<getsection()>
7822: B<getsection($udom,$uname,$cname)>: finds the section of student in the
7823: course $cname, return section name/number or '' for "not in course"
7824: and '-1' for "no section"
7825:
7826: =item *
7827: X<userenvironment()>
7828: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
7829: passed in @what from the requested user's environment, returns a hash
7830:
7831: =back
7832:
7833: =head2 User Roles
7834:
7835: =over 4
7836:
7837: =item *
7838:
7839: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
7840: F: full access
7841: U,I,K: authentication modes (cxx only)
7842: '': forbidden
7843: 1: user needs to choose course
7844: 2: browse allowed
7845: A: passphrase authentication needed
7846:
7847: =item *
7848:
7849: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
7850: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
7851: and course level
7852:
7853: =item *
7854:
7855: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
7856: explanation of a user role term
7857:
7858: =back
7859:
7860: =head2 User Modification
7861:
7862: =over 4
7863:
7864: =item *
7865:
7866: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
7867: user for the level given by URL. Optional start and end dates (leave empty
7868: string or zero for "no date")
7869:
7870: =item *
7871:
7872: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
7873: change a users, password, possible return values are: ok,
7874: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
7875: refused
7876:
7877: =item *
7878:
7879: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
7880:
7881: =item *
7882:
7883: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
7884: modify user
7885:
7886: =item *
7887:
7888: modifystudent
7889:
7890: modify a students enrollment and identification information.
7891: The course id is resolved based on the current users environment.
7892: This means the envoking user must be a course coordinator or otherwise
7893: associated with a course.
7894:
7895: This call is essentially a wrapper for lonnet::modifyuser and
7896: lonnet::modify_student_enrollment
7897:
7898: Inputs:
7899:
7900: =over 4
7901:
7902: =item B<$udom> Students loncapa domain
7903:
7904: =item B<$uname> Students loncapa login name
7905:
7906: =item B<$uid> Students id/student number
7907:
7908: =item B<$umode> Students authentication mode
7909:
7910: =item B<$upass> Students password
7911:
7912: =item B<$first> Students first name
7913:
7914: =item B<$middle> Students middle name
7915:
7916: =item B<$last> Students last name
7917:
7918: =item B<$gene> Students generation
7919:
7920: =item B<$usec> Students section in course
7921:
7922: =item B<$end> Unix time of the roles expiration
7923:
7924: =item B<$start> Unix time of the roles start date
7925:
7926: =item B<$forceid> If defined, allow $uid to be changed
7927:
7928: =item B<$desiredhome> server to use as home server for student
7929:
7930: =back
7931:
7932: =item *
7933:
7934: modify_student_enrollment
7935:
7936: Change a students enrollment status in a class. The environment variable
7937: 'role.request.course' must be defined for this function to proceed.
7938:
7939: Inputs:
7940:
7941: =over 4
7942:
7943: =item $udom, students domain
7944:
7945: =item $uname, students name
7946:
7947: =item $uid, students user id
7948:
7949: =item $first, students first name
7950:
7951: =item $middle
7952:
7953: =item $last
7954:
7955: =item $gene
7956:
7957: =item $usec
7958:
7959: =item $end
7960:
7961: =item $start
7962:
7963: =back
7964:
7965:
7966: =item *
7967:
7968: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
7969: custom role; give a custom role to a user for the level given by URL. Specify
7970: name and domain of role author, and role name
7971:
7972: =item *
7973:
7974: revokerole($udom,$uname,$url,$role) : revoke a role for url
7975:
7976: =item *
7977:
7978: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
7979:
7980: =back
7981:
7982: =head2 Course Infomation
7983:
7984: =over 4
7985:
7986: =item *
7987:
7988: coursedescription($courseid) : returns a hash of information about the
7989: specified course id, including all environment settings for the
7990: course, the description of the course will be in the hash under the
7991: key 'description'
7992:
7993: =item *
7994:
7995: resdata($name,$domain,$type,@which) : request for current parameter
7996: setting for a specific $type, where $type is either 'course' or 'user',
7997: @what should be a list of parameters to ask about. This routine caches
7998: answers for 5 minutes.
7999:
8000: =back
8001:
8002: =head2 Course Modification
8003:
8004: =over 4
8005:
8006: =item *
8007:
8008: writecoursepref($courseid,%prefs) : write preferences (environment
8009: database) for a course
8010:
8011: =item *
8012:
8013: createcourse($udom,$description,$url) : make/modify course
8014:
8015: =back
8016:
8017: =head2 Resource Subroutines
8018:
8019: =over 4
8020:
8021: =item *
8022:
8023: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
8024:
8025: =item *
8026:
8027: repcopy($filename) : subscribes to the requested file, and attempts to
8028: replicate from the owning library server, Might return
8029: 'unavailable', 'not_found', 'forbidden', 'ok', or
8030: 'bad_request', also attempts to grab the metadata for the
8031: resource. Expects the local filesystem pathname
8032: (/home/httpd/html/res/....)
8033:
8034: =back
8035:
8036: =head2 Resource Information
8037:
8038: =over 4
8039:
8040: =item *
8041:
8042: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8043: a vairety of different possible values, $varname should be a request
8044: string, and the other parameters can be used to specify who and what
8045: one is asking about.
8046:
8047: Possible values for $varname are environment.lastname (or other item
8048: from the envirnment hash), user.name (or someother aspect about the
8049: user), resource.0.maxtries (or some other part and parameter of a
8050: resource)
8051:
8052: =item *
8053:
8054: directcondval($number) : get current value of a condition; reads from a state
8055: string
8056:
8057: =item *
8058:
8059: condval($condidx) : value of condition index based on state
8060:
8061: =item *
8062:
8063: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8064: resource's metadata, $what should be either a specific key, or either
8065: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8066: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8067:
8068: this function automatically caches all requests
8069:
8070: =item *
8071:
8072: metadata_query($query,$custom,$customshow) : make a metadata query against the
8073: network of library servers; returns file handle of where SQL and regex results
8074: will be stored for query
8075:
8076: =item *
8077:
8078: symbread($filename) : return symbolic list entry (filename argument optional);
8079: returns the data handle
8080:
8081: =item *
8082:
8083: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
8084: a possible symb for the URL in $thisfn, and if is an encryypted
8085: resource that the user accessed using /enc/ returns a 1 on success, 0
8086: on failure, user must be in a course, as it assumes the existance of
8087: the course initial hash, and uses $env('request.course.id'}
8088:
8089:
8090: =item *
8091:
8092: symbclean($symb) : removes versions numbers from a symb, returns the
8093: cleaned symb
8094:
8095: =item *
8096:
8097: is_on_map($uri) : checks if the $uri is somewhere on the current
8098: course map, user must be in a course for it to work.
8099:
8100: =item *
8101:
8102: numval($salt) : return random seed value (addend for rndseed)
8103:
8104: =item *
8105:
8106: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8107: a random seed, all arguments are optional, if they aren't sent it uses the
8108: environment to derive them. Note: if symb isn't sent and it can't get one
8109: from &symbread it will use the current time as its return value
8110:
8111: =item *
8112:
8113: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8114: unfakeable, receipt
8115:
8116: =item *
8117:
8118: receipt() : API to ireceipt working off of env values; given out to users
8119:
8120: =item *
8121:
8122: countacc($url) : count the number of accesses to a given URL
8123:
8124: =item *
8125:
8126: 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
8127:
8128: =item *
8129:
8130: 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)
8131:
8132: =item *
8133:
8134: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
8135:
8136: =item *
8137:
8138: devalidate($symb) : devalidate temporary spreadsheet calculations,
8139: forcing spreadsheet to reevaluate the resource scores next time.
8140:
8141: =back
8142:
8143: =head2 Storing/Retreiving Data
8144:
8145: =over 4
8146:
8147: =item *
8148:
8149: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8150: for this url; hashref needs to be given and should be a \%hashname; the
8151: remaining args aren't required and if they aren't passed or are '' they will
8152: be derived from the env
8153:
8154: =item *
8155:
8156: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8157: uses critical subroutine
8158:
8159: =item *
8160:
8161: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8162: all args are optional
8163:
8164: =item *
8165:
8166: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8167: dumps the complete (or key matching regexp) namespace into a hash
8168: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8169: normally &store()ed into
8170:
8171: $range should be either an integer '100' (give me the first 100
8172: matching records)
8173: or be two integers sperated by a - with no spaces
8174: '30-50' (give me the 30th through the 50th matching
8175: records)
8176:
8177:
8178: =item *
8179:
8180: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8181: replaces a &store() version of data with a replacement set of data
8182: for a particular resource in a namespace passed in the $storehash hash
8183: reference
8184:
8185: =item *
8186:
8187: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8188: works very similar to store/cstore, but all data is stored in a
8189: temporary location and can be reset using tmpreset, $storehash should
8190: be a hash reference, returns nothing on success
8191:
8192: =item *
8193:
8194: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8195: similar to restore, but all data is stored in a temporary location and
8196: can be reset using tmpreset. Returns a hash of values on success,
8197: error string otherwise.
8198:
8199: =item *
8200:
8201: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8202: deltes all keys for $symb form the temporary storage hash.
8203:
8204: =item *
8205:
8206: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8207: reference filled in from namesp ($udom and $uname are optional)
8208:
8209: =item *
8210:
8211: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8212: namesp ($udom and $uname are optional)
8213:
8214: =item *
8215:
8216: dump($namespace,$udom,$uname,$regexp,$range) :
8217: dumps the complete (or key matching regexp) namespace into a hash
8218: ($udom, $uname, $regexp, $range are optional)
8219:
8220: $range should be either an integer '100' (give me the first 100
8221: matching records)
8222: or be two integers sperated by a - with no spaces
8223: '30-50' (give me the 30th through the 50th matching
8224: records)
8225: =item *
8226:
8227: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8228: $store can be a scalar, an array reference, or if the amount to be
8229: incremented is > 1, a hash reference.
8230:
8231: ($udom and $uname are optional)
8232:
8233: =item *
8234:
8235: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8236: ($udom and $uname are optional)
8237:
8238: =item *
8239:
8240: cput($namespace,$storehash,$udom,$uname) : critical put
8241: ($udom and $uname are optional)
8242:
8243: =item *
8244:
8245: newput($namespace,$storehash,$udom,$uname) :
8246:
8247: Attempts to store the items in the $storehash, but only if they don't
8248: currently exist, if this succeeds you can be certain that you have
8249: successfully created a new key value pair in the $namespace db.
8250:
8251:
8252: Args:
8253: $namespace: name of database to store values to
8254: $storehash: hashref to store to the db
8255: $udom: (optional) domain of user containing the db
8256: $uname: (optional) name of user caontaining the db
8257:
8258: Returns:
8259: 'ok' -> succeeded in storing all keys of $storehash
8260: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8261: least <key> already existed in the db (other
8262: requested keys may also already exist)
8263: 'error: <msg>' -> unable to tie the DB or other erorr occured
8264: 'con_lost' -> unable to contact request server
8265: 'refused' -> action was not allowed by remote machine
8266:
8267:
8268: =item *
8269:
8270: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8271: reference filled in from namesp (encrypts the return communication)
8272: ($udom and $uname are optional)
8273:
8274: =item *
8275:
8276: log($udom,$name,$home,$message) : write to permanent log for user; use
8277: critical subroutine
8278:
8279: =item *
8280:
8281: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
8282: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
8283:
8284: =item *
8285:
8286: put_dom($namespace,$storehash,$udomain) : stores hash in namespace at domain level on primary domain server ($udomain is optional)
8287:
8288: =back
8289:
8290: =head2 Network Status Functions
8291:
8292: =over 4
8293:
8294: =item *
8295:
8296: dirlist($uri) : return directory list based on URI
8297:
8298: =item *
8299:
8300: spareserver() : find server with least workload from spare.tab
8301:
8302: =back
8303:
8304: =head2 Apache Request
8305:
8306: =over 4
8307:
8308: =item *
8309:
8310: ssi($url,%hash) : server side include, does a complete request cycle on url to
8311: localhost, posts hash
8312:
8313: =back
8314:
8315: =head2 Data to String to Data
8316:
8317: =over 4
8318:
8319: =item *
8320:
8321: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8322: and '&' separators, supports elements that are arrayrefs and hashrefs
8323:
8324: =item *
8325:
8326: hashref2str($hashref) : convert a hashref into a string complete with
8327: escaping and '=' and '&' separators, supports elements that are
8328: arrayrefs and hashrefs
8329:
8330: =item *
8331:
8332: arrayref2str($arrayref) : convert an arrayref into a string complete
8333: with escaping and '&' separators, supports elements that are arrayrefs
8334: and hashrefs
8335:
8336: =item *
8337:
8338: str2hash($string) : convert string to hash using unescaping and
8339: splitting on '=' and '&', supports elements that are arrayrefs and
8340: hashrefs
8341:
8342: =item *
8343:
8344: str2array($string) : convert string to hash using unescaping and
8345: splitting on '&', supports elements that are arrayrefs and hashrefs
8346:
8347: =back
8348:
8349: =head2 Logging Routines
8350:
8351: =over 4
8352:
8353: These routines allow one to make log messages in the lonnet.log and
8354: lonnet.perm logfiles.
8355:
8356: =item *
8357:
8358: logtouch() : make sure the logfile, lonnet.log, exists
8359:
8360: =item *
8361:
8362: logthis() : append message to the normal lonnet.log file, it gets
8363: preiodically rolled over and deleted.
8364:
8365: =item *
8366:
8367: logperm() : append a permanent message to lonnet.perm.log, this log
8368: file never gets deleted by any automated portion of the system, only
8369: messages of critical importance should go in here.
8370:
8371: =back
8372:
8373: =head2 General File Helper Routines
8374:
8375: =over 4
8376:
8377: =item *
8378:
8379: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8380: (a) files in /uploaded
8381: (i) If a local copy of the file exists -
8382: compares modification date of local copy with last-modified date for
8383: definitive version stored on home server for course. If local copy is
8384: stale, requests a new version from the home server and stores it.
8385: If the original has been removed from the home server, then local copy
8386: is unlinked.
8387: (ii) If local copy does not exist -
8388: requests the file from the home server and stores it.
8389:
8390: If $caller is 'uploadrep':
8391: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8392: for request for files originally uploaded via DOCS.
8393: - returns 'ok' if fresh local copy now available, -1 otherwise.
8394:
8395: Otherwise:
8396: This indicates a call from the content generation phase of the request.
8397: - returns the entire contents of the file or -1.
8398:
8399: (b) files in /res
8400: - returns the entire contents of a file or -1;
8401: it properly subscribes to and replicates the file if neccessary.
8402:
8403:
8404: =item *
8405:
8406: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8407: reference
8408:
8409: returns either a stat() list of data about the file or an empty list
8410: if the file doesn't exist or couldn't find out about it (connection
8411: problems or user unknown)
8412:
8413: =item *
8414:
8415: filelocation($dir,$file) : returns file system location of a file
8416: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8417: directory that relative $file lookups are to looked in ($dir of /a/dir
8418: and a file of ../bob will become /a/bob)
8419:
8420: =item *
8421:
8422: hreflocation($dir,$file) : returns file system location or a URL; same as
8423: filelocation except for hrefs
8424:
8425: =item *
8426:
8427: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8428:
8429: =back
8430:
8431: =head2 Usererfile file routines (/uploaded*)
8432:
8433: =over 4
8434:
8435: =item *
8436:
8437: userfileupload(): main rotine for putting a file in a user or course's
8438: filespace, arguments are,
8439:
8440: formname - required - this is the name of the element in $env where the
8441: filename, and the contents of the file to create/modifed exist
8442: the filename is in $env{'form.'.$formname.'.filename'} and the
8443: contents of the file is located in $env{'form.'.$formname}
8444: coursedoc - if true, store the file in the course of the active role
8445: of the current user
8446: subdir - required - subdirectory to put the file in under ../userfiles/
8447: if undefined, it will be placed in "unknown"
8448:
8449: (This routine calls clean_filename() to remove any dangerous
8450: characters from the filename, and then calls finuserfileupload() to
8451: complete the transaction)
8452:
8453: returns either the url of the uploaded file (/uploaded/....) if successful
8454: and /adm/notfound.html if unsuccessful
8455:
8456: =item *
8457:
8458: clean_filename(): routine for cleaing a filename up for storage in
8459: userfile space, argument is:
8460:
8461: filename - proposed filename
8462:
8463: returns: the new clean filename
8464:
8465: =item *
8466:
8467: finishuserfileupload(): routine that creaes and sends the file to
8468: userspace, probably shouldn't be called directly
8469:
8470: docuname: username or courseid of destination for the file
8471: docudom: domain of user/course of destination for the file
8472: formname: same as for userfileupload()
8473: fname: filename (inculding subdirectories) for the file
8474:
8475: returns either the url of the uploaded file (/uploaded/....) if successful
8476: and /adm/notfound.html if unsuccessful
8477:
8478: =item *
8479:
8480: renameuserfile(): renames an existing userfile to a new name
8481:
8482: Args:
8483: docuname: username or courseid of destination for the file
8484: docudom: domain of user/course of destination for the file
8485: old: current file name (including any subdirs under userfiles)
8486: new: desired file name (including any subdirs under userfiles)
8487:
8488: =item *
8489:
8490: mkdiruserfile(): creates a directory is a userfiles dir
8491:
8492: Args:
8493: docuname: username or courseid of destination for the file
8494: docudom: domain of user/course of destination for the file
8495: dir: dir to create (including any subdirs under userfiles)
8496:
8497: =item *
8498:
8499: removeuserfile(): removes a file that exists in userfiles
8500:
8501: Args:
8502: docuname: username or courseid of destination for the file
8503: docudom: domain of user/course of destination for the file
8504: fname: filname to delete (including any subdirs under userfiles)
8505:
8506: =item *
8507:
8508: removeuploadedurl(): convience function for removeuserfile()
8509:
8510: Args:
8511: url: a full /uploaded/... url to delete
8512:
8513: =item *
8514:
8515: get_portfile_permissions():
8516: Args:
8517: domain: domain of user or course contain the portfolio files
8518: user: name of user or num of course contain the portfolio files
8519: Returns:
8520: hashref of a dump of the proper file_permissions.db
8521:
8522:
8523: =item *
8524:
8525: get_access_controls():
8526:
8527: Args:
8528: current_permissions: the hash ref returned from get_portfile_permissions()
8529: group: (optional) the group you want the files associated with
8530: file: (optional) the file you want access info on
8531:
8532: Returns:
8533: a hash (keys are file names) of hashes containing
8534: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8535: values are XML containing access control settings (see below)
8536:
8537: Internal notes:
8538:
8539: access controls are stored in file_permissions.db as key=value pairs.
8540: key -> path to file/file_name\0uniqueID:scope_end_start
8541: where scope -> public,guest,course,group,domains or users.
8542: end -> UNIX time for end of access (0 -> no end date)
8543: start -> UNIX time for start of access
8544:
8545: value -> XML description of access control
8546: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8547: <start></start>
8548: <end></end>
8549:
8550: <password></password> for scope type = guest
8551:
8552: <domain></domain> for scope type = course or group
8553: <number></number>
8554: <roles id="">
8555: <role></role>
8556: <access></access>
8557: <section></section>
8558: <group></group>
8559: </roles>
8560:
8561: <dom></dom> for scope type = domains
8562:
8563: <users> for scope type = users
8564: <user>
8565: <uname></uname>
8566: <udom></udom>
8567: </user>
8568: </users>
8569: </scope>
8570:
8571: Access data is also aggregated for each file in an additional key=value pair:
8572: key -> path to file/file_name\0accesscontrol
8573: value -> reference to hash
8574: hash contains key = value pairs
8575: where key = uniqueID:scope_end_start
8576: value = UNIX time record was last updated
8577:
8578: Used to improve speed of look-ups of access controls for each file.
8579:
8580: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8581:
8582: modify_access_controls():
8583:
8584: Modifies access controls for a portfolio file
8585: Args
8586: 1. file name
8587: 2. reference to hash of required changes,
8588: 3. domain
8589: 4. username
8590: where domain,username are the domain of the portfolio owner
8591: (either a user or a course)
8592:
8593: Returns:
8594: 1. result of additions or updates ('ok' or 'error', with error message).
8595: 2. result of deletions ('ok' or 'error', with error message).
8596: 3. reference to hash of any new or updated access controls.
8597: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8598: key = integer (inbound ID)
8599: value = uniqueID
8600:
8601: =back
8602:
8603: =head2 HTTP Helper Routines
8604:
8605: =over 4
8606:
8607: =item *
8608:
8609: escape() : unpack non-word characters into CGI-compatible hex codes
8610:
8611: =item *
8612:
8613: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8614:
8615: =back
8616:
8617: =head1 PRIVATE SUBROUTINES
8618:
8619: =head2 Underlying communication routines (Shouldn't call)
8620:
8621: =over 4
8622:
8623: =item *
8624:
8625: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8626:
8627: =item *
8628:
8629: reply() : uses subreply to send a message to remote machine, logs all failures
8630:
8631: =item *
8632:
8633: critical() : passes a critical message to another server; if cannot
8634: get through then place message in connection buffer directory and
8635: returns con_delayed, if incapable of saving message, returns
8636: con_failed
8637:
8638: =item *
8639:
8640: reconlonc() : tries to reconnect lonc client processes.
8641:
8642: =back
8643:
8644: =head2 Resource Access Logging
8645:
8646: =over 4
8647:
8648: =item *
8649:
8650: flushcourselogs() : flush (save) buffer logs and access logs
8651:
8652: =item *
8653:
8654: courselog($what) : save message for course in hash
8655:
8656: =item *
8657:
8658: courseacclog($what) : save message for course using &courselog(). Perform
8659: special processing for specific resource types (problems, exams, quizzes, etc).
8660:
8661: =item *
8662:
8663: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8664: as a PerlChildExitHandler
8665:
8666: =back
8667:
8668: =head2 Other
8669:
8670: =over 4
8671:
8672: =item *
8673:
8674: symblist($mapname,%newhash) : update symbolic storage links
8675:
8676: =back
8677:
8678: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>