1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.854 2007/03/28 21:44:13 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 %badServerCache %spareid
39: %pr %prp $memcache %packagetab
40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
42: $tmpdir $_64bit %env);
43:
44: use IO::Socket;
45: use GDBM_File;
46: use HTML::LCParser;
47: use HTML::Parser;
48: use Fcntl qw(:flock);
49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
50: use Time::HiRes qw( gettimeofday tv_interval );
51: use Cache::Memcached;
52: use Digest::MD5;
53: use Math::Random;
54: use LONCAPA qw(:DEFAULT :match);
55: use LONCAPA::Configuration;
56: use Apache::lonhosts;
57:
58: my $readit;
59: my $max_connection_retries = 10; # Or some such value.
60:
61: require Exporter;
62:
63: our @ISA = qw (Exporter);
64: our @EXPORT = qw(%env);
65:
66: =pod
67:
68: =head1 Package Variables
69:
70: These are largely undocumented, so if you decipher one please note it here.
71:
72: =over 4
73:
74: =item $processmarker
75:
76: Contains the time this process was started and this servers host id.
77:
78: =item $dumpcount
79:
80: Counts the number of times a message log flush has been attempted (regardless
81: of success) by this process. Used as part of the filename when messages are
82: delayed.
83:
84: =back
85:
86: =cut
87:
88:
89: # --------------------------------------------------------------------- Logging
90: {
91: my $logid;
92: sub instructor_log {
93: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
94: $logid++;
95: my $id=time().'00000'.$$.'00000'.$logid;
96: return &Apache::lonnet::put('nohist_'.$hash_name,
97: { $id => {
98: 'exe_uname' => $env{'user.name'},
99: 'exe_udom' => $env{'user.domain'},
100: 'exe_time' => time(),
101: 'exe_ip' => $ENV{'REMOTE_ADDR'},
102: 'delflag' => $delflag,
103: 'logentry' => $storehash,
104: 'uname' => $uname,
105: 'udom' => $udom,
106: }
107: },
108: $env{'course.'.$env{'request.course.id'}.'.domain'},
109: $env{'course.'.$env{'request.course.id'}.'.num'}
110: );
111: }
112: }
113:
114: sub logtouch {
115: my $execdir=$perlvar{'lonDaemons'};
116: unless (-e "$execdir/logs/lonnet.log") {
117: open(my $fh,">>$execdir/logs/lonnet.log");
118: close $fh;
119: }
120: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
121: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
122: }
123:
124: sub logthis {
125: my $message=shift;
126: my $execdir=$perlvar{'lonDaemons'};
127: my $now=time;
128: my $local=localtime($now);
129: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
130: print $fh "$local ($$): $message\n";
131: close($fh);
132: }
133: return 1;
134: }
135:
136: sub logperm {
137: my $message=shift;
138: my $execdir=$perlvar{'lonDaemons'};
139: my $now=time;
140: my $local=localtime($now);
141: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
142: print $fh "$now:$message:$local\n";
143: close($fh);
144: }
145: return 1;
146: }
147:
148: sub create_connection {
149: my ($hostname,$lonid) = @_;
150: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
151: Type => SOCK_STREAM,
152: Timeout => 10);
153: return 0 if (!$client);
154: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
155: my $result = <$client>;
156: chomp($result);
157: return 1 if ($result eq 'done');
158: return 0;
159: }
160:
161:
162: # -------------------------------------------------- Non-critical communication
163: sub subreply {
164: my ($cmd,$server)=@_;
165: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
166: #
167: # With loncnew process trimming, there's a timing hole between lonc server
168: # process exit and the master server picking up the listen on the AF_UNIX
169: # socket. In that time interval, a lock file will exist:
170:
171: my $lockfile=$peerfile.".lock";
172: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
173: sleep(1);
174: }
175: # At this point, either a loncnew parent is listening or an old lonc
176: # or loncnew child is listening so we can connect or everything's dead.
177: #
178: # We'll give the connection a few tries before abandoning it. If
179: # connection is not possible, we'll con_lost back to the client.
180: #
181: my $client;
182: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
183: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: if($client) {
187: last; # Connected!
188: } else {
189: &create_connection(&hostname($server),$server);
190: }
191: sleep(1); # Try again later if failed connection.
192: }
193: my $answer;
194: if ($client) {
195: print $client "sethost:$server:$cmd\n";
196: $answer=<$client>;
197: if (!$answer) { $answer="con_lost"; }
198: chomp($answer);
199: } else {
200: $answer = 'con_lost'; # Failed connection.
201: }
202: return $answer;
203: }
204:
205: sub reply {
206: my ($cmd,$server)=@_;
207: unless (defined(&hostname($server))) { return 'no_such_host'; }
208: my $answer=subreply($cmd,$server);
209: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
210: &logthis("<font color=\"blue\">WARNING:".
211: " $cmd to $server returned $answer</font>");
212: }
213: return $answer;
214: }
215:
216: # ----------------------------------------------------------- Send USR1 to lonc
217:
218: sub reconlonc {
219: &logthis("Trying to reconnect lonc");
220: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
221: if (open(my $fh,"<$loncfile")) {
222: my $loncpid=<$fh>;
223: chomp($loncpid);
224: if (kill 0 => $loncpid) {
225: &logthis("lonc at pid $loncpid responding, sending USR1");
226: kill USR1 => $loncpid;
227: sleep 1;
228: } else {
229: &logthis(
230: "<font color=\"blue\">WARNING:".
231: " lonc at pid $loncpid not responding, giving up</font>");
232: }
233: } else {
234: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
235: }
236: }
237:
238: # ------------------------------------------------------ Critical communication
239:
240: sub critical {
241: my ($cmd,$server)=@_;
242: unless (&hostname($server)) {
243: &logthis("<font color=\"blue\">WARNING:".
244: " Critical message to unknown server ($server)</font>");
245: return 'no_such_host';
246: }
247: my $answer=reply($cmd,$server);
248: if ($answer eq 'con_lost') {
249: &reconlonc("$perlvar{'lonSockDir'}/$server");
250: my $answer=reply($cmd,$server);
251: if ($answer eq 'con_lost') {
252: my $now=time;
253: my $middlename=$cmd;
254: $middlename=substr($middlename,0,16);
255: $middlename=~s/\W//g;
256: my $dfilename=
257: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
258: $dumpcount++;
259: {
260: my $dfh;
261: if (open($dfh,">$dfilename")) {
262: print $dfh "$cmd\n";
263: close($dfh);
264: }
265: }
266: sleep 2;
267: my $wcmd='';
268: {
269: my $dfh;
270: if (open($dfh,"<$dfilename")) {
271: $wcmd=<$dfh>;
272: close($dfh);
273: }
274: }
275: chomp($wcmd);
276: if ($wcmd eq $cmd) {
277: &logthis("<font color=\"blue\">WARNING: ".
278: "Connection buffer $dfilename: $cmd</font>");
279: &logperm("D:$server:$cmd");
280: return 'con_delayed';
281: } else {
282: &logthis("<font color=\"red\">CRITICAL:"
283: ." Critical connection failed: $server $cmd</font>");
284: &logperm("F:$server:$cmd");
285: return 'con_failed';
286: }
287: }
288: }
289: return $answer;
290: }
291:
292: # ------------------------------------------- check if return value is an error
293:
294: sub error {
295: my ($result) = @_;
296: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
297: if ($2 == 2) { return undef; }
298: return $1;
299: }
300: return undef;
301: }
302:
303: sub convert_and_load_session_env {
304: my ($lonidsdir,$handle)=@_;
305: my @profile;
306: {
307: open(my $idf,"$lonidsdir/$handle.id");
308: flock($idf,LOCK_SH);
309: @profile=<$idf>;
310: close($idf);
311: }
312: my %temp_env;
313: foreach my $line (@profile) {
314: if ($line !~ m/=/) {
315: return 0;
316: }
317: chomp($line);
318: my ($envname,$envvalue)=split(/=/,$line,2);
319: $temp_env{&unescape($envname)} = &unescape($envvalue);
320: }
321: unlink("$lonidsdir/$handle.id");
322: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
323: 0640)) {
324: %disk_env = %temp_env;
325: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
326: untie(%disk_env);
327: }
328: return 1;
329: }
330:
331: # ------------------------------------------- Transfer profile into environment
332: my $env_loaded;
333: sub transfer_profile_to_env {
334: my ($lonidsdir,$handle,$force_transfer) = @_;
335: if (!$force_transfer && $env_loaded) { return; }
336:
337: if (!defined($lonidsdir)) {
338: $lonidsdir = $perlvar{'lonIDsDir'};
339: }
340: if (!defined($handle)) {
341: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
342: }
343:
344: my $convert;
345: {
346: open(my $idf,"$lonidsdir/$handle.id");
347: flock($idf,LOCK_SH);
348: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
349: &GDBM_READER(),0640)) {
350: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
351: untie(%disk_env);
352: } else {
353: $convert = 1;
354: }
355: }
356: if ($convert) {
357: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
358: &logthis("Failed to load session, or convert session.");
359: }
360: }
361:
362: my %remove;
363: while ( my $envname = each(%env) ) {
364: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
365: if ($time < time-300) {
366: $remove{$key}++;
367: }
368: }
369: }
370:
371: $env{'user.environment'} = "$lonidsdir/$handle.id";
372: $env_loaded=1;
373: foreach my $expired_key (keys(%remove)) {
374: &delenv($expired_key);
375: }
376: }
377:
378: sub timed_flock {
379: my ($file,$lock_type) = @_;
380: my $failed=0;
381: eval {
382: local $SIG{__DIE__}='DEFAULT';
383: local $SIG{ALRM}=sub {
384: $failed=1;
385: die("failed lock");
386: };
387: alarm(13);
388: flock($file,$lock_type);
389: alarm(0);
390: };
391: if ($failed) {
392: return undef;
393: } else {
394: return 1;
395: }
396: }
397:
398: # ---------------------------------------------------------- Append Environment
399:
400: sub appenv {
401: my %newenv=@_;
402: foreach my $key (keys(%newenv)) {
403: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
404: &logthis("<font color=\"blue\">WARNING: ".
405: "Attempt to modify environment ".$key." to ".$newenv{$key}
406: .'</font>');
407: delete($newenv{$key});
408: } else {
409: $env{$key}=$newenv{$key};
410: }
411: }
412: open(my $env_file,$env{'user.environment'});
413: if (&timed_flock($env_file,LOCK_EX)
414: &&
415: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
416: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
417: while (my ($key,$value) = each(%newenv)) {
418: $disk_env{$key} = $value;
419: }
420: untie(%disk_env);
421: }
422: return 'ok';
423: }
424: # ----------------------------------------------------- Delete from Environment
425:
426: sub delenv {
427: my $delthis=shift;
428: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
429: &logthis("<font color=\"blue\">WARNING: ".
430: "Attempt to delete from environment ".$delthis);
431: return 'error';
432: }
433: open(my $env_file,$env{'user.environment'});
434: if (&timed_flock($env_file,LOCK_EX)
435: &&
436: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
437: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
438: foreach my $key (keys(%disk_env)) {
439: if ($key=~/^$delthis/) {
440: delete($env{$key});
441: delete($disk_env{$key});
442: }
443: }
444: untie(%disk_env);
445: }
446: return 'ok';
447: }
448:
449: sub get_env_multiple {
450: my ($name) = @_;
451: my @values;
452: if (defined($env{$name})) {
453: # exists is it an array
454: if (ref($env{$name})) {
455: @values=@{ $env{$name} };
456: } else {
457: $values[0]=$env{$name};
458: }
459: }
460: return(@values);
461: }
462:
463: # ------------------------------------------ Find out current server userload
464: # there is a copy in lond
465: sub userload {
466: my $numusers=0;
467: {
468: opendir(LONIDS,$perlvar{'lonIDsDir'});
469: my $filename;
470: my $curtime=time;
471: while ($filename=readdir(LONIDS)) {
472: if ($filename eq '.' || $filename eq '..') {next;}
473: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
474: if ($curtime-$mtime < 1800) { $numusers++; }
475: }
476: closedir(LONIDS);
477: }
478: my $userloadpercent=0;
479: my $maxuserload=$perlvar{'lonUserLoadLim'};
480: if ($maxuserload) {
481: $userloadpercent=100*$numusers/$maxuserload;
482: }
483: $userloadpercent=sprintf("%.2f",$userloadpercent);
484: return $userloadpercent;
485: }
486:
487: # ------------------------------------------ Fight off request when overloaded
488:
489: sub overloaderror {
490: my ($r,$checkserver)=@_;
491: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
492: my $loadavg;
493: if ($checkserver eq $perlvar{'lonHostID'}) {
494: open(my $loadfile,'/proc/loadavg');
495: $loadavg=<$loadfile>;
496: $loadavg =~ s/\s.*//g;
497: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
498: close($loadfile);
499: } else {
500: $loadavg=&reply('load',$checkserver);
501: }
502: my $overload=$loadavg-100;
503: if ($overload>0) {
504: $r->err_headers_out->{'Retry-After'}=$overload;
505: $r->log_error('Overload of '.$overload.' on '.$checkserver);
506: return 413;
507: }
508: return '';
509: }
510:
511: # ------------------------------ Find server with least workload from spare.tab
512:
513: sub spareserver {
514: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
515: my $spare_server;
516: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
517: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
518: : $userloadpercent;
519:
520: foreach my $try_server (@{ $spareid{'primary'} }) {
521: ($spare_server, $lowest_load) =
522: &compare_server_load($try_server, $spare_server, $lowest_load);
523: }
524:
525: my $found_server = ($spare_server ne '' && $lowest_load < 100);
526:
527: if (!$found_server) {
528: foreach my $try_server (@{ $spareid{'default'} }) {
529: ($spare_server, $lowest_load) =
530: &compare_server_load($try_server, $spare_server, $lowest_load);
531: }
532: }
533:
534: if (!$want_server_name) {
535: $spare_server="http://".&hostname($spare_server);
536: }
537: return $spare_server;
538: }
539:
540: sub compare_server_load {
541: my ($try_server, $spare_server, $lowest_load) = @_;
542:
543: my $loadans = &reply('load', $try_server);
544: my $userloadans = &reply('userload',$try_server);
545:
546: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
547: next; #didn't get a number from the server
548: }
549:
550: my $load;
551: if ($loadans =~ /\d/) {
552: if ($userloadans =~ /\d/) {
553: #both are numbers, pick the bigger one
554: $load = ($loadans > $userloadans) ? $loadans
555: : $userloadans;
556: } else {
557: $load = $loadans;
558: }
559: } else {
560: $load = $userloadans;
561: }
562:
563: if (($load =~ /\d/) && ($load < $lowest_load)) {
564: $spare_server = $try_server;
565: $lowest_load = $load;
566: }
567: return ($spare_server,$lowest_load);
568: }
569: # --------------------------------------------- Try to change a user's password
570:
571: sub changepass {
572: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
573: $currentpass = &escape($currentpass);
574: $newpass = &escape($newpass);
575: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
576: $server);
577: if (! $answer) {
578: &logthis("No reply on password change request to $server ".
579: "by $uname in domain $udom.");
580: } elsif ($answer =~ "^ok") {
581: &logthis("$uname in $udom successfully changed their password ".
582: "on $server.");
583: } elsif ($answer =~ "^pwchange_failure") {
584: &logthis("$uname in $udom was unable to change their password ".
585: "on $server. The action was blocked by either lcpasswd ".
586: "or pwchange");
587: } elsif ($answer =~ "^non_authorized") {
588: &logthis("$uname in $udom did not get their password correct when ".
589: "attempting to change it on $server.");
590: } elsif ($answer =~ "^auth_mode_error") {
591: &logthis("$uname in $udom attempted to change their password despite ".
592: "not being locally or internally authenticated on $server.");
593: } elsif ($answer =~ "^unknown_user") {
594: &logthis("$uname in $udom attempted to change their password ".
595: "on $server but were unable to because $server is not ".
596: "their home server.");
597: } elsif ($answer =~ "^refused") {
598: &logthis("$server refused to change $uname in $udom password because ".
599: "it was sent an unencrypted request to change the password.");
600: }
601: return $answer;
602: }
603:
604: # ----------------------- Try to determine user's current authentication scheme
605:
606: sub queryauthenticate {
607: my ($uname,$udom)=@_;
608: my $uhome=&homeserver($uname,$udom);
609: if (!$uhome) {
610: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
611: return 'no_host';
612: }
613: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
614: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
615: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
616: }
617: return $answer;
618: }
619:
620: # --------- Try to authenticate user from domain's lib servers (first this one)
621:
622: sub authenticate {
623: my ($uname,$upass,$udom)=@_;
624: $upass=&escape($upass);
625: $uname= &LONCAPA::clean_username($uname);
626: my $uhome=&homeserver($uname,$udom,1);
627: if ((!$uhome) || ($uhome eq 'no_host')) {
628: # Maybe the machine was offline and only re-appeared again recently?
629: &reconlonc();
630: # One more
631: my $uhome=&homeserver($uname,$udom,1);
632: if ((!$uhome) || ($uhome eq 'no_host')) {
633: &logthis("User $uname at $udom is unknown in authenticate");
634: }
635: return 'no_host';
636: }
637: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
638: if ($answer eq 'authorized') {
639: &logthis("User $uname at $udom authorized by $uhome");
640: return $uhome;
641: }
642: if ($answer eq 'non_authorized') {
643: &logthis("User $uname at $udom rejected by $uhome");
644: return 'no_host';
645: }
646: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
647: return 'no_host';
648: }
649:
650: # ---------------------- Find the homebase for a user from domain's lib servers
651:
652: my %homecache;
653: sub homeserver {
654: my ($uname,$udom,$ignoreBadCache)=@_;
655: my $index="$uname:$udom";
656:
657: if (exists($homecache{$index})) { return $homecache{$index}; }
658:
659: my %servers = &get_servers($udom,'library');
660: foreach my $tryserver (keys(%servers)) {
661: next if ($ignoreBadCache ne 'true' &&
662: exists($badServerCache{$tryserver}));
663:
664: my $answer=reply("home:$udom:$uname",$tryserver);
665: if ($answer eq 'found') {
666: delete($badServerCache{$tryserver});
667: return $homecache{$index}=$tryserver;
668: } elsif ($answer eq 'no_host') {
669: $badServerCache{$tryserver}=1;
670: }
671: }
672: return 'no_host';
673: }
674:
675: # ------------------------------------- Find the usernames behind a list of IDs
676:
677: sub idget {
678: my ($udom,@ids)=@_;
679: my %returnhash=();
680:
681: my %servers = &get_servers($udom,'library');
682: foreach my $tryserver (keys(%servers)) {
683: my $idlist=join('&',@ids);
684: $idlist=~tr/A-Z/a-z/;
685: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
686: my @answer=();
687: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
688: @answer=split(/\&/,$reply);
689: } ;
690: my $i;
691: for ($i=0;$i<=$#ids;$i++) {
692: if ($answer[$i]) {
693: $returnhash{$ids[$i]}=$answer[$i];
694: }
695: }
696: }
697: return %returnhash;
698: }
699:
700: # ------------------------------------- Find the IDs behind a list of usernames
701:
702: sub idrget {
703: my ($udom,@unames)=@_;
704: my %returnhash=();
705: foreach my $uname (@unames) {
706: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
707: }
708: return %returnhash;
709: }
710:
711: # ------------------------------- Store away a list of names and associated IDs
712:
713: sub idput {
714: my ($udom,%ids)=@_;
715: my %servers=();
716: foreach my $uname (keys(%ids)) {
717: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
718: my $uhom=&homeserver($uname,$udom);
719: if ($uhom ne 'no_host') {
720: my $id=&escape($ids{$uname});
721: $id=~tr/A-Z/a-z/;
722: my $esc_unam=&escape($uname);
723: if ($servers{$uhom}) {
724: $servers{$uhom}.='&'.$id.'='.$esc_unam;
725: } else {
726: $servers{$uhom}=$id.'='.$esc_unam;
727: }
728: }
729: }
730: foreach my $server (keys(%servers)) {
731: &critical('idput:'.$udom.':'.$servers{$server},$server);
732: }
733: }
734:
735: # ------------------------------------------- get items from domain db files
736:
737: sub get_dom {
738: my ($namespace,$storearr,$udom)=@_;
739: my $items='';
740: foreach my $item (@$storearr) {
741: $items.=&escape($item).'&';
742: }
743: $items=~s/\&$//;
744: if (!$udom) { $udom=$env{'user.domain'}; }
745: if (defined(&domain($udom,'primary'))) {
746: my $uhome=&domain($udom,'primary');
747: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
748: my @pairs=split(/\&/,$rep);
749: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
750: return @pairs;
751: }
752: my %returnhash=();
753: my $i=0;
754: foreach my $item (@$storearr) {
755: $returnhash{$item}=&thaw_unescape($pairs[$i]);
756: $i++;
757: }
758: return %returnhash;
759: } else {
760: &logthis("get_dom failed - no primary domain server for $udom");
761: }
762: }
763:
764: # -------------------------------------------- put items in domain db files
765:
766: sub put_dom {
767: my ($namespace,$storehash,$udom)=@_;
768: if (!$udom) { $udom=$env{'user.domain'}; }
769: if (defined(&domain($udom,'primary'))) {
770: my $uhome=&domain($udom,'primary');
771: my $items='';
772: foreach my $item (keys(%$storehash)) {
773: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
774: }
775: $items=~s/\&$//;
776: return &reply("putdom:$udom:$namespace:$items",$uhome);
777: } else {
778: &logthis("put_dom failed - no primary domain server for $udom");
779: }
780: }
781:
782: sub retrieve_inst_usertypes {
783: my ($udom) = @_;
784: my (%returnhash,@order);
785: if (defined(&domain($udom,'primary'))) {
786: my $uhome=&domain($udom,'primary');
787: my $rep=&reply("inst_usertypes:$udom",$uhome);
788: my ($hashitems,$orderitems) = split(/:/,$rep);
789: my @pairs=split(/\&/,$hashitems);
790: foreach my $item (@pairs) {
791: my ($key,$value)=split(/=/,$item,2);
792: $key = &unescape($key);
793: next if ($key =~ /^error: 2 /);
794: $returnhash{$key}=&thaw_unescape($value);
795: }
796: my @esc_order = split(/\&/,$orderitems);
797: foreach my $item (@esc_order) {
798: push(@order,&unescape($item));
799: }
800: } else {
801: &logthis("get_dom failed - no primary domain server for $udom");
802: }
803: return (\%returnhash,\@order);
804: }
805:
806: # --------------------------------------------------- Assign a key to a student
807:
808: sub assign_access_key {
809: #
810: # a valid key looks like uname:udom#comments
811: # comments are being appended
812: #
813: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
814: $kdom=
815: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
816: $knum=
817: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
818: $cdom=
819: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
820: $cnum=
821: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
822: $udom=$env{'user.name'} unless (defined($udom));
823: $uname=$env{'user.domain'} unless (defined($uname));
824: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
825: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
826: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
827: # assigned to this person
828: # - this should not happen,
829: # unless something went wrong
830: # the first time around
831: # ready to assign
832: $logentry=$1.'; '.$logentry;
833: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
834: $kdom,$knum) eq 'ok') {
835: # key now belongs to user
836: my $envkey='key.'.$cdom.'_'.$cnum;
837: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
838: &appenv('environment.'.$envkey => $ckey);
839: return 'ok';
840: } else {
841: return
842: 'error: Count not permanently assign key, will need to be re-entered later.';
843: }
844: } else {
845: return 'error: Could not assign key, try again later.';
846: }
847: } elsif (!$existing{$ckey}) {
848: # the key does not exist
849: return 'error: The key does not exist';
850: } else {
851: # the key is somebody else's
852: return 'error: The key is already in use';
853: }
854: }
855:
856: # ------------------------------------------ put an additional comment on a key
857:
858: sub comment_access_key {
859: #
860: # a valid key looks like uname:udom#comments
861: # comments are being appended
862: #
863: my ($ckey,$cdom,$cnum,$logentry)=@_;
864: $cdom=
865: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
866: $cnum=
867: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
868: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
869: if ($existing{$ckey}) {
870: $existing{$ckey}.='; '.$logentry;
871: # ready to assign
872: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
873: $cdom,$cnum) eq 'ok') {
874: return 'ok';
875: } else {
876: return 'error: Count not store comment.';
877: }
878: } else {
879: # the key does not exist
880: return 'error: The key does not exist';
881: }
882: }
883:
884: # ------------------------------------------------------ Generate a set of keys
885:
886: sub generate_access_keys {
887: my ($number,$cdom,$cnum,$logentry)=@_;
888: $cdom=
889: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
890: $cnum=
891: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
892: unless (&allowed('mky',$cdom)) { return 0; }
893: unless (($cdom) && ($cnum)) { return 0; }
894: if ($number>10000) { return 0; }
895: sleep(2); # make sure don't get same seed twice
896: srand(time()^($$+($$<<15))); # from "Programming Perl"
897: my $total=0;
898: for (my $i=1;$i<=$number;$i++) {
899: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
900: sprintf("%lx",int(100000*rand)).'-'.
901: sprintf("%lx",int(100000*rand));
902: $newkey=~s/1/g/g; # folks mix up 1 and l
903: $newkey=~s/0/h/g; # and also 0 and O
904: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
905: if ($existing{$newkey}) {
906: $i--;
907: } else {
908: if (&put('accesskeys',
909: { $newkey => '# generated '.localtime().
910: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
911: '; '.$logentry },
912: $cdom,$cnum) eq 'ok') {
913: $total++;
914: }
915: }
916: }
917: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
918: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
919: return $total;
920: }
921:
922: # ------------------------------------------------------- Validate an accesskey
923:
924: sub validate_access_key {
925: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
926: $cdom=
927: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
928: $cnum=
929: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
930: $udom=$env{'user.domain'} unless (defined($udom));
931: $uname=$env{'user.name'} unless (defined($uname));
932: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
933: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
934: }
935:
936: # ------------------------------------- Find the section of student in a course
937: sub devalidate_getsection_cache {
938: my ($udom,$unam,$courseid)=@_;
939: my $hashid="$udom:$unam:$courseid";
940: &devalidate_cache_new('getsection',$hashid);
941: }
942:
943: sub courseid_to_courseurl {
944: my ($courseid) = @_;
945: #already url style courseid
946: return $courseid if ($courseid =~ m{^/});
947:
948: if (exists($env{'course.'.$courseid.'.num'})) {
949: my $cnum = $env{'course.'.$courseid.'.num'};
950: my $cdom = $env{'course.'.$courseid.'.domain'};
951: return "/$cdom/$cnum";
952: }
953:
954: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
955: if (exists($courseinfo{'num'})) {
956: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
957: }
958:
959: return undef;
960: }
961:
962: sub getsection {
963: my ($udom,$unam,$courseid)=@_;
964: my $cachetime=1800;
965:
966: my $hashid="$udom:$unam:$courseid";
967: my ($result,$cached)=&is_cached_new('getsection',$hashid);
968: if (defined($cached)) { return $result; }
969:
970: my %Pending;
971: my %Expired;
972: #
973: # Each role can either have not started yet (pending), be active,
974: # or have expired.
975: #
976: # If there is an active role, we are done.
977: #
978: # If there is more than one role which has not started yet,
979: # choose the one which will start sooner
980: # If there is one role which has not started yet, return it.
981: #
982: # If there is more than one expired role, choose the one which ended last.
983: # If there is a role which has expired, return it.
984: #
985: $courseid = &courseid_to_courseurl($courseid);
986: my %roleshash = &dump('roles',$udom,$unam,$courseid);
987: foreach my $key (keys(%roleshash)) {
988: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
989: my $section=$1;
990: if ($key eq $courseid.'_st') { $section=''; }
991: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
992: my $now=time;
993: if (defined($end) && $end && ($now > $end)) {
994: $Expired{$end}=$section;
995: next;
996: }
997: if (defined($start) && $start && ($now < $start)) {
998: $Pending{$start}=$section;
999: next;
1000: }
1001: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1002: }
1003: #
1004: # Presumedly there will be few matching roles from the above
1005: # loop and the sorting time will be negligible.
1006: if (scalar(keys(%Pending))) {
1007: my ($time) = sort {$a <=> $b} keys(%Pending);
1008: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1009: }
1010: if (scalar(keys(%Expired))) {
1011: my @sorted = sort {$a <=> $b} keys(%Expired);
1012: my $time = pop(@sorted);
1013: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1014: }
1015: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1016: }
1017:
1018: sub save_cache {
1019: &purge_remembered();
1020: #&Apache::loncommon::validate_page();
1021: undef(%env);
1022: undef($env_loaded);
1023: }
1024:
1025: my $to_remember=-1;
1026: my %remembered;
1027: my %accessed;
1028: my $kicks=0;
1029: my $hits=0;
1030: sub make_key {
1031: my ($name,$id) = @_;
1032: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1033: return &escape($name.':'.$id);
1034: }
1035:
1036: sub devalidate_cache_new {
1037: my ($name,$id,$debug) = @_;
1038: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1039: $id=&make_key($name,$id);
1040: $memcache->delete($id);
1041: delete($remembered{$id});
1042: delete($accessed{$id});
1043: }
1044:
1045: sub is_cached_new {
1046: my ($name,$id,$debug) = @_;
1047: $id=&make_key($name,$id);
1048: if (exists($remembered{$id})) {
1049: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1050: $accessed{$id}=[&gettimeofday()];
1051: $hits++;
1052: return ($remembered{$id},1);
1053: }
1054: my $value = $memcache->get($id);
1055: if (!(defined($value))) {
1056: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1057: return (undef,undef);
1058: }
1059: if ($value eq '__undef__') {
1060: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1061: $value=undef;
1062: }
1063: &make_room($id,$value,$debug);
1064: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1065: return ($value,1);
1066: }
1067:
1068: sub do_cache_new {
1069: my ($name,$id,$value,$time,$debug) = @_;
1070: $id=&make_key($name,$id);
1071: my $setvalue=$value;
1072: if (!defined($setvalue)) {
1073: $setvalue='__undef__';
1074: }
1075: if (!defined($time) ) {
1076: $time=600;
1077: }
1078: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1079: $memcache->set($id,$setvalue,$time);
1080: # need to make a copy of $value
1081: #&make_room($id,$value,$debug);
1082: return $value;
1083: }
1084:
1085: sub make_room {
1086: my ($id,$value,$debug)=@_;
1087: $remembered{$id}=$value;
1088: if ($to_remember<0) { return; }
1089: $accessed{$id}=[&gettimeofday()];
1090: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1091: my $to_kick;
1092: my $max_time=0;
1093: foreach my $other (keys(%accessed)) {
1094: if (&tv_interval($accessed{$other}) > $max_time) {
1095: $to_kick=$other;
1096: $max_time=&tv_interval($accessed{$other});
1097: }
1098: }
1099: delete($remembered{$to_kick});
1100: delete($accessed{$to_kick});
1101: $kicks++;
1102: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1103: return;
1104: }
1105:
1106: sub purge_remembered {
1107: #&logthis("Tossing ".scalar(keys(%remembered)));
1108: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1109: undef(%remembered);
1110: undef(%accessed);
1111: }
1112: # ------------------------------------- Read an entry from a user's environment
1113:
1114: sub userenvironment {
1115: my ($udom,$unam,@what)=@_;
1116: my %returnhash=();
1117: my @answer=split(/\&/,
1118: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1119: &homeserver($unam,$udom)));
1120: my $i;
1121: for ($i=0;$i<=$#what;$i++) {
1122: $returnhash{$what[$i]}=&unescape($answer[$i]);
1123: }
1124: return %returnhash;
1125: }
1126:
1127: # ---------------------------------------------------------- Get a studentphoto
1128: sub studentphoto {
1129: my ($udom,$unam,$ext) = @_;
1130: my $home=&Apache::lonnet::homeserver($unam,$udom);
1131: if (defined($env{'request.course.id'})) {
1132: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1133: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1134: return(&retrievestudentphoto($udom,$unam,$ext));
1135: } else {
1136: my ($result,$perm_reqd)=
1137: &Apache::lonnet::auto_photo_permission($unam,$udom);
1138: if ($result eq 'ok') {
1139: if (!($perm_reqd eq 'yes')) {
1140: return(&retrievestudentphoto($udom,$unam,$ext));
1141: }
1142: }
1143: }
1144: }
1145: } else {
1146: my ($result,$perm_reqd) =
1147: &Apache::lonnet::auto_photo_permission($unam,$udom);
1148: if ($result eq 'ok') {
1149: if (!($perm_reqd eq 'yes')) {
1150: return(&retrievestudentphoto($udom,$unam,$ext));
1151: }
1152: }
1153: }
1154: return '/adm/lonKaputt/lonlogo_broken.gif';
1155: }
1156:
1157: sub retrievestudentphoto {
1158: my ($udom,$unam,$ext,$type) = @_;
1159: my $home=&Apache::lonnet::homeserver($unam,$udom);
1160: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1161: if ($ret eq 'ok') {
1162: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1163: if ($type eq 'thumbnail') {
1164: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1165: }
1166: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1167: return $tokenurl;
1168: } else {
1169: if ($type eq 'thumbnail') {
1170: return '/adm/lonKaputt/genericstudent_tn.gif';
1171: } else {
1172: return '/adm/lonKaputt/lonlogo_broken.gif';
1173: }
1174: }
1175: }
1176:
1177: # -------------------------------------------------------------------- New chat
1178:
1179: sub chatsend {
1180: my ($newentry,$anon,$group)=@_;
1181: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1182: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1183: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1184: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1185: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1186: &escape($newentry)).':'.$group,$chome);
1187: }
1188:
1189: # ------------------------------------------ Find current version of a resource
1190:
1191: sub getversion {
1192: my $fname=&clutter(shift);
1193: unless ($fname=~/^\/res\//) { return -1; }
1194: return ¤tversion(&filelocation('',$fname));
1195: }
1196:
1197: sub currentversion {
1198: my $fname=shift;
1199: my ($result,$cached)=&is_cached_new('resversion',$fname);
1200: if (defined($cached)) { return $result; }
1201: my $author=$fname;
1202: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1203: my ($udom,$uname)=split(/\//,$author);
1204: my $home=homeserver($uname,$udom);
1205: if ($home eq 'no_host') {
1206: return -1;
1207: }
1208: my $answer=reply("currentversion:$fname",$home);
1209: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1210: return -1;
1211: }
1212: return &do_cache_new('resversion',$fname,$answer,600);
1213: }
1214:
1215: # ----------------------------- Subscribe to a resource, return URL if possible
1216:
1217: sub subscribe {
1218: my $fname=shift;
1219: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1220: $fname=~s/[\n\r]//g;
1221: my $author=$fname;
1222: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1223: my ($udom,$uname)=split(/\//,$author);
1224: my $home=homeserver($uname,$udom);
1225: if ($home eq 'no_host') {
1226: return 'not_found';
1227: }
1228: my $answer=reply("sub:$fname",$home);
1229: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1230: $answer.=' by '.$home;
1231: }
1232: return $answer;
1233: }
1234:
1235: # -------------------------------------------------------------- Replicate file
1236:
1237: sub repcopy {
1238: my $filename=shift;
1239: $filename=~s/\/+/\//g;
1240: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1241: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1242: if ($filename=~m|^/home/httpd/html/userfiles/| or
1243: $filename=~m -^/*(uploaded|editupload)/-) {
1244: return &repcopy_userfile($filename);
1245: }
1246: $filename=~s/[\n\r]//g;
1247: my $transname="$filename.in.transfer";
1248: # FIXME: this should flock
1249: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1250: my $remoteurl=subscribe($filename);
1251: if ($remoteurl =~ /^con_lost by/) {
1252: &logthis("Subscribe returned $remoteurl: $filename");
1253: return 'unavailable';
1254: } elsif ($remoteurl eq 'not_found') {
1255: #&logthis("Subscribe returned not_found: $filename");
1256: return 'not_found';
1257: } elsif ($remoteurl =~ /^rejected by/) {
1258: &logthis("Subscribe returned $remoteurl: $filename");
1259: return 'forbidden';
1260: } elsif ($remoteurl eq 'directory') {
1261: return 'ok';
1262: } else {
1263: my $author=$filename;
1264: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1265: my ($udom,$uname)=split(/\//,$author);
1266: my $home=homeserver($uname,$udom);
1267: unless ($home eq $perlvar{'lonHostID'}) {
1268: my @parts=split(/\//,$filename);
1269: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1270: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1271: &logthis("Malconfiguration for replication: $filename");
1272: return 'bad_request';
1273: }
1274: my $count;
1275: for ($count=5;$count<$#parts;$count++) {
1276: $path.="/$parts[$count]";
1277: if ((-e $path)!=1) {
1278: mkdir($path,0777);
1279: }
1280: }
1281: my $ua=new LWP::UserAgent;
1282: my $request=new HTTP::Request('GET',"$remoteurl");
1283: my $response=$ua->request($request,$transname);
1284: if ($response->is_error()) {
1285: unlink($transname);
1286: my $message=$response->status_line;
1287: &logthis("<font color=\"blue\">WARNING:"
1288: ." LWP get: $message: $filename</font>");
1289: return 'unavailable';
1290: } else {
1291: if ($remoteurl!~/\.meta$/) {
1292: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1293: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1294: if ($mresponse->is_error()) {
1295: unlink($filename.'.meta');
1296: &logthis(
1297: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1298: }
1299: }
1300: rename($transname,$filename);
1301: return 'ok';
1302: }
1303: }
1304: }
1305: }
1306:
1307: # ------------------------------------------------ Get server side include body
1308: sub ssi_body {
1309: my ($filelink,%form)=@_;
1310: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1311: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1312: }
1313: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1314: &ssi($filelink,%form));
1315: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1316: $output=~s/^.*?\<body[^\>]*\>//si;
1317: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1318: return $output;
1319: }
1320:
1321: # --------------------------------------------------------- Server Side Include
1322:
1323: sub absolute_url {
1324: my ($host_name) = @_;
1325: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1326: if ($host_name eq '') {
1327: $host_name = $ENV{'SERVER_NAME'};
1328: }
1329: return $protocol.$host_name;
1330: }
1331:
1332: sub ssi {
1333:
1334: my ($fn,%form)=@_;
1335:
1336: my $ua=new LWP::UserAgent;
1337:
1338: my $request;
1339:
1340: $form{'no_update_last_known'}=1;
1341:
1342: if (%form) {
1343: $request=new HTTP::Request('POST',&absolute_url().$fn);
1344: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1345: } else {
1346: $request=new HTTP::Request('GET',&absolute_url().$fn);
1347: }
1348:
1349: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1350: my $response=$ua->request($request);
1351:
1352: return $response->content;
1353: }
1354:
1355: sub externalssi {
1356: my ($url)=@_;
1357: my $ua=new LWP::UserAgent;
1358: my $request=new HTTP::Request('GET',$url);
1359: my $response=$ua->request($request);
1360: return $response->content;
1361: }
1362:
1363: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1364:
1365: sub allowuploaded {
1366: my ($srcurl,$url)=@_;
1367: $url=&clutter(&declutter($url));
1368: my $dir=$url;
1369: $dir=~s/\/[^\/]+$//;
1370: my %httpref=();
1371: my $httpurl=&hreflocation('',$url);
1372: $httpref{'httpref.'.$httpurl}=$srcurl;
1373: &Apache::lonnet::appenv(%httpref);
1374: }
1375:
1376: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1377: # input: action, courseID, current domain, intended
1378: # path to file, source of file, instruction to parse file for objects,
1379: # ref to hash for embedded objects,
1380: # ref to hash for codebase of java objects.
1381: #
1382: # output: url to file (if action was uploaddoc),
1383: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1384: #
1385: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1386: # course.
1387: #
1388: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1389: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1390: # course's home server.
1391: #
1392: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1393: # be copied from $source (current location) to
1394: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1395: # and will then be copied to
1396: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1397: # course's home server.
1398: #
1399: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1400: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1401: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1402: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1403: # in course's home server.
1404: #
1405:
1406: sub process_coursefile {
1407: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1408: my $fetchresult;
1409: my $home=&homeserver($docuname,$docudom);
1410: if ($action eq 'propagate') {
1411: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1412: $home);
1413: } else {
1414: my $fpath = '';
1415: my $fname = $file;
1416: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1417: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1418: my $filepath = &build_filepath($fpath);
1419: if ($action eq 'copy') {
1420: if ($source eq '') {
1421: $fetchresult = 'no source file';
1422: return $fetchresult;
1423: } else {
1424: my $destination = $filepath.'/'.$fname;
1425: rename($source,$destination);
1426: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1427: $home);
1428: }
1429: } elsif ($action eq 'uploaddoc') {
1430: open(my $fh,'>'.$filepath.'/'.$fname);
1431: print $fh $env{'form.'.$source};
1432: close($fh);
1433: if ($parser eq 'parse') {
1434: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1435: unless ($parse_result eq 'ok') {
1436: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1437: }
1438: }
1439: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1440: $home);
1441: if ($fetchresult eq 'ok') {
1442: return '/uploaded/'.$fpath.'/'.$fname;
1443: } else {
1444: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1445: ' to host '.$home.': '.$fetchresult);
1446: return '/adm/notfound.html';
1447: }
1448: }
1449: }
1450: unless ( $fetchresult eq 'ok') {
1451: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1452: ' to host '.$home.': '.$fetchresult);
1453: }
1454: return $fetchresult;
1455: }
1456:
1457: sub build_filepath {
1458: my ($fpath) = @_;
1459: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1460: unless ($fpath eq '') {
1461: my @parts=split('/',$fpath);
1462: foreach my $part (@parts) {
1463: $filepath.= '/'.$part;
1464: if ((-e $filepath)!=1) {
1465: mkdir($filepath,0777);
1466: }
1467: }
1468: }
1469: return $filepath;
1470: }
1471:
1472: sub store_edited_file {
1473: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1474: my $file = $primary_url;
1475: $file =~ s#^/uploaded/$docudom/$docuname/##;
1476: my $fpath = '';
1477: my $fname = $file;
1478: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1479: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1480: my $filepath = &build_filepath($fpath);
1481: open(my $fh,'>'.$filepath.'/'.$fname);
1482: print $fh $content;
1483: close($fh);
1484: my $home=&homeserver($docuname,$docudom);
1485: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1486: $home);
1487: if ($$fetchresult eq 'ok') {
1488: return '/uploaded/'.$fpath.'/'.$fname;
1489: } else {
1490: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1491: ' to host '.$home.': '.$$fetchresult);
1492: return '/adm/notfound.html';
1493: }
1494: }
1495:
1496: sub clean_filename {
1497: my ($fname,$args)=@_;
1498: # Replace Windows backslashes by forward slashes
1499: $fname=~s/\\/\//g;
1500: if (!$args->{'keep_path'}) {
1501: # Get rid of everything but the actual filename
1502: $fname=~s/^.*\/([^\/]+)$/$1/;
1503: }
1504: # Replace spaces by underscores
1505: $fname=~s/\s+/\_/g;
1506: # Replace all other weird characters by nothing
1507: $fname=~s{[^/\w\.\-]}{}g;
1508: # Replace all .\d. sequences with _\d. so they no longer look like version
1509: # numbers
1510: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1511: return $fname;
1512: }
1513:
1514: # --------------- Take an uploaded file and put it into the userfiles directory
1515: # input: $formname - the contents of the file are in $env{"form.$formname"}
1516: # the desired filenam is in $env{"form.$formname.filename"}
1517: # $coursedoc - if true up to the current course
1518: # if false
1519: # $subdir - directory in userfile to store the file into
1520: # $parser, $allfiles, $codebase - unknown
1521: #
1522: # output: url of file in userspace, or error: <message>
1523: # or /adm/notfound.html if failure to upload occurse
1524:
1525:
1526: sub userfileupload {
1527: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1528: if (!defined($subdir)) { $subdir='unknown'; }
1529: my $fname=$env{'form.'.$formname.'.filename'};
1530: $fname=&clean_filename($fname);
1531: # See if there is anything left
1532: unless ($fname) { return 'error: no uploaded file'; }
1533: chop($env{'form.'.$formname});
1534: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1535: my $now = time;
1536: my $filepath = 'tmp/helprequests/'.$now;
1537: my @parts=split(/\//,$filepath);
1538: my $fullpath = $perlvar{'lonDaemons'};
1539: for (my $i=0;$i<@parts;$i++) {
1540: $fullpath .= '/'.$parts[$i];
1541: if ((-e $fullpath)!=1) {
1542: mkdir($fullpath,0777);
1543: }
1544: }
1545: open(my $fh,'>'.$fullpath.'/'.$fname);
1546: print $fh $env{'form.'.$formname};
1547: close($fh);
1548: return $fullpath.'/'.$fname;
1549: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1550: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1551: '_'.$env{'user.domain'}.'/pending';
1552: my @parts=split(/\//,$filepath);
1553: my $fullpath = $perlvar{'lonDaemons'};
1554: for (my $i=0;$i<@parts;$i++) {
1555: $fullpath .= '/'.$parts[$i];
1556: if ((-e $fullpath)!=1) {
1557: mkdir($fullpath,0777);
1558: }
1559: }
1560: open(my $fh,'>'.$fullpath.'/'.$fname);
1561: print $fh $env{'form.'.$formname};
1562: close($fh);
1563: return $fullpath.'/'.$fname;
1564: }
1565:
1566: # Create the directory if not present
1567: $fname="$subdir/$fname";
1568: if ($coursedoc) {
1569: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1570: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1571: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1572: return &finishuserfileupload($docuname,$docudom,
1573: $formname,$fname,$parser,$allfiles,
1574: $codebase);
1575: } else {
1576: $fname=$env{'form.folder'}.'/'.$fname;
1577: return &process_coursefile('uploaddoc',$docuname,$docudom,
1578: $fname,$formname,$parser,
1579: $allfiles,$codebase);
1580: }
1581: } elsif (defined($destuname)) {
1582: my $docuname=$destuname;
1583: my $docudom=$destudom;
1584: return &finishuserfileupload($docuname,$docudom,$formname,
1585: $fname,$parser,$allfiles,$codebase);
1586:
1587: } else {
1588: my $docuname=$env{'user.name'};
1589: my $docudom=$env{'user.domain'};
1590: if (exists($env{'form.group'})) {
1591: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1592: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1593: }
1594: return &finishuserfileupload($docuname,$docudom,$formname,
1595: $fname,$parser,$allfiles,$codebase);
1596: }
1597: }
1598:
1599: sub finishuserfileupload {
1600: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1601: my $path=$docudom.'/'.$docuname.'/';
1602: my $filepath=$perlvar{'lonDocRoot'};
1603: my ($fnamepath,$file);
1604: $file=$fname;
1605: if ($fname=~m|/|) {
1606: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1607: $path.=$fnamepath.'/';
1608: }
1609: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1610: my $count;
1611: for ($count=4;$count<=$#parts;$count++) {
1612: $filepath.="/$parts[$count]";
1613: if ((-e $filepath)!=1) {
1614: mkdir($filepath,0777);
1615: }
1616: }
1617: # Save the file
1618: {
1619: if (!open(FH,'>'.$filepath.'/'.$file)) {
1620: &logthis('Failed to create '.$filepath.'/'.$file);
1621: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1622: return '/adm/notfound.html';
1623: }
1624: if (!print FH ($env{'form.'.$formname})) {
1625: &logthis('Failed to write to '.$filepath.'/'.$file);
1626: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1627: return '/adm/notfound.html';
1628: }
1629: close(FH);
1630: }
1631: if ($parser eq 'parse') {
1632: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1633: $codebase);
1634: unless ($parse_result eq 'ok') {
1635: &logthis('Failed to parse '.$filepath.$file.
1636: ' for embedded media: '.$parse_result);
1637: }
1638: }
1639: # Notify homeserver to grep it
1640: #
1641: my $docuhome=&homeserver($docuname,$docudom);
1642: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1643: if ($fetchresult eq 'ok') {
1644: #
1645: # Return the URL to it
1646: return '/uploaded/'.$path.$file;
1647: } else {
1648: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1649: ': '.$fetchresult);
1650: return '/adm/notfound.html';
1651: }
1652: }
1653:
1654: sub extract_embedded_items {
1655: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1656: my @state = ();
1657: my %javafiles = (
1658: codebase => '',
1659: code => '',
1660: archive => ''
1661: );
1662: my %mediafiles = (
1663: src => '',
1664: movie => '',
1665: );
1666: my $p;
1667: if ($content) {
1668: $p = HTML::LCParser->new($content);
1669: } else {
1670: $p = HTML::LCParser->new($filepath.'/'.$file);
1671: }
1672: while (my $t=$p->get_token()) {
1673: if ($t->[0] eq 'S') {
1674: my ($tagname, $attr) = ($t->[1],$t->[2]);
1675: push (@state, $tagname);
1676: if (lc($tagname) eq 'allow') {
1677: &add_filetype($allfiles,$attr->{'src'},'src');
1678: }
1679: if (lc($tagname) eq 'img') {
1680: &add_filetype($allfiles,$attr->{'src'},'src');
1681: }
1682: if (lc($tagname) eq 'script') {
1683: if ($attr->{'archive'} =~ /\.jar$/i) {
1684: &add_filetype($allfiles,$attr->{'archive'},'archive');
1685: } else {
1686: &add_filetype($allfiles,$attr->{'src'},'src');
1687: }
1688: }
1689: if (lc($tagname) eq 'link') {
1690: if (lc($attr->{'rel'}) eq 'stylesheet') {
1691: &add_filetype($allfiles,$attr->{'href'},'href');
1692: }
1693: }
1694: if (lc($tagname) eq 'object' ||
1695: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1696: foreach my $item (keys(%javafiles)) {
1697: $javafiles{$item} = '';
1698: }
1699: }
1700: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1701: my $name = lc($attr->{'name'});
1702: foreach my $item (keys(%javafiles)) {
1703: if ($name eq $item) {
1704: $javafiles{$item} = $attr->{'value'};
1705: last;
1706: }
1707: }
1708: foreach my $item (keys(%mediafiles)) {
1709: if ($name eq $item) {
1710: &add_filetype($allfiles, $attr->{'value'}, 'value');
1711: last;
1712: }
1713: }
1714: }
1715: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1716: foreach my $item (keys(%javafiles)) {
1717: if ($attr->{$item}) {
1718: $javafiles{$item} = $attr->{$item};
1719: last;
1720: }
1721: }
1722: foreach my $item (keys(%mediafiles)) {
1723: if ($attr->{$item}) {
1724: &add_filetype($allfiles,$attr->{$item},$item);
1725: last;
1726: }
1727: }
1728: }
1729: } elsif ($t->[0] eq 'E') {
1730: my ($tagname) = ($t->[1]);
1731: if ($javafiles{'codebase'} ne '') {
1732: $javafiles{'codebase'} .= '/';
1733: }
1734: if (lc($tagname) eq 'applet' ||
1735: lc($tagname) eq 'object' ||
1736: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1737: ) {
1738: foreach my $item (keys(%javafiles)) {
1739: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1740: my $file=$javafiles{'codebase'}.$javafiles{$item};
1741: &add_filetype($allfiles,$file,$item);
1742: }
1743: }
1744: }
1745: pop @state;
1746: }
1747: }
1748: return 'ok';
1749: }
1750:
1751: sub add_filetype {
1752: my ($allfiles,$file,$type)=@_;
1753: if (exists($allfiles->{$file})) {
1754: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1755: push(@{$allfiles->{$file}}, &escape($type));
1756: }
1757: } else {
1758: @{$allfiles->{$file}} = (&escape($type));
1759: }
1760: }
1761:
1762: sub removeuploadedurl {
1763: my ($url)=@_;
1764: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1765: return &removeuserfile($uname,$udom,$fname);
1766: }
1767:
1768: sub removeuserfile {
1769: my ($docuname,$docudom,$fname)=@_;
1770: my $home=&homeserver($docuname,$docudom);
1771: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1772: if ($result eq 'ok') {
1773: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1774: my $metafile = $fname.'.meta';
1775: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1776: my $url = "/uploaded/$docudom/$docuname/$fname";
1777: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1778: my $sqlresult =
1779: &update_portfolio_table($docuname,$docudom,$file,
1780: 'portfolio_metadata',$group,
1781: 'delete');
1782: }
1783: }
1784: return $result;
1785: }
1786:
1787: sub mkdiruserfile {
1788: my ($docuname,$docudom,$dir)=@_;
1789: my $home=&homeserver($docuname,$docudom);
1790: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1791: }
1792:
1793: sub renameuserfile {
1794: my ($docuname,$docudom,$old,$new)=@_;
1795: my $home=&homeserver($docuname,$docudom);
1796: my $result = &reply("renameuserfile:$docudom:$docuname:".
1797: &escape("$old").':'.&escape("$new"),$home);
1798: if ($result eq 'ok') {
1799: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1800: my $oldmeta = $old.'.meta';
1801: my $newmeta = $new.'.meta';
1802: my $metaresult =
1803: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1804: my $url = "/uploaded/$docudom/$docuname/$old";
1805: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1806: my $sqlresult =
1807: &update_portfolio_table($docuname,$docudom,$file,
1808: 'portfolio_metadata',$group,
1809: 'delete');
1810: }
1811: }
1812: return $result;
1813: }
1814:
1815: # ------------------------------------------------------------------------- Log
1816:
1817: sub log {
1818: my ($dom,$nam,$hom,$what)=@_;
1819: return critical("log:$dom:$nam:$what",$hom);
1820: }
1821:
1822: # ------------------------------------------------------------------ Course Log
1823: #
1824: # This routine flushes several buffers of non-mission-critical nature
1825: #
1826:
1827: sub flushcourselogs {
1828: &logthis('Flushing log buffers');
1829: #
1830: # course logs
1831: # This is a log of all transactions in a course, which can be used
1832: # for data mining purposes
1833: #
1834: # It also collects the courseid database, which lists last transaction
1835: # times and course titles for all courseids
1836: #
1837: my %courseidbuffer=();
1838: foreach my $crsid (keys %courselogs) {
1839: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1840: &escape($courselogs{$crsid}),
1841: $coursehombuf{$crsid}) eq 'ok') {
1842: delete $courselogs{$crsid};
1843: } else {
1844: &logthis('Failed to flush log buffer for '.$crsid);
1845: if (length($courselogs{$crsid})>40000) {
1846: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1847: " exceeded maximum size, deleting.</font>");
1848: delete $courselogs{$crsid};
1849: }
1850: }
1851: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1852: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1853: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1854: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1855: } else {
1856: $courseidbuffer{$coursehombuf{$crsid}}=
1857: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1858: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1859: }
1860: }
1861: #
1862: # Write course id database (reverse lookup) to homeserver of courses
1863: # Is used in pickcourse
1864: #
1865: foreach my $crs_home (keys(%courseidbuffer)) {
1866: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1867: $crs_home);
1868: }
1869: #
1870: # File accesses
1871: # Writes to the dynamic metadata of resources to get hit counts, etc.
1872: #
1873: foreach my $entry (keys(%accesshash)) {
1874: if ($entry =~ /___count$/) {
1875: my ($dom,$name);
1876: ($dom,$name,undef)=
1877: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1878: if (! defined($dom) || $dom eq '' ||
1879: ! defined($name) || $name eq '') {
1880: my $cid = $env{'request.course.id'};
1881: $dom = $env{'request.'.$cid.'.domain'};
1882: $name = $env{'request.'.$cid.'.num'};
1883: }
1884: my $value = $accesshash{$entry};
1885: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1886: my %temphash=($url => $value);
1887: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1888: if ($result eq 'ok') {
1889: delete $accesshash{$entry};
1890: } elsif ($result eq 'unknown_cmd') {
1891: # Target server has old code running on it.
1892: my %temphash=($entry => $value);
1893: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1894: delete $accesshash{$entry};
1895: }
1896: }
1897: } else {
1898: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1899: my %temphash=($entry => $accesshash{$entry});
1900: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1901: delete $accesshash{$entry};
1902: }
1903: }
1904: }
1905: #
1906: # Roles
1907: # Reverse lookup of user roles for course faculty/staff and co-authorship
1908: #
1909: foreach my $entry (keys(%userrolehash)) {
1910: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1911: split(/\:/,$entry);
1912: if (&Apache::lonnet::put('nohist_userroles',
1913: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1914: $rudom,$runame) eq 'ok') {
1915: delete $userrolehash{$entry};
1916: }
1917: }
1918: #
1919: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1920: #
1921: my %domrolebuffer = ();
1922: foreach my $entry (keys %domainrolehash) {
1923: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1924: if ($domrolebuffer{$rudom}) {
1925: $domrolebuffer{$rudom}.='&'.&escape($entry).
1926: '='.&escape($domainrolehash{$entry});
1927: } else {
1928: $domrolebuffer{$rudom}.=&escape($entry).
1929: '='.&escape($domainrolehash{$entry});
1930: }
1931: delete $domainrolehash{$entry};
1932: }
1933: foreach my $dom (keys(%domrolebuffer)) {
1934: my %servers = &get_servers($dom,'library');
1935: foreach my $tryserver (keys(%servers)) {
1936: unless (&reply('domroleput:'.$dom.':'.
1937: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1938: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1939: }
1940: }
1941: }
1942: $dumpcount++;
1943: }
1944:
1945: sub courselog {
1946: my $what=shift;
1947: $what=time.':'.$what;
1948: unless ($env{'request.course.id'}) { return ''; }
1949: $coursedombuf{$env{'request.course.id'}}=
1950: $env{'course.'.$env{'request.course.id'}.'.domain'};
1951: $coursenumbuf{$env{'request.course.id'}}=
1952: $env{'course.'.$env{'request.course.id'}.'.num'};
1953: $coursehombuf{$env{'request.course.id'}}=
1954: $env{'course.'.$env{'request.course.id'}.'.home'};
1955: $coursedescrbuf{$env{'request.course.id'}}=
1956: $env{'course.'.$env{'request.course.id'}.'.description'};
1957: $courseinstcodebuf{$env{'request.course.id'}}=
1958: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1959: $courseownerbuf{$env{'request.course.id'}}=
1960: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1961: $coursetypebuf{$env{'request.course.id'}}=
1962: $env{'course.'.$env{'request.course.id'}.'.type'};
1963: if (defined $courselogs{$env{'request.course.id'}}) {
1964: $courselogs{$env{'request.course.id'}}.='&'.$what;
1965: } else {
1966: $courselogs{$env{'request.course.id'}}.=$what;
1967: }
1968: if (length($courselogs{$env{'request.course.id'}})>4048) {
1969: &flushcourselogs();
1970: }
1971: }
1972:
1973: sub courseacclog {
1974: my $fnsymb=shift;
1975: unless ($env{'request.course.id'}) { return ''; }
1976: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1977: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1978: $what.=':POST';
1979: # FIXME: Probably ought to escape things....
1980: foreach my $key (keys(%env)) {
1981: if ($key=~/^form\.(.*)/) {
1982: $what.=':'.$1.'='.$env{$key};
1983: }
1984: }
1985: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1986: # FIXME: We should not be depending on a form parameter that someone
1987: # editing lonsearchcat.pm might change in the future.
1988: if ($env{'form.phase'} eq 'course_search') {
1989: $what.= ':POST';
1990: # FIXME: Probably ought to escape things....
1991: foreach my $element ('courseexp','crsfulltext','crsrelated',
1992: 'crsdiscuss') {
1993: $what.=':'.$element.'='.$env{'form.'.$element};
1994: }
1995: }
1996: }
1997: &courselog($what);
1998: }
1999:
2000: sub countacc {
2001: my $url=&declutter(shift);
2002: return if (! defined($url) || $url eq '');
2003: unless ($env{'request.course.id'}) { return ''; }
2004: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2005: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2006: $accesshash{$key}++;
2007: }
2008:
2009: sub linklog {
2010: my ($from,$to)=@_;
2011: $from=&declutter($from);
2012: $to=&declutter($to);
2013: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2014: $accesshash{$to.'___'.$from.'___goto'}=1;
2015: }
2016:
2017: sub userrolelog {
2018: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2019: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2020: ($trole=~/^in/) || ($trole=~/^cc/) ||
2021: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2022: ($trole=~/^ta/)) {
2023: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2024: $userrolehash
2025: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2026: =$tend.':'.$tstart;
2027: }
2028: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2029: ($trole=~/^li/) || ($trole=~/^li/) ||
2030: ($trole=~/^au/) || ($trole=~/^dg/) ||
2031: ($trole=~/^sc/)) {
2032: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2033: $domainrolehash
2034: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2035: = $tend.':'.$tstart;
2036: }
2037: }
2038:
2039: sub get_course_adv_roles {
2040: my $cid=shift;
2041: $cid=$env{'request.course.id'} unless (defined($cid));
2042: my %coursehash=&coursedescription($cid);
2043: my %nothide=();
2044: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2045: $nothide{join(':',split(/[\@\:]/,$user))}=1;
2046: }
2047: my %returnhash=();
2048: my %dumphash=
2049: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2050: my $now=time;
2051: foreach my $entry (keys %dumphash) {
2052: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2053: if (($tstart) && ($tstart<0)) { next; }
2054: if (($tend) && ($tend<$now)) { next; }
2055: if (($tstart) && ($now<$tstart)) { next; }
2056: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2057: if ($username eq '' || $domain eq '') { next; }
2058: if ((&privileged($username,$domain)) &&
2059: (!$nothide{$username.':'.$domain})) { next; }
2060: if ($role eq 'cr') { next; }
2061: my $key=&plaintext($role);
2062: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2063: if ($returnhash{$key}) {
2064: $returnhash{$key}.=','.$username.':'.$domain;
2065: } else {
2066: $returnhash{$key}=$username.':'.$domain;
2067: }
2068: }
2069: return %returnhash;
2070: }
2071:
2072: sub get_my_roles {
2073: my ($uname,$udom,$types,$roles,$roledoms)=@_;
2074: unless (defined($uname)) { $uname=$env{'user.name'}; }
2075: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2076: my %dumphash=
2077: &dump('nohist_userroles',$udom,$uname);
2078: my %returnhash=();
2079: my $now=time;
2080: foreach my $entry (keys(%dumphash)) {
2081: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2082: if (($tstart) && ($tstart<0)) { next; }
2083: my $status = 'active';
2084: if (($tend) && ($tend<$now)) {
2085: $status = 'previous';
2086: }
2087: if (($tstart) && ($now<$tstart)) {
2088: $status = 'future';
2089: }
2090: if (ref($types) eq 'ARRAY') {
2091: if (!grep(/^\Q$status\E$/,@{$types})) {
2092: next;
2093: }
2094: } else {
2095: if ($status ne 'active') {
2096: next;
2097: }
2098: }
2099: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2100: if (ref($roledoms) eq 'ARRAY') {
2101: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2102: next;
2103: }
2104: }
2105: if (ref($roles) eq 'ARRAY') {
2106: if (!grep(/^\Q$role\E$/,@{$roles})) {
2107: next;
2108: }
2109: }
2110: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2111: }
2112: return %returnhash;
2113: }
2114:
2115: # ----------------------------------------------------- Frontpage Announcements
2116: #
2117: #
2118:
2119: sub postannounce {
2120: my ($server,$text)=@_;
2121: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2122: unless ($text=~/\w/) { $text=''; }
2123: return &reply('setannounce:'.&escape($text),$server);
2124: }
2125:
2126: sub getannounce {
2127:
2128: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2129: my $announcement='';
2130: while (my $line = <$fh>) { $announcement .= $line; }
2131: close($fh);
2132: if ($announcement=~/\w/) {
2133: return
2134: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2135: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2136: } else {
2137: return '';
2138: }
2139: } else {
2140: return '';
2141: }
2142: }
2143:
2144: # ---------------------------------------------------------- Course ID routines
2145: # Deal with domain's nohist_courseid.db files
2146: #
2147:
2148: sub courseidput {
2149: my ($domain,$what,$coursehome)=@_;
2150: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2151: }
2152:
2153: sub courseiddump {
2154: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
2155: my %returnhash=();
2156: unless ($domfilter) { $domfilter=''; }
2157: my %libserv = &all_library();
2158: foreach my $tryserver (keys(%libserv)) {
2159: if ( ( $hostidflag == 1
2160: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2161: || (!defined($hostidflag)) ) {
2162:
2163: if ($domfilter eq ''
2164: || (&host_domain($tryserver) eq $domfilter)) {
2165: foreach my $line (
2166: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
2167: $sincefilter.':'.&escape($descfilter).':'.
2168: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
2169: $tryserver))) {
2170: my ($key,$value)=split(/\=/,$line,2);
2171: if (($key) && ($value)) {
2172: $returnhash{&unescape($key)}=$value;
2173: }
2174: }
2175: }
2176: }
2177: }
2178: return %returnhash;
2179: }
2180:
2181: # ---------------------------------------------------------- DC e-mail
2182:
2183: sub dcmailput {
2184: my ($domain,$msgid,$message,$server)=@_;
2185: my $status = &Apache::lonnet::critical(
2186: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2187: &escape($message),$server);
2188: return $status;
2189: }
2190:
2191: sub dcmaildump {
2192: my ($dom,$startdate,$enddate,$senders) = @_;
2193: my %returnhash=();
2194:
2195: if (defined(&domain($dom,'primary'))) {
2196: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2197: &escape($enddate).':';
2198: my @esc_senders=map { &escape($_)} @$senders;
2199: $cmd.=&escape(join('&',@esc_senders));
2200: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
2201: my ($key,$value) = split(/\=/,$line,2);
2202: if (($key) && ($value)) {
2203: $returnhash{&unescape($key)} = &unescape($value);
2204: }
2205: }
2206: }
2207: return %returnhash;
2208: }
2209: # ---------------------------------------------------------- Domain roles
2210:
2211: sub get_domain_roles {
2212: my ($dom,$roles,$startdate,$enddate)=@_;
2213: if (undef($startdate) || $startdate eq '') {
2214: $startdate = '.';
2215: }
2216: if (undef($enddate) || $enddate eq '') {
2217: $enddate = '.';
2218: }
2219: my $rolelist = join(':',@{$roles});
2220: my %personnel = ();
2221:
2222: my %servers = &get_servers($dom,'library');
2223: foreach my $tryserver (keys(%servers)) {
2224: %{$personnel{$tryserver}}=();
2225: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2226: &escape($startdate).':'.
2227: &escape($enddate).':'.
2228: &escape($rolelist), $tryserver))) {
2229: my ($key,$value) = split(/\=/,$line,2);
2230: if (($key) && ($value)) {
2231: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2232: }
2233: }
2234: }
2235: return %personnel;
2236: }
2237:
2238: # ----------------------------------------------------------- Check out an item
2239:
2240: sub get_first_access {
2241: my ($type,$argsymb)=@_;
2242: my ($symb,$courseid,$udom,$uname)=&whichuser();
2243: if ($argsymb) { $symb=$argsymb; }
2244: my ($map,$id,$res)=&decode_symb($symb);
2245: if ($type eq 'map') {
2246: $res=&symbread($map);
2247: } else {
2248: $res=$symb;
2249: }
2250: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2251: return $times{"$courseid\0$res"};
2252: }
2253:
2254: sub set_first_access {
2255: my ($type)=@_;
2256: my ($symb,$courseid,$udom,$uname)=&whichuser();
2257: my ($map,$id,$res)=&decode_symb($symb);
2258: if ($type eq 'map') {
2259: $res=&symbread($map);
2260: } else {
2261: $res=$symb;
2262: }
2263: my $firstaccess=&get_first_access($type,$symb);
2264: if (!$firstaccess) {
2265: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2266: }
2267: return 'already_set';
2268: }
2269:
2270: sub checkout {
2271: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2272: my $now=time;
2273: my $lonhost=$perlvar{'lonHostID'};
2274: my $infostr=&escape(
2275: 'CHECKOUTTOKEN&'.
2276: $tuname.'&'.
2277: $tudom.'&'.
2278: $tcrsid.'&'.
2279: $symb.'&'.
2280: $now.'&'.$ENV{'REMOTE_ADDR'});
2281: my $token=&reply('tmpput:'.$infostr,$lonhost);
2282: if ($token=~/^error\:/) {
2283: &logthis("<font color=\"blue\">WARNING: ".
2284: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2285: "</font>");
2286: return '';
2287: }
2288:
2289: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2290: $token=~tr/a-z/A-Z/;
2291:
2292: my %infohash=('resource.0.outtoken' => $token,
2293: 'resource.0.checkouttime' => $now,
2294: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2295:
2296: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2297: return '';
2298: } else {
2299: &logthis("<font color=\"blue\">WARNING: ".
2300: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2301: "</font>");
2302: }
2303:
2304: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2305: &escape('Checkout '.$infostr.' - '.
2306: $token)) ne 'ok') {
2307: return '';
2308: } else {
2309: &logthis("<font color=\"blue\">WARNING: ".
2310: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2311: "</font>");
2312: }
2313: return $token;
2314: }
2315:
2316: # ------------------------------------------------------------ Check in an item
2317:
2318: sub checkin {
2319: my $token=shift;
2320: my $now=time;
2321: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2322: $lonhost=~tr/A-Z/a-z/;
2323: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
2324: $dtoken=~s/\W/\_/g;
2325: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2326: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2327:
2328: unless (($tuname) && ($tudom)) {
2329: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2330: return '';
2331: }
2332:
2333: unless (&allowed('mgr',$tcrsid)) {
2334: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
2335: $env{'user.name'}.' - '.$env{'user.domain'});
2336: return '';
2337: }
2338:
2339: my %infohash=('resource.0.intoken' => $token,
2340: 'resource.0.checkintime' => $now,
2341: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
2342:
2343: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2344: return '';
2345: }
2346:
2347: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2348: &escape('Checkin - '.$token)) ne 'ok') {
2349: return '';
2350: }
2351:
2352: return ($symb,$tuname,$tudom,$tcrsid);
2353: }
2354:
2355: # --------------------------------------------- Set Expire Date for Spreadsheet
2356:
2357: sub expirespread {
2358: my ($uname,$udom,$stype,$usymb)=@_;
2359: my $cid=$env{'request.course.id'};
2360: if ($cid) {
2361: my $now=time;
2362: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2363: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2364: $env{'course.'.$cid.'.num'}.
2365: ':nohist_expirationdates:'.
2366: &escape($key).'='.$now,
2367: $env{'course.'.$cid.'.home'})
2368: }
2369: return 'ok';
2370: }
2371:
2372: # ----------------------------------------------------- Devalidate Spreadsheets
2373:
2374: sub devalidate {
2375: my ($symb,$uname,$udom)=@_;
2376: my $cid=$env{'request.course.id'};
2377: if ($cid) {
2378: # delete the stored spreadsheets for
2379: # - the student level sheet of this user in course's homespace
2380: # - the assessment level sheet for this resource
2381: # for this user in user's homespace
2382: # - current conditional state info
2383: my $key=$uname.':'.$udom.':';
2384: my $status=
2385: &del('nohist_calculatedsheets',
2386: [$key.'studentcalc:'],
2387: $env{'course.'.$cid.'.domain'},
2388: $env{'course.'.$cid.'.num'})
2389: .' '.
2390: &del('nohist_calculatedsheets_'.$cid,
2391: [$key.'assesscalc:'.$symb],$udom,$uname);
2392: unless ($status eq 'ok ok') {
2393: &logthis('Could not devalidate spreadsheet '.
2394: $uname.' at '.$udom.' for '.
2395: $symb.': '.$status);
2396: }
2397: &delenv('user.state.'.$cid);
2398: }
2399: }
2400:
2401: sub get_scalar {
2402: my ($string,$end) = @_;
2403: my $value;
2404: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2405: $value = $1;
2406: } elsif ($$string =~ s/^([^&]*?)&//) {
2407: $value = $1;
2408: }
2409: return &unescape($value);
2410: }
2411:
2412: sub array2str {
2413: my (@array) = @_;
2414: my $result=&arrayref2str(\@array);
2415: $result=~s/^__ARRAY_REF__//;
2416: $result=~s/__END_ARRAY_REF__$//;
2417: return $result;
2418: }
2419:
2420: sub arrayref2str {
2421: my ($arrayref) = @_;
2422: my $result='__ARRAY_REF__';
2423: foreach my $elem (@$arrayref) {
2424: if(ref($elem) eq 'ARRAY') {
2425: $result.=&arrayref2str($elem).'&';
2426: } elsif(ref($elem) eq 'HASH') {
2427: $result.=&hashref2str($elem).'&';
2428: } elsif(ref($elem)) {
2429: #print("Got a ref of ".(ref($elem))." skipping.");
2430: } else {
2431: $result.=&escape($elem).'&';
2432: }
2433: }
2434: $result=~s/\&$//;
2435: $result .= '__END_ARRAY_REF__';
2436: return $result;
2437: }
2438:
2439: sub hash2str {
2440: my (%hash) = @_;
2441: my $result=&hashref2str(\%hash);
2442: $result=~s/^__HASH_REF__//;
2443: $result=~s/__END_HASH_REF__$//;
2444: return $result;
2445: }
2446:
2447: sub hashref2str {
2448: my ($hashref)=@_;
2449: my $result='__HASH_REF__';
2450: foreach my $key (sort(keys(%$hashref))) {
2451: if (ref($key) eq 'ARRAY') {
2452: $result.=&arrayref2str($key).'=';
2453: } elsif (ref($key) eq 'HASH') {
2454: $result.=&hashref2str($key).'=';
2455: } elsif (ref($key)) {
2456: $result.='=';
2457: #print("Got a ref of ".(ref($key))." skipping.");
2458: } else {
2459: if ($key) {$result.=&escape($key).'=';} else { last; }
2460: }
2461:
2462: if(ref($hashref->{$key}) eq 'ARRAY') {
2463: $result.=&arrayref2str($hashref->{$key}).'&';
2464: } elsif(ref($hashref->{$key}) eq 'HASH') {
2465: $result.=&hashref2str($hashref->{$key}).'&';
2466: } elsif(ref($hashref->{$key})) {
2467: $result.='&';
2468: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
2469: } else {
2470: $result.=&escape($hashref->{$key}).'&';
2471: }
2472: }
2473: $result=~s/\&$//;
2474: $result .= '__END_HASH_REF__';
2475: return $result;
2476: }
2477:
2478: sub str2hash {
2479: my ($string)=@_;
2480: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2481: return %$hash;
2482: }
2483:
2484: sub str2hashref {
2485: my ($string) = @_;
2486:
2487: my %hash;
2488:
2489: if($string !~ /^__HASH_REF__/) {
2490: if (! ($string eq '' || !defined($string))) {
2491: $hash{'error'}='Not hash reference';
2492: }
2493: return (\%hash, $string);
2494: }
2495:
2496: $string =~ s/^__HASH_REF__//;
2497:
2498: while($string !~ /^__END_HASH_REF__/) {
2499: #key
2500: my $key='';
2501: if($string =~ /^__HASH_REF__/) {
2502: ($key, $string)=&str2hashref($string);
2503: if(defined($key->{'error'})) {
2504: $hash{'error'}='Bad data';
2505: return (\%hash, $string);
2506: }
2507: } elsif($string =~ /^__ARRAY_REF__/) {
2508: ($key, $string)=&str2arrayref($string);
2509: if($key->[0] eq 'Array reference error') {
2510: $hash{'error'}='Bad data';
2511: return (\%hash, $string);
2512: }
2513: } else {
2514: $string =~ s/^(.*?)=//;
2515: $key=&unescape($1);
2516: }
2517: $string =~ s/^=//;
2518:
2519: #value
2520: my $value='';
2521: if($string =~ /^__HASH_REF__/) {
2522: ($value, $string)=&str2hashref($string);
2523: if(defined($value->{'error'})) {
2524: $hash{'error'}='Bad data';
2525: return (\%hash, $string);
2526: }
2527: } elsif($string =~ /^__ARRAY_REF__/) {
2528: ($value, $string)=&str2arrayref($string);
2529: if($value->[0] eq 'Array reference error') {
2530: $hash{'error'}='Bad data';
2531: return (\%hash, $string);
2532: }
2533: } else {
2534: $value=&get_scalar(\$string,'__END_HASH_REF__');
2535: }
2536: $string =~ s/^&//;
2537:
2538: $hash{$key}=$value;
2539: }
2540:
2541: $string =~ s/^__END_HASH_REF__//;
2542:
2543: return (\%hash, $string);
2544: }
2545:
2546: sub str2array {
2547: my ($string)=@_;
2548: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2549: return @$array;
2550: }
2551:
2552: sub str2arrayref {
2553: my ($string) = @_;
2554: my @array;
2555:
2556: if($string !~ /^__ARRAY_REF__/) {
2557: if (! ($string eq '' || !defined($string))) {
2558: $array[0]='Array reference error';
2559: }
2560: return (\@array, $string);
2561: }
2562:
2563: $string =~ s/^__ARRAY_REF__//;
2564:
2565: while($string !~ /^__END_ARRAY_REF__/) {
2566: my $value='';
2567: if($string =~ /^__HASH_REF__/) {
2568: ($value, $string)=&str2hashref($string);
2569: if(defined($value->{'error'})) {
2570: $array[0] ='Array reference error';
2571: return (\@array, $string);
2572: }
2573: } elsif($string =~ /^__ARRAY_REF__/) {
2574: ($value, $string)=&str2arrayref($string);
2575: if($value->[0] eq 'Array reference error') {
2576: $array[0] ='Array reference error';
2577: return (\@array, $string);
2578: }
2579: } else {
2580: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2581: }
2582: $string =~ s/^&//;
2583:
2584: push(@array, $value);
2585: }
2586:
2587: $string =~ s/^__END_ARRAY_REF__//;
2588:
2589: return (\@array, $string);
2590: }
2591:
2592: # -------------------------------------------------------------------Temp Store
2593:
2594: sub tmpreset {
2595: my ($symb,$namespace,$domain,$stuname) = @_;
2596: if (!$symb) {
2597: $symb=&symbread();
2598: if (!$symb) { $symb= $env{'request.url'}; }
2599: }
2600: $symb=escape($symb);
2601:
2602: if (!$namespace) { $namespace=$env{'request.state'}; }
2603: $namespace=~s/\//\_/g;
2604: $namespace=~s/\W//g;
2605:
2606: if (!$domain) { $domain=$env{'user.domain'}; }
2607: if (!$stuname) { $stuname=$env{'user.name'}; }
2608: if ($domain eq 'public' && $stuname eq 'public') {
2609: $stuname=$ENV{'REMOTE_ADDR'};
2610: }
2611: my $path=$perlvar{'lonDaemons'}.'/tmp';
2612: my %hash;
2613: if (tie(%hash,'GDBM_File',
2614: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2615: &GDBM_WRCREAT(),0640)) {
2616: foreach my $key (keys %hash) {
2617: if ($key=~ /:$symb/) {
2618: delete($hash{$key});
2619: }
2620: }
2621: }
2622: }
2623:
2624: sub tmpstore {
2625: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2626:
2627: if (!$symb) {
2628: $symb=&symbread();
2629: if (!$symb) { $symb= $env{'request.url'}; }
2630: }
2631: $symb=escape($symb);
2632:
2633: if (!$namespace) {
2634: # I don't think we would ever want to store this for a course.
2635: # it seems this will only be used if we don't have a course.
2636: #$namespace=$env{'request.course.id'};
2637: #if (!$namespace) {
2638: $namespace=$env{'request.state'};
2639: #}
2640: }
2641: $namespace=~s/\//\_/g;
2642: $namespace=~s/\W//g;
2643: if (!$domain) { $domain=$env{'user.domain'}; }
2644: if (!$stuname) { $stuname=$env{'user.name'}; }
2645: if ($domain eq 'public' && $stuname eq 'public') {
2646: $stuname=$ENV{'REMOTE_ADDR'};
2647: }
2648: my $now=time;
2649: my %hash;
2650: my $path=$perlvar{'lonDaemons'}.'/tmp';
2651: if (tie(%hash,'GDBM_File',
2652: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2653: &GDBM_WRCREAT(),0640)) {
2654: $hash{"version:$symb"}++;
2655: my $version=$hash{"version:$symb"};
2656: my $allkeys='';
2657: foreach my $key (keys(%$storehash)) {
2658: $allkeys.=$key.':';
2659: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
2660: }
2661: $hash{"$version:$symb:timestamp"}=$now;
2662: $allkeys.='timestamp';
2663: $hash{"$version:keys:$symb"}=$allkeys;
2664: if (untie(%hash)) {
2665: return 'ok';
2666: } else {
2667: return "error:$!";
2668: }
2669: } else {
2670: return "error:$!";
2671: }
2672: }
2673:
2674: # -----------------------------------------------------------------Temp Restore
2675:
2676: sub tmprestore {
2677: my ($symb,$namespace,$domain,$stuname) = @_;
2678:
2679: if (!$symb) {
2680: $symb=&symbread();
2681: if (!$symb) { $symb= $env{'request.url'}; }
2682: }
2683: $symb=escape($symb);
2684:
2685: if (!$namespace) { $namespace=$env{'request.state'}; }
2686:
2687: if (!$domain) { $domain=$env{'user.domain'}; }
2688: if (!$stuname) { $stuname=$env{'user.name'}; }
2689: if ($domain eq 'public' && $stuname eq 'public') {
2690: $stuname=$ENV{'REMOTE_ADDR'};
2691: }
2692: my %returnhash;
2693: $namespace=~s/\//\_/g;
2694: $namespace=~s/\W//g;
2695: my %hash;
2696: my $path=$perlvar{'lonDaemons'}.'/tmp';
2697: if (tie(%hash,'GDBM_File',
2698: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2699: &GDBM_READER(),0640)) {
2700: my $version=$hash{"version:$symb"};
2701: $returnhash{'version'}=$version;
2702: my $scope;
2703: for ($scope=1;$scope<=$version;$scope++) {
2704: my $vkeys=$hash{"$scope:keys:$symb"};
2705: my @keys=split(/:/,$vkeys);
2706: my $key;
2707: $returnhash{"$scope:keys"}=$vkeys;
2708: foreach $key (@keys) {
2709: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2710: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2711: }
2712: }
2713: if (!(untie(%hash))) {
2714: return "error:$!";
2715: }
2716: } else {
2717: return "error:$!";
2718: }
2719: return %returnhash;
2720: }
2721:
2722: # ----------------------------------------------------------------------- Store
2723:
2724: sub store {
2725: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2726: my $home='';
2727:
2728: if ($stuname) { $home=&homeserver($stuname,$domain); }
2729:
2730: $symb=&symbclean($symb);
2731: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2732:
2733: if (!$domain) { $domain=$env{'user.domain'}; }
2734: if (!$stuname) { $stuname=$env{'user.name'}; }
2735:
2736: &devalidate($symb,$stuname,$domain);
2737:
2738: $symb=escape($symb);
2739: if (!$namespace) {
2740: unless ($namespace=$env{'request.course.id'}) {
2741: return '';
2742: }
2743: }
2744: if (!$home) { $home=$env{'user.home'}; }
2745:
2746: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2747: $$storehash{'host'}=$perlvar{'lonHostID'};
2748:
2749: my $namevalue='';
2750: foreach my $key (keys(%$storehash)) {
2751: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2752: }
2753: $namevalue=~s/\&$//;
2754: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2755: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2756: }
2757:
2758: # -------------------------------------------------------------- Critical Store
2759:
2760: sub cstore {
2761: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2762: my $home='';
2763:
2764: if ($stuname) { $home=&homeserver($stuname,$domain); }
2765:
2766: $symb=&symbclean($symb);
2767: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2768:
2769: if (!$domain) { $domain=$env{'user.domain'}; }
2770: if (!$stuname) { $stuname=$env{'user.name'}; }
2771:
2772: &devalidate($symb,$stuname,$domain);
2773:
2774: $symb=escape($symb);
2775: if (!$namespace) {
2776: unless ($namespace=$env{'request.course.id'}) {
2777: return '';
2778: }
2779: }
2780: if (!$home) { $home=$env{'user.home'}; }
2781:
2782: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2783: $$storehash{'host'}=$perlvar{'lonHostID'};
2784:
2785: my $namevalue='';
2786: foreach my $key (keys(%$storehash)) {
2787: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2788: }
2789: $namevalue=~s/\&$//;
2790: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2791: return critical
2792: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2793: }
2794:
2795: # --------------------------------------------------------------------- Restore
2796:
2797: sub restore {
2798: my ($symb,$namespace,$domain,$stuname) = @_;
2799: my $home='';
2800:
2801: if ($stuname) { $home=&homeserver($stuname,$domain); }
2802:
2803: if (!$symb) {
2804: unless ($symb=escape(&symbread())) { return ''; }
2805: } else {
2806: $symb=&escape(&symbclean($symb));
2807: }
2808: if (!$namespace) {
2809: unless ($namespace=$env{'request.course.id'}) {
2810: return '';
2811: }
2812: }
2813: if (!$domain) { $domain=$env{'user.domain'}; }
2814: if (!$stuname) { $stuname=$env{'user.name'}; }
2815: if (!$home) { $home=$env{'user.home'}; }
2816: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2817:
2818: my %returnhash=();
2819: foreach my $line (split(/\&/,$answer)) {
2820: my ($name,$value)=split(/\=/,$line);
2821: $returnhash{&unescape($name)}=&thaw_unescape($value);
2822: }
2823: my $version;
2824: for ($version=1;$version<=$returnhash{'version'};$version++) {
2825: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2826: $returnhash{$item}=$returnhash{$version.':'.$item};
2827: }
2828: }
2829: return %returnhash;
2830: }
2831:
2832: # ---------------------------------------------------------- Course Description
2833:
2834: sub coursedescription {
2835: my ($courseid,$args)=@_;
2836: $courseid=~s/^\///;
2837: $courseid=~s/\_/\//g;
2838: my ($cdomain,$cnum)=split(/\//,$courseid);
2839: my $chome=&homeserver($cnum,$cdomain);
2840: my $normalid=$cdomain.'_'.$cnum;
2841: # need to always cache even if we get errors otherwise we keep
2842: # trying and trying and trying to get the course description.
2843: my %envhash=();
2844: my %returnhash=();
2845:
2846: my $expiretime=600;
2847: if ($env{'request.course.id'} eq $normalid) {
2848: $expiretime=120;
2849: }
2850:
2851: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2852: if (!$args->{'freshen_cache'}
2853: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2854: foreach my $key (keys(%env)) {
2855: next if ($key !~ /^\Q$prefix\E(.*)/);
2856: my ($setting) = $1;
2857: $returnhash{$setting} = $env{$key};
2858: }
2859: return %returnhash;
2860: }
2861:
2862: # get the data agin
2863: if (!$args->{'one_time'}) {
2864: $envhash{'course.'.$normalid.'.last_cache'}=time;
2865: }
2866:
2867: if ($chome ne 'no_host') {
2868: %returnhash=&dump('environment',$cdomain,$cnum);
2869: if (!exists($returnhash{'con_lost'})) {
2870: $returnhash{'home'}= $chome;
2871: $returnhash{'domain'} = $cdomain;
2872: $returnhash{'num'} = $cnum;
2873: if (!defined($returnhash{'type'})) {
2874: $returnhash{'type'} = 'Course';
2875: }
2876: while (my ($name,$value) = each %returnhash) {
2877: $envhash{'course.'.$normalid.'.'.$name}=$value;
2878: }
2879: $returnhash{'url'}=&clutter($returnhash{'url'});
2880: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2881: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2882: $envhash{'course.'.$normalid.'.home'}=$chome;
2883: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2884: $envhash{'course.'.$normalid.'.num'}=$cnum;
2885: }
2886: }
2887: if (!$args->{'one_time'}) {
2888: &appenv(%envhash);
2889: }
2890: return %returnhash;
2891: }
2892:
2893: # -------------------------------------------------See if a user is privileged
2894:
2895: sub privileged {
2896: my ($username,$domain)=@_;
2897: my $rolesdump=&reply("dump:$domain:$username:roles",
2898: &homeserver($username,$domain));
2899: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2900: my $now=time;
2901: if ($rolesdump ne '') {
2902: foreach my $entry (split(/&/,$rolesdump)) {
2903: if ($entry!~/^rolesdef_/) {
2904: my ($area,$role)=split(/=/,$entry);
2905: $area=~s/\_\w\w$//;
2906: my ($trole,$tend,$tstart)=split(/_/,$role);
2907: if (($trole eq 'dc') || ($trole eq 'su')) {
2908: my $active=1;
2909: if ($tend) {
2910: if ($tend<$now) { $active=0; }
2911: }
2912: if ($tstart) {
2913: if ($tstart>$now) { $active=0; }
2914: }
2915: if ($active) { return 1; }
2916: }
2917: }
2918: }
2919: }
2920: return 0;
2921: }
2922:
2923: # -------------------------------------------------------- Get user privileges
2924:
2925: sub rolesinit {
2926: my ($domain,$username,$authhost)=@_;
2927: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
2928: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
2929: my %allroles=();
2930: my %allgroups=();
2931: my $now=time;
2932: my %userroles = ('user.login.time' => $now);
2933: my $group_privs;
2934:
2935: if ($rolesdump ne '') {
2936: foreach my $entry (split(/&/,$rolesdump)) {
2937: if ($entry!~/^rolesdef_/) {
2938: my ($area,$role)=split(/=/,$entry);
2939: $area=~s/\_\w\w$//;
2940: my ($trole,$tend,$tstart,$group_privs);
2941: if ($role=~/^cr/) {
2942: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
2943: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
2944: ($tend,$tstart)=split('_',$trest);
2945: } else {
2946: $trole=$role;
2947: }
2948: } elsif ($role =~ m|^gr/|) {
2949: ($trole,$tend,$tstart) = split(/_/,$role);
2950: ($trole,$group_privs) = split(/\//,$trole);
2951: $group_privs = &unescape($group_privs);
2952: } else {
2953: ($trole,$tend,$tstart)=split(/_/,$role);
2954: }
2955: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2956: $username);
2957: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
2958: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2959: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2960: if (($area ne '') && ($trole ne '')) {
2961: my $spec=$trole.'.'.$area;
2962: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2963: if ($trole =~ /^cr\//) {
2964: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2965: } elsif ($trole eq 'gr') {
2966: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
2967: } else {
2968: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2969: }
2970: }
2971: }
2972: }
2973: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2974: $userroles{'user.adv'} = $adv;
2975: $userroles{'user.author'} = $author;
2976: $env{'user.adv'}=$adv;
2977: }
2978: return \%userroles;
2979: }
2980:
2981: sub set_arearole {
2982: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2983: # log the associated role with the area
2984: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2985: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
2986: }
2987:
2988: sub custom_roleprivs {
2989: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2990: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2991: my $homsvr=homeserver($rauthor,$rdomain);
2992: if (&hostname($homsvr) ne '') {
2993: my ($rdummy,$roledef)=
2994: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2995: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2996: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2997: if (defined($syspriv)) {
2998: $$allroles{'cm./'}.=':'.$syspriv;
2999: $$allroles{$spec.'./'}.=':'.$syspriv;
3000: }
3001: if ($tdomain ne '') {
3002: if (defined($dompriv)) {
3003: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3004: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3005: }
3006: if (($trest ne '') && (defined($coursepriv))) {
3007: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3008: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3009: }
3010: }
3011: }
3012: }
3013: }
3014:
3015: sub group_roleprivs {
3016: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3017: my $access = 1;
3018: my $now = time;
3019: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3020: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3021: if ($access) {
3022: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3023: $$allgroups{$course}{$group} .=':'.$group_privs;
3024: }
3025: }
3026:
3027: sub standard_roleprivs {
3028: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3029: if (defined($pr{$trole.':s'})) {
3030: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3031: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3032: }
3033: if ($tdomain ne '') {
3034: if (defined($pr{$trole.':d'})) {
3035: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3036: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3037: }
3038: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3039: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3040: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3041: }
3042: }
3043: }
3044:
3045: sub set_userprivs {
3046: my ($userroles,$allroles,$allgroups) = @_;
3047: my $author=0;
3048: my $adv=0;
3049: my %grouproles = ();
3050: if (keys(%{$allgroups}) > 0) {
3051: foreach my $role (keys %{$allroles}) {
3052: my ($trole,$area,$sec,$extendedarea);
3053: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
3054: $trole = $1;
3055: $area = $2;
3056: $sec = $3;
3057: $extendedarea = $area.$sec;
3058: if (exists($$allgroups{$area})) {
3059: foreach my $group (keys(%{$$allgroups{$area}})) {
3060: my $spec = $trole.'.'.$extendedarea;
3061: $grouproles{$spec.'.'.$area.'/'.$group} =
3062: $$allgroups{$area}{$group};
3063: }
3064: }
3065: }
3066: }
3067: }
3068: foreach my $group (keys(%grouproles)) {
3069: $$allroles{$group} = $grouproles{$group};
3070: }
3071: foreach my $role (keys(%{$allroles})) {
3072: my %thesepriv;
3073: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3074: foreach my $item (split(/:/,$$allroles{$role})) {
3075: if ($item ne '') {
3076: my ($privilege,$restrictions)=split(/&/,$item);
3077: if ($restrictions eq '') {
3078: $thesepriv{$privilege}='F';
3079: } elsif ($thesepriv{$privilege} ne 'F') {
3080: $thesepriv{$privilege}.=$restrictions;
3081: }
3082: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3083: }
3084: }
3085: my $thesestr='';
3086: foreach my $priv (keys(%thesepriv)) {
3087: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3088: }
3089: $userroles->{'user.priv.'.$role} = $thesestr;
3090: }
3091: return ($author,$adv);
3092: }
3093:
3094: # --------------------------------------------------------------- get interface
3095:
3096: sub get {
3097: my ($namespace,$storearr,$udomain,$uname)=@_;
3098: my $items='';
3099: foreach my $item (@$storearr) {
3100: $items.=&escape($item).'&';
3101: }
3102: $items=~s/\&$//;
3103: if (!$udomain) { $udomain=$env{'user.domain'}; }
3104: if (!$uname) { $uname=$env{'user.name'}; }
3105: my $uhome=&homeserver($uname,$udomain);
3106:
3107: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
3108: my @pairs=split(/\&/,$rep);
3109: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3110: return @pairs;
3111: }
3112: my %returnhash=();
3113: my $i=0;
3114: foreach my $item (@$storearr) {
3115: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3116: $i++;
3117: }
3118: return %returnhash;
3119: }
3120:
3121: # --------------------------------------------------------------- del interface
3122:
3123: sub del {
3124: my ($namespace,$storearr,$udomain,$uname)=@_;
3125: my $items='';
3126: foreach my $item (@$storearr) {
3127: $items.=&escape($item).'&';
3128: }
3129: $items=~s/\&$//;
3130: if (!$udomain) { $udomain=$env{'user.domain'}; }
3131: if (!$uname) { $uname=$env{'user.name'}; }
3132: my $uhome=&homeserver($uname,$udomain);
3133:
3134: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3135: }
3136:
3137: # -------------------------------------------------------------- dump interface
3138:
3139: sub dump {
3140: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3141: if (!$udomain) { $udomain=$env{'user.domain'}; }
3142: if (!$uname) { $uname=$env{'user.name'}; }
3143: my $uhome=&homeserver($uname,$udomain);
3144: if ($regexp) {
3145: $regexp=&escape($regexp);
3146: } else {
3147: $regexp='.';
3148: }
3149: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3150: my @pairs=split(/\&/,$rep);
3151: my %returnhash=();
3152: foreach my $item (@pairs) {
3153: my ($key,$value)=split(/=/,$item,2);
3154: $key = &unescape($key);
3155: next if ($key =~ /^error: 2 /);
3156: $returnhash{$key}=&thaw_unescape($value);
3157: }
3158: return %returnhash;
3159: }
3160:
3161: # --------------------------------------------------------- dumpstore interface
3162:
3163: sub dumpstore {
3164: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3165: if (!$udomain) { $udomain=$env{'user.domain'}; }
3166: if (!$uname) { $uname=$env{'user.name'}; }
3167: my $uhome=&homeserver($uname,$udomain);
3168: if ($regexp) {
3169: $regexp=&escape($regexp);
3170: } else {
3171: $regexp='.';
3172: }
3173: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3174: my @pairs=split(/\&/,$rep);
3175: my %returnhash=();
3176: foreach my $item (@pairs) {
3177: my ($key,$value)=split(/=/,$item,2);
3178: next if ($key =~ /^error: 2 /);
3179: $returnhash{$key}=&thaw_unescape($value);
3180: }
3181: return %returnhash;
3182: }
3183:
3184: # -------------------------------------------------------------- keys interface
3185:
3186: sub getkeys {
3187: my ($namespace,$udomain,$uname)=@_;
3188: if (!$udomain) { $udomain=$env{'user.domain'}; }
3189: if (!$uname) { $uname=$env{'user.name'}; }
3190: my $uhome=&homeserver($uname,$udomain);
3191: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3192: my @keyarray=();
3193: foreach my $key (split(/\&/,$rep)) {
3194: next if ($key =~ /^error: 2 /);
3195: push(@keyarray,&unescape($key));
3196: }
3197: return @keyarray;
3198: }
3199:
3200: # --------------------------------------------------------------- currentdump
3201: sub currentdump {
3202: my ($courseid,$sdom,$sname)=@_;
3203: $courseid = $env{'request.course.id'} if (! defined($courseid));
3204: $sdom = $env{'user.domain'} if (! defined($sdom));
3205: $sname = $env{'user.name'} if (! defined($sname));
3206: my $uhome = &homeserver($sname,$sdom);
3207: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3208: return if ($rep =~ /^(error:|no_such_host)/);
3209: #
3210: my %returnhash=();
3211: #
3212: if ($rep eq "unknown_cmd") {
3213: # an old lond will not know currentdump
3214: # Do a dump and make it look like a currentdump
3215: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
3216: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3217: my %hash = @tmp;
3218: @tmp=();
3219: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3220: } else {
3221: my @pairs=split(/\&/,$rep);
3222: foreach my $pair (@pairs) {
3223: my ($key,$value)=split(/=/,$pair,2);
3224: my ($symb,$param) = split(/:/,$key);
3225: $returnhash{&unescape($symb)}->{&unescape($param)} =
3226: &thaw_unescape($value);
3227: }
3228: }
3229: return %returnhash;
3230: }
3231:
3232: sub convert_dump_to_currentdump{
3233: my %hash = %{shift()};
3234: my %returnhash;
3235: # Code ripped from lond, essentially. The only difference
3236: # here is the unescaping done by lonnet::dump(). Conceivably
3237: # we might run in to problems with parameter names =~ /^v\./
3238: while (my ($key,$value) = each(%hash)) {
3239: my ($v,$symb,$param) = split(/:/,$key);
3240: $symb = &unescape($symb);
3241: $param = &unescape($param);
3242: next if ($v eq 'version' || $symb eq 'keys');
3243: next if (exists($returnhash{$symb}) &&
3244: exists($returnhash{$symb}->{$param}) &&
3245: $returnhash{$symb}->{'v.'.$param} > $v);
3246: $returnhash{$symb}->{$param}=$value;
3247: $returnhash{$symb}->{'v.'.$param}=$v;
3248: }
3249: #
3250: # Remove all of the keys in the hashes which keep track of
3251: # the version of the parameter.
3252: while (my ($symb,$param_hash) = each(%returnhash)) {
3253: # use a foreach because we are going to delete from the hash.
3254: foreach my $key (keys(%$param_hash)) {
3255: delete($param_hash->{$key}) if ($key =~ /^v\./);
3256: }
3257: }
3258: return \%returnhash;
3259: }
3260:
3261: # ------------------------------------------------------ critical inc interface
3262:
3263: sub cinc {
3264: return &inc(@_,'critical');
3265: }
3266:
3267: # --------------------------------------------------------------- inc interface
3268:
3269: sub inc {
3270: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3271: if (!$udomain) { $udomain=$env{'user.domain'}; }
3272: if (!$uname) { $uname=$env{'user.name'}; }
3273: my $uhome=&homeserver($uname,$udomain);
3274: my $items='';
3275: if (! ref($store)) {
3276: # got a single value, so use that instead
3277: $items = &escape($store).'=&';
3278: } elsif (ref($store) eq 'SCALAR') {
3279: $items = &escape($$store).'=&';
3280: } elsif (ref($store) eq 'ARRAY') {
3281: $items = join('=&',map {&escape($_);} @{$store});
3282: } elsif (ref($store) eq 'HASH') {
3283: while (my($key,$value) = each(%{$store})) {
3284: $items.= &escape($key).'='.&escape($value).'&';
3285: }
3286: }
3287: $items=~s/\&$//;
3288: if ($critical) {
3289: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3290: } else {
3291: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3292: }
3293: }
3294:
3295: # --------------------------------------------------------------- put interface
3296:
3297: sub put {
3298: my ($namespace,$storehash,$udomain,$uname)=@_;
3299: if (!$udomain) { $udomain=$env{'user.domain'}; }
3300: if (!$uname) { $uname=$env{'user.name'}; }
3301: my $uhome=&homeserver($uname,$udomain);
3302: my $items='';
3303: foreach my $item (keys(%$storehash)) {
3304: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3305: }
3306: $items=~s/\&$//;
3307: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3308: }
3309:
3310: # ------------------------------------------------------------ newput interface
3311:
3312: sub newput {
3313: my ($namespace,$storehash,$udomain,$uname)=@_;
3314: if (!$udomain) { $udomain=$env{'user.domain'}; }
3315: if (!$uname) { $uname=$env{'user.name'}; }
3316: my $uhome=&homeserver($uname,$udomain);
3317: my $items='';
3318: foreach my $key (keys(%$storehash)) {
3319: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3320: }
3321: $items=~s/\&$//;
3322: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3323: }
3324:
3325: # --------------------------------------------------------- putstore interface
3326:
3327: sub putstore {
3328: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3329: if (!$udomain) { $udomain=$env{'user.domain'}; }
3330: if (!$uname) { $uname=$env{'user.name'}; }
3331: my $uhome=&homeserver($uname,$udomain);
3332: my $items='';
3333: foreach my $key (keys(%$storehash)) {
3334: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3335: }
3336: $items=~s/\&$//;
3337: my $esc_symb=&escape($symb);
3338: my $esc_v=&escape($version);
3339: my $reply =
3340: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3341: $uhome);
3342: if ($reply eq 'unknown_cmd') {
3343: # gfall back to way things use to be done
3344: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3345: $uname);
3346: }
3347: return $reply;
3348: }
3349:
3350: sub old_putstore {
3351: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3352: if (!$udomain) { $udomain=$env{'user.domain'}; }
3353: if (!$uname) { $uname=$env{'user.name'}; }
3354: my $uhome=&homeserver($uname,$udomain);
3355: my %newstorehash;
3356: foreach my $item (keys(%$storehash)) {
3357: my $key = $version.':'.&escape($symb).':'.$item;
3358: $newstorehash{$key} = $storehash->{$item};
3359: }
3360: my $items='';
3361: my %allitems = ();
3362: foreach my $item (keys(%newstorehash)) {
3363: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3364: my $key = $1.':keys:'.$2;
3365: $allitems{$key} .= $3.':';
3366: }
3367: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
3368: }
3369: foreach my $item (keys(%allitems)) {
3370: $allitems{$item} =~ s/\:$//;
3371: $items.= $item.'='.$allitems{$item}.'&';
3372: }
3373: $items=~s/\&$//;
3374: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3375: }
3376:
3377: # ------------------------------------------------------ critical put interface
3378:
3379: sub cput {
3380: my ($namespace,$storehash,$udomain,$uname)=@_;
3381: if (!$udomain) { $udomain=$env{'user.domain'}; }
3382: if (!$uname) { $uname=$env{'user.name'}; }
3383: my $uhome=&homeserver($uname,$udomain);
3384: my $items='';
3385: foreach my $item (keys(%$storehash)) {
3386: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3387: }
3388: $items=~s/\&$//;
3389: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3390: }
3391:
3392: # -------------------------------------------------------------- eget interface
3393:
3394: sub eget {
3395: my ($namespace,$storearr,$udomain,$uname)=@_;
3396: my $items='';
3397: foreach my $item (@$storearr) {
3398: $items.=&escape($item).'&';
3399: }
3400: $items=~s/\&$//;
3401: if (!$udomain) { $udomain=$env{'user.domain'}; }
3402: if (!$uname) { $uname=$env{'user.name'}; }
3403: my $uhome=&homeserver($uname,$udomain);
3404: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3405: my @pairs=split(/\&/,$rep);
3406: my %returnhash=();
3407: my $i=0;
3408: foreach my $item (@$storearr) {
3409: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3410: $i++;
3411: }
3412: return %returnhash;
3413: }
3414:
3415: # ------------------------------------------------------------ tmpput interface
3416: sub tmpput {
3417: my ($storehash,$server,$context)=@_;
3418: my $items='';
3419: foreach my $item (keys(%$storehash)) {
3420: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3421: }
3422: $items=~s/\&$//;
3423: if (defined($context)) {
3424: $items .= ':'.&escape($context);
3425: }
3426: return &reply("tmpput:$items",$server);
3427: }
3428:
3429: # ------------------------------------------------------------ tmpget interface
3430: sub tmpget {
3431: my ($token,$server)=@_;
3432: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3433: my $rep=&reply("tmpget:$token",$server);
3434: my %returnhash;
3435: foreach my $item (split(/\&/,$rep)) {
3436: my ($key,$value)=split(/=/,$item);
3437: $returnhash{&unescape($key)}=&thaw_unescape($value);
3438: }
3439: return %returnhash;
3440: }
3441:
3442: # ------------------------------------------------------------ tmpget interface
3443: sub tmpdel {
3444: my ($token,$server)=@_;
3445: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3446: return &reply("tmpdel:$token",$server);
3447: }
3448:
3449: # -------------------------------------------------- portfolio access checking
3450:
3451: sub portfolio_access {
3452: my ($requrl) = @_;
3453: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3454: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3455: if ($result) {
3456: my %setters;
3457: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3458: my ($startblock,$endblock) =
3459: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3460: if ($startblock && $endblock) {
3461: return 'B';
3462: }
3463: } else {
3464: my ($startblock,$endblock) =
3465: &Apache::loncommon::blockcheck(\%setters,'port');
3466: if ($startblock && $endblock) {
3467: return 'B';
3468: }
3469: }
3470: }
3471: if ($result eq 'ok') {
3472: return 'F';
3473: } elsif ($result =~ /^[^:]+:guest_/) {
3474: return 'A';
3475: }
3476: return '';
3477: }
3478:
3479: sub get_portfolio_access {
3480: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3481:
3482: if (!ref($access_hash)) {
3483: my $current_perms = &get_portfile_permissions($udom,$unum);
3484: my %access_controls = &get_access_controls($current_perms,$group,
3485: $file_name);
3486: $access_hash = $access_controls{$file_name};
3487: }
3488:
3489: my ($public,$guest,@domains,@users,@courses,@groups);
3490: my $now = time;
3491: if (ref($access_hash) eq 'HASH') {
3492: foreach my $key (keys(%{$access_hash})) {
3493: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3494: if ($start > $now) {
3495: next;
3496: }
3497: if ($end && $end<$now) {
3498: next;
3499: }
3500: if ($scope eq 'public') {
3501: $public = $key;
3502: last;
3503: } elsif ($scope eq 'guest') {
3504: $guest = $key;
3505: } elsif ($scope eq 'domains') {
3506: push(@domains,$key);
3507: } elsif ($scope eq 'users') {
3508: push(@users,$key);
3509: } elsif ($scope eq 'course') {
3510: push(@courses,$key);
3511: } elsif ($scope eq 'group') {
3512: push(@groups,$key);
3513: }
3514: }
3515: if ($public) {
3516: return 'ok';
3517: }
3518: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3519: if ($guest) {
3520: return $guest;
3521: }
3522: } else {
3523: if (@domains > 0) {
3524: foreach my $domkey (@domains) {
3525: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3526: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3527: return 'ok';
3528: }
3529: }
3530: }
3531: }
3532: if (@users > 0) {
3533: foreach my $userkey (@users) {
3534: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3535: return 'ok';
3536: }
3537: }
3538: }
3539: my %roleshash;
3540: my @courses_and_groups = @courses;
3541: push(@courses_and_groups,@groups);
3542: if (@courses_and_groups > 0) {
3543: my (%allgroups,%allroles);
3544: my ($start,$end,$role,$sec,$group);
3545: foreach my $envkey (%env) {
3546: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
3547: my $cid = $2.'_'.$3;
3548: if ($1 eq 'gr') {
3549: $group = $4;
3550: $allgroups{$cid}{$group} = $env{$envkey};
3551: } else {
3552: if ($4 eq '') {
3553: $sec = 'none';
3554: } else {
3555: $sec = $4;
3556: }
3557: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3558: }
3559: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
3560: my $cid = $2.'_'.$3;
3561: if ($4 eq '') {
3562: $sec = 'none';
3563: } else {
3564: $sec = $4;
3565: }
3566: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3567: }
3568: }
3569: if (keys(%allroles) == 0) {
3570: return;
3571: }
3572: foreach my $key (@courses_and_groups) {
3573: my %content = %{$$access_hash{$key}};
3574: my $cnum = $content{'number'};
3575: my $cdom = $content{'domain'};
3576: my $cid = $cdom.'_'.$cnum;
3577: if (!exists($allroles{$cid})) {
3578: next;
3579: }
3580: foreach my $role_id (keys(%{$content{'roles'}})) {
3581: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3582: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3583: my @status = @{$content{'roles'}{$role_id}{'access'}};
3584: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3585: foreach my $role (keys(%{$allroles{$cid}})) {
3586: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3587: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3588: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3589: if (grep/^all$/,@sections) {
3590: return 'ok';
3591: } else {
3592: if (grep/^$sec$/,@sections) {
3593: return 'ok';
3594: }
3595: }
3596: }
3597: }
3598: if (keys(%{$allgroups{$cid}}) == 0) {
3599: if (grep/^none$/,@groups) {
3600: return 'ok';
3601: }
3602: } else {
3603: if (grep/^all$/,@groups) {
3604: return 'ok';
3605: }
3606: foreach my $group (keys(%{$allgroups{$cid}})) {
3607: if (grep/^$group$/,@groups) {
3608: return 'ok';
3609: }
3610: }
3611: }
3612: }
3613: }
3614: }
3615: }
3616: }
3617: if ($guest) {
3618: return $guest;
3619: }
3620: }
3621: }
3622: return;
3623: }
3624:
3625: sub course_group_datechecker {
3626: my ($dates,$now,$status) = @_;
3627: my ($start,$end) = split(/\./,$dates);
3628: if (!$start && !$end) {
3629: return 'ok';
3630: }
3631: if (grep/^active$/,@{$status}) {
3632: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3633: return 'ok';
3634: }
3635: }
3636: if (grep/^previous$/,@{$status}) {
3637: if ($end > $now ) {
3638: return 'ok';
3639: }
3640: }
3641: if (grep/^future$/,@{$status}) {
3642: if ($start > $now) {
3643: return 'ok';
3644: }
3645: }
3646: return;
3647: }
3648:
3649: sub parse_portfolio_url {
3650: my ($url) = @_;
3651:
3652: my ($type,$udom,$unum,$group,$file_name);
3653:
3654: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
3655: $type = 1;
3656: $udom = $1;
3657: $unum = $2;
3658: $file_name = $3;
3659: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
3660: $type = 2;
3661: $udom = $1;
3662: $unum = $2;
3663: $group = $3;
3664: $file_name = $3.'/'.$4;
3665: }
3666: if (wantarray) {
3667: return ($type,$udom,$unum,$file_name,$group);
3668: }
3669: return $type;
3670: }
3671:
3672: sub is_portfolio_url {
3673: my ($url) = @_;
3674: return scalar(&parse_portfolio_url($url));
3675: }
3676:
3677: sub is_portfolio_file {
3678: my ($file) = @_;
3679: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
3680: return 1;
3681: }
3682: return;
3683: }
3684:
3685:
3686: # ---------------------------------------------- Custom access rule evaluation
3687:
3688: sub customaccess {
3689: my ($priv,$uri)=@_;
3690: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
3691: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
3692: $udom = &LONCAPA::clean_domain($udom);
3693: $ucrs = &LONCAPA::clean_username($ucrs);
3694: my $access=0;
3695: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3696: my ($effect,$realm,$role)=split(/\:/,$right);
3697: if ($role) {
3698: if ($role ne $urole) { next; }
3699: }
3700: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3701: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
3702: if ($tdom) {
3703: if ($tdom ne $udom) { next; }
3704: }
3705: if ($tcrs) {
3706: if ($tcrs ne $ucrs) { next; }
3707: }
3708: if ($tsec) {
3709: if ($tsec ne $usec) { next; }
3710: }
3711: $access=($effect eq 'allow');
3712: last;
3713: }
3714: if ($realm eq '' && $role eq '') {
3715: $access=($effect eq 'allow');
3716: }
3717: }
3718: return $access;
3719: }
3720:
3721: # ------------------------------------------------- Check for a user privilege
3722:
3723: sub allowed {
3724: my ($priv,$uri,$symb,$role)=@_;
3725: my $ver_orguri=$uri;
3726: $uri=&deversion($uri);
3727: my $orguri=$uri;
3728: $uri=&declutter($uri);
3729:
3730: if ($priv eq 'evb') {
3731: # Evade communication block restrictions for specified role in a course
3732: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3733: return $1;
3734: } else {
3735: return;
3736: }
3737: }
3738:
3739: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3740: # Free bre access to adm and meta resources
3741: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
3742: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3743: && ($priv eq 'bre')) {
3744: return 'F';
3745: }
3746:
3747: # Free bre access to user's own portfolio contents
3748: my ($space,$domain,$name,@dir)=split('/',$uri);
3749: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3750: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
3751: my %setters;
3752: my ($startblock,$endblock) =
3753: &Apache::loncommon::blockcheck(\%setters,'port');
3754: if ($startblock && $endblock) {
3755: return 'B';
3756: } else {
3757: return 'F';
3758: }
3759: }
3760:
3761: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
3762: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3763: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3764: if (exists($env{'request.course.id'})) {
3765: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3766: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3767: if (($domain eq $cdom) && ($name eq $cnum)) {
3768: my $courseprivid=$env{'request.course.id'};
3769: $courseprivid=~s/\_/\//;
3770: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3771: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3772: return $1;
3773: } else {
3774: if ($env{'request.course.sec'}) {
3775: $courseprivid.='/'.$env{'request.course.sec'};
3776: }
3777: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3778: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3779: return $2;
3780: }
3781: }
3782: }
3783: }
3784: }
3785:
3786: # Free bre to public access
3787:
3788: if ($priv eq 'bre') {
3789: my $copyright=&metadata($uri,'copyright');
3790: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3791: return 'F';
3792: }
3793: if ($copyright eq 'priv') {
3794: $uri=~/([^\/]+)\/([^\/]+)\//;
3795: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3796: return '';
3797: }
3798: }
3799: if ($copyright eq 'domain') {
3800: $uri=~/([^\/]+)\/([^\/]+)\//;
3801: unless (($env{'user.domain'} eq $1) ||
3802: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3803: return '';
3804: }
3805: }
3806: if ($env{'request.role'}=~ /li\.\//) {
3807: # Library role, so allow browsing of resources in this domain.
3808: return 'F';
3809: }
3810: if ($copyright eq 'custom') {
3811: unless (&customaccess($priv,$uri)) { return ''; }
3812: }
3813: }
3814: # Domain coordinator is trying to create a course
3815: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3816: # uri is the requested domain in this case.
3817: # comparison to 'request.role.domain' shows if the user has selected
3818: # a role of dc for the domain in question.
3819: return 'F' if ($uri eq $env{'request.role.domain'});
3820: }
3821:
3822: my $thisallowed='';
3823: my $statecond=0;
3824: my $courseprivid='';
3825:
3826: # Course
3827:
3828: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3829: $thisallowed.=$1;
3830: }
3831:
3832: # Domain
3833:
3834: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3835: =~/\Q$priv\E\&([^\:]*)/) {
3836: $thisallowed.=$1;
3837: }
3838:
3839: # Course: uri itself is a course
3840: my $courseuri=$uri;
3841: $courseuri=~s/\_(\d)/\/$1/;
3842: $courseuri=~s/^([^\/])/\/$1/;
3843:
3844: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3845: =~/\Q$priv\E\&([^\:]*)/) {
3846: $thisallowed.=$1;
3847: }
3848:
3849: # URI is an uploaded document for this course, default permissions don't matter
3850: # not allowing 'edit' access (editupload) to uploaded course docs
3851: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3852: $thisallowed='';
3853: my ($match)=&is_on_map($uri);
3854: if ($match) {
3855: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3856: =~/\Q$priv\E\&([^\:]*)/) {
3857: $thisallowed.=$1;
3858: }
3859: } else {
3860: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3861: if ($refuri) {
3862: if ($refuri =~ m|^/adm/|) {
3863: $thisallowed='F';
3864: } else {
3865: $refuri=&declutter($refuri);
3866: my ($match) = &is_on_map($refuri);
3867: if ($match) {
3868: $thisallowed='F';
3869: }
3870: }
3871: }
3872: }
3873: }
3874:
3875: if ($priv eq 'bre'
3876: && $thisallowed ne 'F'
3877: && $thisallowed ne '2'
3878: && &is_portfolio_url($uri)) {
3879: $thisallowed = &portfolio_access($uri);
3880: }
3881:
3882: # Full access at system, domain or course-wide level? Exit.
3883:
3884: if ($thisallowed=~/F/) {
3885: return 'F';
3886: }
3887:
3888: # If this is generating or modifying users, exit with special codes
3889:
3890: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3891: if (($priv eq 'cca') || ($priv eq 'caa')) {
3892: my ($audom,$auname)=split('/',$uri);
3893: # no author name given, so this just checks on the general right to make a co-author in this domain
3894: unless ($auname) { return $thisallowed; }
3895: # an author name is given, so we are about to actually make a co-author for a certain account
3896: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3897: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3898: ($audom ne $env{'request.role.domain'}))) { return ''; }
3899: }
3900: return $thisallowed;
3901: }
3902: #
3903: # Gathered so far: system, domain and course wide privileges
3904: #
3905: # Course: See if uri or referer is an individual resource that is part of
3906: # the course
3907:
3908: if ($env{'request.course.id'}) {
3909:
3910: $courseprivid=$env{'request.course.id'};
3911: if ($env{'request.course.sec'}) {
3912: $courseprivid.='/'.$env{'request.course.sec'};
3913: }
3914: $courseprivid=~s/\_/\//;
3915: my $checkreferer=1;
3916: my ($match,$cond)=&is_on_map($uri);
3917: if ($match) {
3918: $statecond=$cond;
3919: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3920: =~/\Q$priv\E\&([^\:]*)/) {
3921: $thisallowed.=$1;
3922: $checkreferer=0;
3923: }
3924: }
3925:
3926: if ($checkreferer) {
3927: my $refuri=$env{'httpref.'.$orguri};
3928: unless ($refuri) {
3929: foreach my $key (keys(%env)) {
3930: if ($key=~/^httpref\..*\*/) {
3931: my $pattern=$key;
3932: $pattern=~s/^httpref\.\/res\///;
3933: $pattern=~s/\*/\[\^\/\]\+/g;
3934: $pattern=~s/\//\\\//g;
3935: if ($orguri=~/$pattern/) {
3936: $refuri=$env{$key};
3937: }
3938: }
3939: }
3940: }
3941:
3942: if ($refuri) {
3943: $refuri=&declutter($refuri);
3944: my ($match,$cond)=&is_on_map($refuri);
3945: if ($match) {
3946: my $refstatecond=$cond;
3947: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3948: =~/\Q$priv\E\&([^\:]*)/) {
3949: $thisallowed.=$1;
3950: $uri=$refuri;
3951: $statecond=$refstatecond;
3952: }
3953: }
3954: }
3955: }
3956: }
3957:
3958: #
3959: # Gathered now: all privileges that could apply, and condition number
3960: #
3961: #
3962: # Full or no access?
3963: #
3964:
3965: if ($thisallowed=~/F/) {
3966: return 'F';
3967: }
3968:
3969: unless ($thisallowed) {
3970: return '';
3971: }
3972:
3973: # Restrictions exist, deal with them
3974: #
3975: # C:according to course preferences
3976: # R:according to resource settings
3977: # L:unless locked
3978: # X:according to user session state
3979: #
3980:
3981: # Possibly locked functionality, check all courses
3982: # Locks might take effect only after 10 minutes cache expiration for other
3983: # courses, and 2 minutes for current course
3984:
3985: my $envkey;
3986: if ($thisallowed=~/L/) {
3987: foreach $envkey (keys %env) {
3988: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3989: my $courseid=$2;
3990: my $roleid=$1.'.'.$2;
3991: $courseid=~s/^\///;
3992: my $expiretime=600;
3993: if ($env{'request.role'} eq $roleid) {
3994: $expiretime=120;
3995: }
3996: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3997: my $prefix='course.'.$cdom.'_'.$cnum.'.';
3998: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
3999: &coursedescription($courseid,{'freshen_cache' => 1});
4000: }
4001: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4002: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4003: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4004: &log($env{'user.domain'},$env{'user.name'},
4005: $env{'user.home'},
4006: 'Locked by res: '.$priv.' for '.$uri.' due to '.
4007: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4008: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4009: return '';
4010: }
4011: }
4012: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4013: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4014: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4015: &log($env{'user.domain'},$env{'user.name'},
4016: $env{'user.home'},
4017: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
4018: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4019: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4020: return '';
4021: }
4022: }
4023: }
4024: }
4025: }
4026:
4027: #
4028: # Rest of the restrictions depend on selected course
4029: #
4030:
4031: unless ($env{'request.course.id'}) {
4032: if ($thisallowed eq 'A') {
4033: return 'A';
4034: } elsif ($thisallowed eq 'B') {
4035: return 'B';
4036: } else {
4037: return '1';
4038: }
4039: }
4040:
4041: #
4042: # Now user is definitely in a course
4043: #
4044:
4045:
4046: # Course preferences
4047:
4048: if ($thisallowed=~/C/) {
4049: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4050: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4051: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
4052: =~/\Q$rolecode\E/) {
4053: if ($priv ne 'pch') {
4054: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4055: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4056: $env{'request.course.id'});
4057: }
4058: return '';
4059: }
4060:
4061: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
4062: =~/\Q$unamedom\E/) {
4063: if ($priv ne 'pch') {
4064: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4065: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4066: $env{'request.course.id'});
4067: }
4068: return '';
4069: }
4070: }
4071:
4072: # Resource preferences
4073:
4074: if ($thisallowed=~/R/) {
4075: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4076: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
4077: if ($priv ne 'pch') {
4078: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4079: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4080: }
4081: return '';
4082: }
4083: }
4084:
4085: # Restricted by state or randomout?
4086:
4087: if ($thisallowed=~/X/) {
4088: if ($env{'acc.randomout'}) {
4089: if (!$symb) { $symb=&symbread($uri,1); }
4090: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
4091: return '';
4092: }
4093: }
4094: if (&condval($statecond)) {
4095: return '2';
4096: } else {
4097: return '';
4098: }
4099: }
4100:
4101: if ($thisallowed eq 'A') {
4102: return 'A';
4103: } elsif ($thisallowed eq 'B') {
4104: return 'B';
4105: }
4106: return 'F';
4107: }
4108:
4109: sub split_uri_for_cond {
4110: my $uri=&deversion(&declutter(shift));
4111: my @uriparts=split(/\//,$uri);
4112: my $filename=pop(@uriparts);
4113: my $pathname=join('/',@uriparts);
4114: return ($pathname,$filename);
4115: }
4116: # --------------------------------------------------- Is a resource on the map?
4117:
4118: sub is_on_map {
4119: my ($pathname,$filename) = &split_uri_for_cond(shift);
4120: #Trying to find the conditional for the file
4121: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
4122: /\&\Q$filename\E\:([\d\|]+)\&/);
4123: if ($match) {
4124: return (1,$1);
4125: } else {
4126: return (0,0);
4127: }
4128: }
4129:
4130: # --------------------------------------------------------- Get symb from alias
4131:
4132: sub get_symb_from_alias {
4133: my $symb=shift;
4134: my ($map,$resid,$url)=&decode_symb($symb);
4135: # Already is a symb
4136: if ($url) { return $symb; }
4137: # Must be an alias
4138: my $aliassymb='';
4139: my %bighash;
4140: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
4141: &GDBM_READER(),0640)) {
4142: my $rid=$bighash{'mapalias_'.$symb};
4143: if ($rid) {
4144: my ($mapid,$resid)=split(/\./,$rid);
4145: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4146: $resid,$bighash{'src_'.$rid});
4147: }
4148: untie %bighash;
4149: }
4150: return $aliassymb;
4151: }
4152:
4153: # ----------------------------------------------------------------- Define Role
4154:
4155: sub definerole {
4156: if (allowed('mcr','/')) {
4157: my ($rolename,$sysrole,$domrole,$courole)=@_;
4158: foreach my $role (split(':',$sysrole)) {
4159: my ($crole,$cqual)=split(/\&/,$role);
4160: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4161: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4162: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4163: return "refused:s:$crole&$cqual";
4164: }
4165: }
4166: }
4167: foreach my $role (split(':',$domrole)) {
4168: my ($crole,$cqual)=split(/\&/,$role);
4169: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4170: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4171: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
4172: return "refused:d:$crole&$cqual";
4173: }
4174: }
4175: }
4176: foreach my $role (split(':',$courole)) {
4177: my ($crole,$cqual)=split(/\&/,$role);
4178: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4179: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4180: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4181: return "refused:c:$crole&$cqual";
4182: }
4183: }
4184: }
4185: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4186: "$env{'user.domain'}:$env{'user.name'}:".
4187: "rolesdef_$rolename=".
4188: escape($sysrole.'_'.$domrole.'_'.$courole);
4189: return reply($command,$env{'user.home'});
4190: } else {
4191: return 'refused';
4192: }
4193: }
4194:
4195: # ---------------- Make a metadata query against the network of library servers
4196:
4197: sub metadata_query {
4198: my ($query,$custom,$customshow,$server_array)=@_;
4199: my %rhash;
4200: my %libserv = &all_library();
4201: my @server_list = (defined($server_array) ? @$server_array
4202: : keys(%libserv) );
4203: for my $server (@server_list) {
4204: unless ($custom or $customshow) {
4205: my $reply=&reply("querysend:".&escape($query),$server);
4206: $rhash{$server}=$reply;
4207: }
4208: else {
4209: my $reply=&reply("querysend:".&escape($query).':'.
4210: &escape($custom).':'.&escape($customshow),
4211: $server);
4212: $rhash{$server}=$reply;
4213: }
4214: }
4215: return \%rhash;
4216: }
4217:
4218: # ----------------------------------------- Send log queries and wait for reply
4219:
4220: sub log_query {
4221: my ($uname,$udom,$query,%filters)=@_;
4222: my $uhome=&homeserver($uname,$udom);
4223: if ($uhome eq 'no_host') { return 'error: no_host'; }
4224: my $uhost=&hostname($uhome);
4225: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
4226: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4227: $uhome);
4228: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
4229: return get_query_reply($queryid);
4230: }
4231:
4232: # -------------------------- Update MySQL table for portfolio file
4233:
4234: sub update_portfolio_table {
4235: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
4236: my $homeserver = &homeserver($uname,$udom);
4237: my $queryid=
4238: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4239: ':'.&escape($file_name).':'.$action,$homeserver);
4240: my $reply = &get_query_reply($queryid);
4241: return $reply;
4242: }
4243:
4244: # ------- Request retrieval of institutional classlists for course(s)
4245:
4246: sub fetch_enrollment_query {
4247: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
4248: my $homeserver;
4249: my $maxtries = 1;
4250: if ($context eq 'automated') {
4251: $homeserver = $perlvar{'lonHostID'};
4252: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
4253: } else {
4254: $homeserver = &homeserver($cnum,$dom);
4255: }
4256: my $host=&hostname($homeserver);
4257: my $cmd = '';
4258: foreach my $affiliate (keys %{$affiliatesref}) {
4259: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4260: }
4261: $cmd =~ s/%%$//;
4262: $cmd = &escape($cmd);
4263: my $query = 'fetchenrollment';
4264: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
4265: unless ($queryid=~/^\Q$host\E\_/) {
4266: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4267: return 'error: '.$queryid;
4268: }
4269: my $reply = &get_query_reply($queryid);
4270: my $tries = 1;
4271: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4272: $reply = &get_query_reply($queryid);
4273: $tries ++;
4274: }
4275: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4276: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4277: } else {
4278: my @responses = split/:/,$reply;
4279: if ($homeserver eq $perlvar{'lonHostID'}) {
4280: foreach my $line (@responses) {
4281: my ($key,$value) = split(/=/,$line,2);
4282: $$replyref{$key} = $value;
4283: }
4284: } else {
4285: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
4286: foreach my $line (@responses) {
4287: my ($key,$value) = split(/=/,$line);
4288: $$replyref{$key} = $value;
4289: if ($value > 0) {
4290: foreach my $item (@{$$affiliatesref{$key}}) {
4291: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
4292: my $destname = $pathname.'/'.$filename;
4293: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
4294: if ($xml_classlist =~ /^error/) {
4295: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4296: } else {
4297: if ( open(FILE,">$destname") ) {
4298: print FILE &unescape($xml_classlist);
4299: close(FILE);
4300: } else {
4301: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
4302: }
4303: }
4304: }
4305: }
4306: }
4307: }
4308: return 'ok';
4309: }
4310: return 'error';
4311: }
4312:
4313: sub get_query_reply {
4314: my $queryid=shift;
4315: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4316: my $reply='';
4317: for (1..100) {
4318: sleep 2;
4319: if (-e $replyfile.'.end') {
4320: if (open(my $fh,$replyfile)) {
4321: $reply.=<$fh>;
4322: close($fh);
4323: } else { return 'error: reply_file_error'; }
4324: return &unescape($reply);
4325: }
4326: }
4327: return 'timeout:'.$queryid;
4328: }
4329:
4330: sub courselog_query {
4331: #
4332: # possible filters:
4333: # url: url or symb
4334: # username
4335: # domain
4336: # action: view, submit, grade
4337: # start: timestamp
4338: # end: timestamp
4339: #
4340: my (%filters)=@_;
4341: unless ($env{'request.course.id'}) { return 'no_course'; }
4342: if ($filters{'url'}) {
4343: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4344: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4345: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4346: }
4347: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4348: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4349: return &log_query($cname,$cdom,'courselog',%filters);
4350: }
4351:
4352: sub userlog_query {
4353: my ($uname,$udom,%filters)=@_;
4354: return &log_query($uname,$udom,'userlog',%filters);
4355: }
4356:
4357: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4358:
4359: sub auto_run {
4360: my ($cnum,$cdom) = @_;
4361: my $homeserver = &homeserver($cnum,$cdom);
4362: my $response = &reply('autorun:'.$cdom,$homeserver);
4363: return $response;
4364: }
4365:
4366: sub auto_get_sections {
4367: my ($cnum,$cdom,$inst_coursecode) = @_;
4368: my $homeserver = &homeserver($cnum,$cdom);
4369: my @secs = ();
4370: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
4371: unless ($response eq 'refused') {
4372: @secs = split/:/,$response;
4373: }
4374: return @secs;
4375: }
4376:
4377: sub auto_new_course {
4378: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4379: my $homeserver = &homeserver($cnum,$cdom);
4380: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
4381: return $response;
4382: }
4383:
4384: sub auto_validate_courseID {
4385: my ($cnum,$cdom,$inst_course_id) = @_;
4386: my $homeserver = &homeserver($cnum,$cdom);
4387: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
4388: return $response;
4389: }
4390:
4391: sub auto_create_password {
4392: my ($cnum,$cdom,$authparam) = @_;
4393: my $homeserver = &homeserver($cnum,$cdom);
4394: my $create_passwd = 0;
4395: my $authchk = '';
4396: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4397: if ($response eq 'refused') {
4398: $authchk = 'refused';
4399: } else {
4400: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4401: }
4402: return ($authparam,$create_passwd,$authchk);
4403: }
4404:
4405: sub auto_photo_permission {
4406: my ($cnum,$cdom,$students) = @_;
4407: my $homeserver = &homeserver($cnum,$cdom);
4408: my ($outcome,$perm_reqd,$conditions) =
4409: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
4410: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4411: return (undef,undef);
4412: }
4413: return ($outcome,$perm_reqd,$conditions);
4414: }
4415:
4416: sub auto_checkphotos {
4417: my ($uname,$udom,$pid) = @_;
4418: my $homeserver = &homeserver($uname,$udom);
4419: my ($result,$resulttype);
4420: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
4421: &escape($uname).':'.&escape($pid),
4422: $homeserver));
4423: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4424: return (undef,undef);
4425: }
4426: if ($outcome) {
4427: ($result,$resulttype) = split(/:/,$outcome);
4428: }
4429: return ($result,$resulttype);
4430: }
4431:
4432: sub auto_photochoice {
4433: my ($cnum,$cdom) = @_;
4434: my $homeserver = &homeserver($cnum,$cdom);
4435: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
4436: &escape($cdom),
4437: $homeserver)));
4438: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4439: return (undef,undef);
4440: }
4441: return ($update,$comment);
4442: }
4443:
4444: sub auto_photoupdate {
4445: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4446: my $homeserver = &homeserver($cnum,$dom);
4447: my $host=&hostname($homeserver);
4448: my $cmd = '';
4449: my $maxtries = 1;
4450: foreach my $affiliate (keys(%{$affiliatesref})) {
4451: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
4452: }
4453: $cmd =~ s/%%$//;
4454: $cmd = &escape($cmd);
4455: my $query = 'institutionalphotos';
4456: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4457: unless ($queryid=~/^\Q$host\E\_/) {
4458: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4459: return 'error: '.$queryid;
4460: }
4461: my $reply = &get_query_reply($queryid);
4462: my $tries = 1;
4463: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4464: $reply = &get_query_reply($queryid);
4465: $tries ++;
4466: }
4467: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4468: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4469: } else {
4470: my @responses = split(/:/,$reply);
4471: my $outcome = shift(@responses);
4472: foreach my $item (@responses) {
4473: my ($key,$value) = split(/=/,$item);
4474: $$photo{$key} = $value;
4475: }
4476: return $outcome;
4477: }
4478: return 'error';
4479: }
4480:
4481: sub auto_instcode_format {
4482: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4483: $cat_order) = @_;
4484: my $courses = '';
4485: my @homeservers;
4486: if ($caller eq 'global') {
4487: my %servers = &get_servers($codedom,'library');
4488: foreach my $tryserver (keys(%servers)) {
4489: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4490: push(@homeservers,$tryserver);
4491: }
4492: }
4493: } else {
4494: push(@homeservers,&homeserver($caller,$codedom));
4495: }
4496: foreach my $code (keys(%{$instcodes})) {
4497: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
4498: }
4499: chop($courses);
4500: my $ok_response = 0;
4501: my $response;
4502: while (@homeservers > 0 && $ok_response == 0) {
4503: my $server = shift(@homeservers);
4504: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4505: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4506: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
4507: split/:/,$response;
4508: %{$codes} = (%{$codes},&str2hash($codes_str));
4509: push(@{$codetitles},&str2array($codetitles_str));
4510: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4511: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4512: $ok_response = 1;
4513: }
4514: }
4515: if ($ok_response) {
4516: return 'ok';
4517: } else {
4518: return $response;
4519: }
4520: }
4521:
4522: sub auto_instcode_defaults {
4523: my ($domain,$returnhash,$code_order) = @_;
4524: my @homeservers;
4525:
4526: my %servers = &get_servers($domain,'library');
4527: foreach my $tryserver (keys(%servers)) {
4528: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4529: push(@homeservers,$tryserver);
4530: }
4531: }
4532:
4533: my $response;
4534: foreach my $server (@homeservers) {
4535: $response=&reply('autoinstcodedefaults:'.$domain,$server);
4536: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4537:
4538: foreach my $pair (split(/\&/,$response)) {
4539: my ($name,$value)=split(/\=/,$pair);
4540: if ($name eq 'code_order') {
4541: @{$code_order} = split(/\&/,&unescape($value));
4542: } else {
4543: $returnhash->{&unescape($name)}=&unescape($value);
4544: }
4545: }
4546: return 'ok';
4547: }
4548:
4549: return $response;
4550: }
4551:
4552: sub auto_validate_class_sec {
4553: my ($cdom,$cnum,$owner,$inst_class) = @_;
4554: my $homeserver = &homeserver($cnum,$cdom);
4555: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
4556: &escape($owner).':'.$cdom,$homeserver);
4557: return $response;
4558: }
4559:
4560: # ------------------------------------------------------- Course Group routines
4561:
4562: sub get_coursegroups {
4563: my ($cdom,$cnum,$group,$namespace) = @_;
4564: return(&dump($namespace,$cdom,$cnum,$group));
4565: }
4566:
4567: sub modify_coursegroup {
4568: my ($cdom,$cnum,$groupsettings) = @_;
4569: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4570: }
4571:
4572: sub toggle_coursegroup_status {
4573: my ($cdom,$cnum,$group,$action) = @_;
4574: my ($from_namespace,$to_namespace);
4575: if ($action eq 'delete') {
4576: $from_namespace = 'coursegroups';
4577: $to_namespace = 'deleted_groups';
4578: } else {
4579: $from_namespace = 'deleted_groups';
4580: $to_namespace = 'coursegroups';
4581: }
4582: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
4583: if (my $tmp = &error(%curr_group)) {
4584: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4585: return ('read error',$tmp);
4586: } else {
4587: my %savedsettings = %curr_group;
4588: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
4589: my $deloutcome;
4590: if ($result eq 'ok') {
4591: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
4592: } else {
4593: return ('write error',$result);
4594: }
4595: if ($deloutcome eq 'ok') {
4596: return 'ok';
4597: } else {
4598: return ('delete error',$deloutcome);
4599: }
4600: }
4601: }
4602:
4603: sub modify_group_roles {
4604: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4605: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4606: my $role = 'gr/'.&escape($userprivs);
4607: my ($uname,$udom) = split(/:/,$user);
4608: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
4609: if ($result eq 'ok') {
4610: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4611: }
4612: return $result;
4613: }
4614:
4615: sub modify_coursegroup_membership {
4616: my ($cdom,$cnum,$membership) = @_;
4617: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4618: return $result;
4619: }
4620:
4621: sub get_active_groups {
4622: my ($udom,$uname,$cdom,$cnum) = @_;
4623: my $now = time;
4624: my %groups = ();
4625: foreach my $key (keys(%env)) {
4626: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
4627: my ($start,$end) = split(/\./,$env{$key});
4628: if (($end!=0) && ($end<$now)) { next; }
4629: if (($start!=0) && ($start>$now)) { next; }
4630: if ($1 eq $cdom && $2 eq $cnum) {
4631: $groups{$3} = $env{$key} ;
4632: }
4633: }
4634: }
4635: return %groups;
4636: }
4637:
4638: sub get_group_membership {
4639: my ($cdom,$cnum,$group) = @_;
4640: return(&dump('groupmembership',$cdom,$cnum,$group));
4641: }
4642:
4643: sub get_users_groups {
4644: my ($udom,$uname,$courseid) = @_;
4645: my @usersgroups;
4646: my $cachetime=1800;
4647:
4648: my $hashid="$udom:$uname:$courseid";
4649: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4650: if (defined($cached)) {
4651: @usersgroups = split(/:/,$grouplist);
4652: } else {
4653: $grouplist = '';
4654: my $courseurl = &courseid_to_courseurl($courseid);
4655: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
4656: my $access_end = $env{'course.'.$courseid.
4657: '.default_enrollment_end_date'};
4658: my $now = time;
4659: foreach my $key (keys(%roleshash)) {
4660: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4661: my $group = $1;
4662: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4663: my $start = $2;
4664: my $end = $1;
4665: if ($start == -1) { next; } # deleted from group
4666: if (($start!=0) && ($start>$now)) { next; }
4667: if (($end!=0) && ($end<$now)) {
4668: if ($access_end && $access_end < $now) {
4669: if ($access_end - $end < 86400) {
4670: push(@usersgroups,$group);
4671: }
4672: }
4673: next;
4674: }
4675: push(@usersgroups,$group);
4676: }
4677: }
4678: }
4679: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4680: $grouplist = join(':',@usersgroups);
4681: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4682: }
4683: return @usersgroups;
4684: }
4685:
4686: sub devalidate_getgroups_cache {
4687: my ($udom,$uname,$cdom,$cnum)=@_;
4688: my $courseid = $cdom.'_'.$cnum;
4689:
4690: my $hashid="$udom:$uname:$courseid";
4691: &devalidate_cache_new('getgroups',$hashid);
4692: }
4693:
4694: # ------------------------------------------------------------------ Plain Text
4695:
4696: sub plaintext {
4697: my ($short,$type,$cid) = @_;
4698: if ($short =~ /^cr/) {
4699: return (split('/',$short))[-1];
4700: }
4701: if (!defined($cid)) {
4702: $cid = $env{'request.course.id'};
4703: }
4704: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4705: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4706: '.plaintext'});
4707: }
4708: my %rolenames = (
4709: Course => 'std',
4710: Group => 'alt1',
4711: );
4712: if (defined($type) &&
4713: defined($rolenames{$type}) &&
4714: defined($prp{$short}{$rolenames{$type}})) {
4715: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4716: } else {
4717: return &Apache::lonlocal::mt($prp{$short}{'std'});
4718: }
4719: }
4720:
4721: # ----------------------------------------------------------------- Assign Role
4722:
4723: sub assignrole {
4724: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4725: my $mrole;
4726: if ($role =~ /^cr\//) {
4727: my $cwosec=$url;
4728: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4729: unless (&allowed('ccr',$cwosec)) {
4730: &logthis('Refused custom assignrole: '.
4731: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4732: $env{'user.name'}.' at '.$env{'user.domain'});
4733: return 'refused';
4734: }
4735: $mrole='cr';
4736: } elsif ($role =~ /^gr\//) {
4737: my $cwogrp=$url;
4738: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
4739: unless (&allowed('mdg',$cwogrp)) {
4740: &logthis('Refused group assignrole: '.
4741: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4742: $env{'user.name'}.' at '.$env{'user.domain'});
4743: return 'refused';
4744: }
4745: $mrole='gr';
4746: } else {
4747: my $cwosec=$url;
4748: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
4749: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4750: &logthis('Refused assignrole: '.
4751: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4752: $env{'user.name'}.' at '.$env{'user.domain'});
4753: return 'refused';
4754: }
4755: $mrole=$role;
4756: }
4757: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4758: "$udom:$uname:$url".'_'."$mrole=$role";
4759: if ($end) { $command.='_'.$end; }
4760: if ($start) {
4761: if ($end) {
4762: $command.='_'.$start;
4763: } else {
4764: $command.='_0_'.$start;
4765: }
4766: }
4767: my $origstart = $start;
4768: my $origend = $end;
4769: # actually delete
4770: if ($deleteflag) {
4771: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4772: # modify command to delete the role
4773: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4774: "$udom:$uname:$url".'_'."$mrole";
4775: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4776: # set start and finish to negative values for userrolelog
4777: $start=-1;
4778: $end=-1;
4779: }
4780: }
4781: # send command
4782: my $answer=&reply($command,&homeserver($uname,$udom));
4783: # log new user role if status is ok
4784: if ($answer eq 'ok') {
4785: &userrolelog($role,$uname,$udom,$url,$start,$end);
4786: # for course roles, perform group memberships changes triggered by role change.
4787: unless ($role =~ /^gr/) {
4788: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4789: $origstart);
4790: }
4791: }
4792: return $answer;
4793: }
4794:
4795: # -------------------------------------------------- Modify user authentication
4796: # Overrides without validation
4797:
4798: sub modifyuserauth {
4799: my ($udom,$uname,$umode,$upass)=@_;
4800: my $uhome=&homeserver($uname,$udom);
4801: unless (&allowed('mau',$udom)) { return 'refused'; }
4802: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4803: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4804: ' in domain '.$env{'request.role.domain'});
4805: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4806: &escape($upass),$uhome);
4807: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4808: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4809: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4810: &log($udom,,$uname,$uhome,
4811: 'Authentication changed by '.$env{'user.domain'}.', '.
4812: $env{'user.name'}.', '.$umode.
4813: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4814: unless ($reply eq 'ok') {
4815: &logthis('Authentication mode error: '.$reply);
4816: return 'error: '.$reply;
4817: }
4818: return 'ok';
4819: }
4820:
4821: # --------------------------------------------------------------- Modify a user
4822:
4823: sub modifyuser {
4824: my ($udom, $uname, $uid,
4825: $umode, $upass, $first,
4826: $middle, $last, $gene,
4827: $forceid, $desiredhome, $email)=@_;
4828: $udom= &LONCAPA::clean_domain($udom);
4829: $uname=&LONCAPA::clean_username($uname);
4830: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4831: $umode.', '.$first.', '.$middle.', '.
4832: $last.', '.$gene.'(forceid: '.$forceid.')'.
4833: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4834: ' desiredhome not specified').
4835: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4836: ' in domain '.$env{'request.role.domain'});
4837: my $uhome=&homeserver($uname,$udom,'true');
4838: # ----------------------------------------------------------------- Create User
4839: if (($uhome eq 'no_host') &&
4840: (($umode && $upass) || ($umode eq 'localauth'))) {
4841: my $unhome='';
4842: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
4843: $unhome = $desiredhome;
4844: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4845: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4846: } else { # load balancing routine for determining $unhome
4847: my $loadm=10000000;
4848: my %servers = &get_servers($udom,'library');
4849: foreach my $tryserver (keys(%servers)) {
4850: my $answer=reply('load',$tryserver);
4851: if (($answer=~/\d+/) && ($answer<$loadm)) {
4852: $loadm=$answer;
4853: $unhome=$tryserver;
4854: }
4855: }
4856: }
4857: if (($unhome eq '') || ($unhome eq 'no_host')) {
4858: return 'error: unable to find a home server for '.$uname.
4859: ' in domain '.$udom;
4860: }
4861: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4862: &escape($upass),$unhome);
4863: unless ($reply eq 'ok') {
4864: return 'error: '.$reply;
4865: }
4866: $uhome=&homeserver($uname,$udom,'true');
4867: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4868: return 'error: unable verify users home machine.';
4869: }
4870: } # End of creation of new user
4871: # ---------------------------------------------------------------------- Add ID
4872: if ($uid) {
4873: $uid=~tr/A-Z/a-z/;
4874: my %uidhash=&idrget($udom,$uname);
4875: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4876: && (!$forceid)) {
4877: unless ($uid eq $uidhash{$uname}) {
4878: return 'error: user id "'.$uid.'" does not match '.
4879: 'current user id "'.$uidhash{$uname}.'".';
4880: }
4881: } else {
4882: &idput($udom,($uname => $uid));
4883: }
4884: }
4885: # -------------------------------------------------------------- Add names, etc
4886: my @tmp=&get('environment',
4887: ['firstname','middlename','lastname','generation'],
4888: $udom,$uname);
4889: my %names;
4890: if ($tmp[0] =~ m/^error:.*/) {
4891: %names=();
4892: } else {
4893: %names = @tmp;
4894: }
4895: #
4896: # Make sure to not trash student environment if instructor does not bother
4897: # to supply name and email information
4898: #
4899: if ($first) { $names{'firstname'} = $first; }
4900: if (defined($middle)) { $names{'middlename'} = $middle; }
4901: if ($last) { $names{'lastname'} = $last; }
4902: if (defined($gene)) { $names{'generation'} = $gene; }
4903: if ($email) {
4904: $email=~s/[^\w\@\.\-\,]//gs;
4905: if ($email=~/\@/) { $names{'notification'} = $email;
4906: $names{'critnotification'} = $email;
4907: $names{'permanentemail'} = $email; }
4908: }
4909: my $reply = &put('environment', \%names, $udom,$uname);
4910: if ($reply ne 'ok') { return 'error: '.$reply; }
4911: &devalidate_cache_new('namescache',$uname.':'.$udom);
4912: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
4913: $umode.', '.$first.', '.$middle.', '.
4914: $last.', '.$gene.' by '.
4915: $env{'user.name'}.' at '.$env{'user.domain'});
4916: return 'ok';
4917: }
4918:
4919: # -------------------------------------------------------------- Modify student
4920:
4921: sub modifystudent {
4922: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
4923: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
4924: if (!$cid) {
4925: unless ($cid=$env{'request.course.id'}) {
4926: return 'not_in_class';
4927: }
4928: }
4929: # --------------------------------------------------------------- Make the user
4930: my $reply=&modifyuser
4931: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
4932: $desiredhome,$email);
4933: unless ($reply eq 'ok') { return $reply; }
4934: # This will cause &modify_student_enrollment to get the uid from the
4935: # students environment
4936: $uid = undef if (!$forceid);
4937: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
4938: $gene,$usec,$end,$start,$type,$locktype,$cid);
4939: return $reply;
4940: }
4941:
4942: sub modify_student_enrollment {
4943: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
4944: my ($cdom,$cnum,$chome);
4945: if (!$cid) {
4946: unless ($cid=$env{'request.course.id'}) {
4947: return 'not_in_class';
4948: }
4949: $cdom=$env{'course.'.$cid.'.domain'};
4950: $cnum=$env{'course.'.$cid.'.num'};
4951: } else {
4952: ($cdom,$cnum)=split(/_/,$cid);
4953: }
4954: $chome=$env{'course.'.$cid.'.home'};
4955: if (!$chome) {
4956: $chome=&homeserver($cnum,$cdom);
4957: }
4958: if (!$chome) { return 'unknown_course'; }
4959: # Make sure the user exists
4960: my $uhome=&homeserver($uname,$udom);
4961: if (($uhome eq '') || ($uhome eq 'no_host')) {
4962: return 'error: no such user';
4963: }
4964: # Get student data if we were not given enough information
4965: if (!defined($first) || $first eq '' ||
4966: !defined($last) || $last eq '' ||
4967: !defined($uid) || $uid eq '' ||
4968: !defined($middle) || $middle eq '' ||
4969: !defined($gene) || $gene eq '') {
4970: # They did not supply us with enough data to enroll the student, so
4971: # we need to pick up more information.
4972: my %tmp = &get('environment',
4973: ['firstname','middlename','lastname', 'generation','id']
4974: ,$udom,$uname);
4975:
4976: #foreach my $key (keys(%tmp)) {
4977: # &logthis("key $key = ".$tmp{$key});
4978: #}
4979: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4980: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4981: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
4982: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
4983: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4984: }
4985: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
4986: my $reply=cput('classlist',
4987: {"$uname:$udom" =>
4988: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
4989: $cdom,$cnum);
4990: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4991: return 'error: '.$reply;
4992: } else {
4993: &devalidate_getsection_cache($udom,$uname,$cid);
4994: }
4995: # Add student role to user
4996: my $uurl='/'.$cid;
4997: $uurl=~s/\_/\//g;
4998: if ($usec) {
4999: $uurl.='/'.$usec;
5000: }
5001: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
5002: }
5003:
5004: sub format_name {
5005: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5006: my $name;
5007: if ($first ne 'lastname') {
5008: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5009: } else {
5010: if ($lastname=~/\S/) {
5011: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5012: $name=~s/\s+,/,/;
5013: } else {
5014: $name.= $firstname.' '.$middlename.' '.$generation;
5015: }
5016: }
5017: $name=~s/^\s+//;
5018: $name=~s/\s+$//;
5019: $name=~s/\s+/ /g;
5020: return $name;
5021: }
5022:
5023: # ------------------------------------------------- Write to course preferences
5024:
5025: sub writecoursepref {
5026: my ($courseid,%prefs)=@_;
5027: $courseid=~s/^\///;
5028: $courseid=~s/\_/\//g;
5029: my ($cdomain,$cnum)=split(/\//,$courseid);
5030: my $chome=homeserver($cnum,$cdomain);
5031: if (($chome eq '') || ($chome eq 'no_host')) {
5032: return 'error: no such course';
5033: }
5034: my $cstring='';
5035: foreach my $pref (keys(%prefs)) {
5036: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
5037: }
5038: $cstring=~s/\&$//;
5039: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5040: }
5041:
5042: # ---------------------------------------------------------- Make/modify course
5043:
5044: sub createcourse {
5045: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5046: $course_owner,$crstype)=@_;
5047: $url=&declutter($url);
5048: my $cid='';
5049: unless (&allowed('ccc',$udom)) {
5050: return 'refused';
5051: }
5052: # ------------------------------------------------------------------- Create ID
5053: my $uname=int(1+rand(9)).
5054: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5055: substr($$.time,0,5).unpack("H8",pack("I32",time)).
5056: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5057: # ----------------------------------------------- Make sure that does not exist
5058: my $uhome=&homeserver($uname,$udom,'true');
5059: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5060: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5061: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5062: $uhome=&homeserver($uname,$udom,'true');
5063: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5064: return 'error: unable to generate unique course-ID';
5065: }
5066: }
5067: # ------------------------------------------------ Check supplied server name
5068: $course_server = $env{'user.homeserver'} if (! defined($course_server));
5069: if (! &is_library($course_server)) {
5070: return 'error:bad server name '.$course_server;
5071: }
5072: # ------------------------------------------------------------- Make the course
5073: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
5074: $course_server);
5075: unless ($reply eq 'ok') { return 'error: '.$reply; }
5076: $uhome=&homeserver($uname,$udom,'true');
5077: if (($uhome eq '') || ($uhome eq 'no_host')) {
5078: return 'error: no such course';
5079: }
5080: # ----------------------------------------------------------------- Course made
5081: # log existence
5082: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
5083: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5084: &escape($crstype),$uhome);
5085: &flushcourselogs();
5086: # set toplevel url
5087: my $topurl=$url;
5088: unless ($nonstandard) {
5089: # ------------------------------------------ For standard courses, make top url
5090: my $mapurl=&clutter($url);
5091: if ($mapurl eq '/res/') { $mapurl=''; }
5092: $env{'form.initmap'}=(<<ENDINITMAP);
5093: <map>
5094: <resource id="1" type="start"></resource>
5095: <resource id="2" src="$mapurl"></resource>
5096: <resource id="3" type="finish"></resource>
5097: <link index="1" from="1" to="2"></link>
5098: <link index="2" from="2" to="3"></link>
5099: </map>
5100: ENDINITMAP
5101: $topurl=&declutter(
5102: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
5103: );
5104: }
5105: # ----------------------------------------------------------- Write preferences
5106: &writecoursepref($udom.'_'.$uname,
5107: ('description' => $description,
5108: 'url' => $topurl));
5109: return '/'.$udom.'/'.$uname;
5110: }
5111:
5112: sub is_course {
5113: my ($cdom,$cnum) = @_;
5114: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5115: undef,'.');
5116: if (exists($courses{$cdom.'_'.$cnum})) {
5117: return 1;
5118: }
5119: return 0;
5120: }
5121:
5122: # ---------------------------------------------------------- Assign Custom Role
5123:
5124: sub assigncustomrole {
5125: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
5126: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
5127: $end,$start,$deleteflag);
5128: }
5129:
5130: # ----------------------------------------------------------------- Revoke Role
5131:
5132: sub revokerole {
5133: my ($udom,$uname,$url,$role,$deleteflag)=@_;
5134: my $now=time;
5135: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
5136: }
5137:
5138: # ---------------------------------------------------------- Revoke Custom Role
5139:
5140: sub revokecustomrole {
5141: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
5142: my $now=time;
5143: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5144: $deleteflag);
5145: }
5146:
5147: # ------------------------------------------------------------ Disk usage
5148: sub diskusage {
5149: my ($udom,$uname,$directoryRoot)=@_;
5150: $directoryRoot =~ s/\/$//;
5151: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
5152: return $listing;
5153: }
5154:
5155: sub is_locked {
5156: my ($file_name, $domain, $user) = @_;
5157: my @check;
5158: my $is_locked;
5159: push @check, $file_name;
5160: my %locked = &get('file_permissions',\@check,
5161: $env{'user.domain'},$env{'user.name'});
5162: my ($tmp)=keys(%locked);
5163: if ($tmp=~/^error:/) { undef(%locked); }
5164:
5165: if (ref($locked{$file_name}) eq 'ARRAY') {
5166: $is_locked = 'false';
5167: foreach my $entry (@{$locked{$file_name}}) {
5168: if (ref($entry) eq 'ARRAY') {
5169: $is_locked = 'true';
5170: last;
5171: }
5172: }
5173: } else {
5174: $is_locked = 'false';
5175: }
5176: }
5177:
5178: sub declutter_portfile {
5179: my ($file) = @_;
5180: $file =~ s{^(/portfolio/|portfolio/)}{/};
5181: return $file;
5182: }
5183:
5184: # ------------------------------------------------------------- Mark as Read Only
5185:
5186: sub mark_as_readonly {
5187: my ($domain,$user,$files,$what) = @_;
5188: my %current_permissions = &dump('file_permissions',$domain,$user);
5189: my ($tmp)=keys(%current_permissions);
5190: if ($tmp=~/^error:/) { undef(%current_permissions); }
5191: foreach my $file (@{$files}) {
5192: $file = &declutter_portfile($file);
5193: push(@{$current_permissions{$file}},$what);
5194: }
5195: &put('file_permissions',\%current_permissions,$domain,$user);
5196: return;
5197: }
5198:
5199: # ------------------------------------------------------------Save Selected Files
5200:
5201: sub save_selected_files {
5202: my ($user, $path, @files) = @_;
5203: my $filename = $user."savedfiles";
5204: my @other_files = &files_not_in_path($user, $path);
5205: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5206: foreach my $file (@files) {
5207: print (OUT $env{'form.currentpath'}.$file."\n");
5208: }
5209: foreach my $file (@other_files) {
5210: print (OUT $file."\n");
5211: }
5212: close (OUT);
5213: return 'ok';
5214: }
5215:
5216: sub clear_selected_files {
5217: my ($user) = @_;
5218: my $filename = $user."savedfiles";
5219: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5220: print (OUT undef);
5221: close (OUT);
5222: return ("ok");
5223: }
5224:
5225: sub files_in_path {
5226: my ($user, $path) = @_;
5227: my $filename = $user."savedfiles";
5228: my %return_files;
5229: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5230: while (my $line_in = <IN>) {
5231: chomp ($line_in);
5232: my @paths_and_file = split (m!/!, $line_in);
5233: my $file_part = pop (@paths_and_file);
5234: my $path_part = join ('/', @paths_and_file);
5235: $path_part.='/';
5236: my $path_and_file = $path_part.$file_part;
5237: if ($path_part eq $path) {
5238: $return_files{$file_part}= 'selected';
5239: }
5240: }
5241: close (IN);
5242: return (\%return_files);
5243: }
5244:
5245: # called in portfolio select mode, to show files selected NOT in current directory
5246: sub files_not_in_path {
5247: my ($user, $path) = @_;
5248: my $filename = $user."savedfiles";
5249: my @return_files;
5250: my $path_part;
5251: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5252: while (my $line = <IN>) {
5253: #ok, I know it's clunky, but I want it to work
5254: my @paths_and_file = split(m|/|, $line);
5255: my $file_part = pop(@paths_and_file);
5256: chomp($file_part);
5257: my $path_part = join('/', @paths_and_file);
5258: $path_part .= '/';
5259: my $path_and_file = $path_part.$file_part;
5260: if ($path_part ne $path) {
5261: push(@return_files, ($path_and_file));
5262: }
5263: }
5264: close(OUT);
5265: return (@return_files);
5266: }
5267:
5268: #----------------------------------------------Get portfolio file permissions
5269:
5270: sub get_portfile_permissions {
5271: my ($domain,$user) = @_;
5272: my %current_permissions = &dump('file_permissions',$domain,$user);
5273: my ($tmp)=keys(%current_permissions);
5274: if ($tmp=~/^error:/) { undef(%current_permissions); }
5275: return \%current_permissions;
5276: }
5277:
5278: #---------------------------------------------Get portfolio file access controls
5279:
5280: sub get_access_controls {
5281: my ($current_permissions,$group,$file) = @_;
5282: my %access;
5283: my $real_file = $file;
5284: $file =~ s/\.meta$//;
5285: if (defined($file)) {
5286: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5287: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
5288: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
5289: }
5290: }
5291: } else {
5292: foreach my $key (keys(%{$current_permissions})) {
5293: if ($key =~ /\0accesscontrol$/) {
5294: if (defined($group)) {
5295: if ($key !~ m-^\Q$group\E/-) {
5296: next;
5297: }
5298: }
5299: my ($fullpath) = split(/\0/,$key);
5300: if (ref($$current_permissions{$key}) eq 'HASH') {
5301: foreach my $control (keys(%{$$current_permissions{$key}})) {
5302: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5303: }
5304: }
5305: }
5306: }
5307: }
5308: return %access;
5309: }
5310:
5311: sub modify_access_controls {
5312: my ($file_name,$changes,$domain,$user)=@_;
5313: my ($outcome,$deloutcome);
5314: my %store_permissions;
5315: my %new_values;
5316: my %new_control;
5317: my %translation;
5318: my @deletions = ();
5319: my $now = time;
5320: if (exists($$changes{'activate'})) {
5321: if (ref($$changes{'activate'}) eq 'HASH') {
5322: my @newitems = sort(keys(%{$$changes{'activate'}}));
5323: my $numnew = scalar(@newitems);
5324: for (my $i=0; $i<$numnew; $i++) {
5325: my $newkey = $newitems[$i];
5326: my $newid = &Apache::loncommon::get_cgi_id();
5327: if ($newkey =~ /^\d+:/) {
5328: $newkey =~ s/^(\d+)/$newid/;
5329: $translation{$1} = $newid;
5330: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5331: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5332: $translation{$1} = $newid;
5333: }
5334: $new_values{$file_name."\0".$newkey} =
5335: $$changes{'activate'}{$newitems[$i]};
5336: $new_control{$newkey} = $now;
5337: }
5338: }
5339: }
5340: my %todelete;
5341: my %changed_items;
5342: foreach my $action ('delete','update') {
5343: if (exists($$changes{$action})) {
5344: if (ref($$changes{$action}) eq 'HASH') {
5345: foreach my $key (keys(%{$$changes{$action}})) {
5346: my ($itemnum) = ($key =~ /^([^:]+):/);
5347: if ($action eq 'delete') {
5348: $todelete{$itemnum} = 1;
5349: } else {
5350: $changed_items{$itemnum} = $key;
5351: }
5352: }
5353: }
5354: }
5355: }
5356: # get lock on access controls for file.
5357: my $lockhash = {
5358: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5359: ':'.$env{'user.domain'},
5360: };
5361: my $tries = 0;
5362: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5363:
5364: while (($gotlock ne 'ok') && $tries <3) {
5365: $tries ++;
5366: sleep 1;
5367: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5368: }
5369: if ($gotlock eq 'ok') {
5370: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5371: my ($tmp)=keys(%curr_permissions);
5372: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5373: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5374: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5375: if (ref($curr_controls) eq 'HASH') {
5376: foreach my $control_item (keys(%{$curr_controls})) {
5377: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5378: if (defined($todelete{$itemnum})) {
5379: push(@deletions,$file_name."\0".$control_item);
5380: } else {
5381: if (defined($changed_items{$itemnum})) {
5382: $new_control{$changed_items{$itemnum}} = $now;
5383: push(@deletions,$file_name."\0".$control_item);
5384: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5385: } else {
5386: $new_control{$control_item} = $$curr_controls{$control_item};
5387: }
5388: }
5389: }
5390: }
5391: }
5392: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5393: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5394: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5395: # remove lock
5396: my @del_lock = ($file_name."\0".'locked_access_records');
5397: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5398: my ($file,$group);
5399: if (&is_course($domain,$user)) {
5400: ($group,$file) = split(/\//,$file_name,2);
5401: } else {
5402: $file = $file_name;
5403: }
5404: my $sqlresult =
5405: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5406: $group);
5407: } else {
5408: $outcome = "error: could not obtain lockfile\n";
5409: }
5410: return ($outcome,$deloutcome,\%new_values,\%translation);
5411: }
5412:
5413: sub make_public_indefinitely {
5414: my ($requrl) = @_;
5415: my $now = time;
5416: my $action = 'activate';
5417: my $aclnum = 0;
5418: if (&is_portfolio_url($requrl)) {
5419: my (undef,$udom,$unum,$file_name,$group) =
5420: &parse_portfolio_url($requrl);
5421: my $current_perms = &get_portfile_permissions($udom,$unum);
5422: my %access_controls = &get_access_controls($current_perms,
5423: $group,$file_name);
5424: foreach my $key (keys(%{$access_controls{$file_name}})) {
5425: my ($num,$scope,$end,$start) =
5426: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5427: if ($scope eq 'public') {
5428: if ($start <= $now && $end == 0) {
5429: $action = 'none';
5430: } else {
5431: $action = 'update';
5432: $aclnum = $num;
5433: }
5434: last;
5435: }
5436: }
5437: if ($action eq 'none') {
5438: return 'ok';
5439: } else {
5440: my %changes;
5441: my $newend = 0;
5442: my $newstart = $now;
5443: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5444: $changes{$action}{$newkey} = {
5445: type => 'public',
5446: time => {
5447: start => $newstart,
5448: end => $newend,
5449: },
5450: };
5451: my ($outcome,$deloutcome,$new_values,$translation) =
5452: &modify_access_controls($file_name,\%changes,$udom,$unum);
5453: return $outcome;
5454: }
5455: } else {
5456: return 'invalid';
5457: }
5458: }
5459:
5460: #------------------------------------------------------Get Marked as Read Only
5461:
5462: sub get_marked_as_readonly {
5463: my ($domain,$user,$what,$group) = @_;
5464: my $current_permissions = &get_portfile_permissions($domain,$user);
5465: my @readonly_files;
5466: my $cmp1=$what;
5467: if (ref($what)) { $cmp1=join('',@{$what}) };
5468: while (my ($file_name,$value) = each(%{$current_permissions})) {
5469: if (defined($group)) {
5470: if ($file_name !~ m-^\Q$group\E/-) {
5471: next;
5472: }
5473: }
5474: if (ref($value) eq "ARRAY"){
5475: foreach my $stored_what (@{$value}) {
5476: my $cmp2=$stored_what;
5477: if (ref($stored_what) eq 'ARRAY') {
5478: $cmp2=join('',@{$stored_what});
5479: }
5480: if ($cmp1 eq $cmp2) {
5481: push(@readonly_files, $file_name);
5482: last;
5483: } elsif (!defined($what)) {
5484: push(@readonly_files, $file_name);
5485: last;
5486: }
5487: }
5488: }
5489: }
5490: return @readonly_files;
5491: }
5492: #-----------------------------------------------------------Get Marked as Read Only Hash
5493:
5494: sub get_marked_as_readonly_hash {
5495: my ($current_permissions,$group,$what) = @_;
5496: my %readonly_files;
5497: while (my ($file_name,$value) = each(%{$current_permissions})) {
5498: if (defined($group)) {
5499: if ($file_name !~ m-^\Q$group\E/-) {
5500: next;
5501: }
5502: }
5503: if (ref($value) eq "ARRAY"){
5504: foreach my $stored_what (@{$value}) {
5505: if (ref($stored_what) eq 'ARRAY') {
5506: foreach my $lock_descriptor(@{$stored_what}) {
5507: if ($lock_descriptor eq 'graded') {
5508: $readonly_files{$file_name} = 'graded';
5509: } elsif ($lock_descriptor eq 'handback') {
5510: $readonly_files{$file_name} = 'handback';
5511: } else {
5512: if (!exists($readonly_files{$file_name})) {
5513: $readonly_files{$file_name} = 'locked';
5514: }
5515: }
5516: }
5517: }
5518: }
5519: }
5520: }
5521: return %readonly_files;
5522: }
5523: # ------------------------------------------------------------ Unmark as Read Only
5524:
5525: sub unmark_as_readonly {
5526: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5527: # for portfolio submissions, $what contains [$symb,$crsid]
5528: my ($domain,$user,$what,$file_name,$group) = @_;
5529: $file_name = &declutter_portfile($file_name);
5530: my $symb_crs = $what;
5531: if (ref($what)) { $symb_crs=join('',@$what); }
5532: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
5533: my ($tmp)=keys(%current_permissions);
5534: if ($tmp=~/^error:/) { undef(%current_permissions); }
5535: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
5536: foreach my $file (@readonly_files) {
5537: my $clean_file = &declutter_portfile($file);
5538: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
5539: my $current_locks = $current_permissions{$file};
5540: my @new_locks;
5541: my @del_keys;
5542: if (ref($current_locks) eq "ARRAY"){
5543: foreach my $locker (@{$current_locks}) {
5544: my $compare=$locker;
5545: if (ref($locker) eq 'ARRAY') {
5546: $compare=join('',@{$locker});
5547: if ($compare ne $symb_crs) {
5548: push(@new_locks, $locker);
5549: }
5550: }
5551: }
5552: if (scalar(@new_locks) > 0) {
5553: $current_permissions{$file} = \@new_locks;
5554: } else {
5555: push(@del_keys, $file);
5556: &del('file_permissions',\@del_keys, $domain, $user);
5557: delete($current_permissions{$file});
5558: }
5559: }
5560: }
5561: &put('file_permissions',\%current_permissions,$domain,$user);
5562: return;
5563: }
5564:
5565: # ------------------------------------------------------------ Directory lister
5566:
5567: sub dirlist {
5568: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5569:
5570: $uri=~s/^\///;
5571: $uri=~s/\/$//;
5572: my ($udom, $uname);
5573: (undef,$udom,$uname)=split(/\//,$uri);
5574: if(defined($userdomain)) {
5575: $udom = $userdomain;
5576: }
5577: if(defined($username)) {
5578: $uname = $username;
5579: }
5580:
5581: my $dirRoot = $perlvar{'lonDocRoot'};
5582: if(defined($alternateDirectoryRoot)) {
5583: $dirRoot = $alternateDirectoryRoot;
5584: $dirRoot =~ s/\/$//;
5585: }
5586:
5587: if($udom) {
5588: if($uname) {
5589: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5590: &homeserver($uname,$udom));
5591: my @listing_results;
5592: if ($listing eq 'unknown_cmd') {
5593: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5594: &homeserver($uname,$udom));
5595: @listing_results = split(/:/,$listing);
5596: } else {
5597: @listing_results = map { &unescape($_); } split(/:/,$listing);
5598: }
5599: return @listing_results;
5600: } elsif(!defined($alternateDirectoryRoot)) {
5601: my %allusers;
5602: my %servers = &get_servers($udom,'library');
5603: foreach my $tryserver (keys(%servers)) {
5604: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5605: $udom, $tryserver);
5606: my @listing_results;
5607: if ($listing eq 'unknown_cmd') {
5608: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5609: $udom, $tryserver);
5610: @listing_results = split(/:/,$listing);
5611: } else {
5612: @listing_results =
5613: map { &unescape($_); } split(/:/,$listing);
5614: }
5615: if ($listing_results[0] ne 'no_such_dir' &&
5616: $listing_results[0] ne 'empty' &&
5617: $listing_results[0] ne 'con_lost') {
5618: foreach my $line (@listing_results) {
5619: my ($entry) = split(/&/,$line,2);
5620: $allusers{$entry} = 1;
5621: }
5622: }
5623: }
5624: my $alluserstr='';
5625: foreach my $user (sort(keys(%allusers))) {
5626: $alluserstr.=$user.'&user:';
5627: }
5628: $alluserstr=~s/:$//;
5629: return split(/:/,$alluserstr);
5630: } else {
5631: return ('missing user name');
5632: }
5633: } elsif(!defined($alternateDirectoryRoot)) {
5634: my @all_domains = sort(&all_domains());
5635: foreach my $domain (@all_domains) {
5636: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5637: }
5638: return @all_domains;
5639: } else {
5640: return ('missing domain');
5641: }
5642: }
5643:
5644: # --------------------------------------------- GetFileTimestamp
5645: # This function utilizes dirlist and returns the date stamp for
5646: # when it was last modified. It will also return an error of -1
5647: # if an error occurs
5648:
5649: ##
5650: ## FIXME: This subroutine assumes its caller knows something about the
5651: ## directory structure of the home server for the student ($root).
5652: ## Not a good assumption to make. Since this is for looking up files
5653: ## in user directories, the full path should be constructed by lond, not
5654: ## whatever machine we request data from.
5655: ##
5656: sub GetFileTimestamp {
5657: my ($studentDomain,$studentName,$filename,$root)=@_;
5658: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5659: $studentName = &LONCAPA::clean_username($studentName);
5660: my $subdir=$studentName.'__';
5661: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5662: my $proname="$studentDomain/$subdir/$studentName";
5663: $proname .= '/'.$filename;
5664: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5665: $studentName, $root);
5666: my @stats = split('&', $fileStat);
5667: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5668: # @stats contains first the filename, then the stat output
5669: return $stats[10]; # so this is 10 instead of 9.
5670: } else {
5671: return -1;
5672: }
5673: }
5674:
5675: sub stat_file {
5676: my ($uri) = @_;
5677: $uri = &clutter_with_no_wrapper($uri);
5678:
5679: my ($udom,$uname,$file,$dir);
5680: if ($uri =~ m-^/(uploaded|editupload)/-) {
5681: ($udom,$uname,$file) =
5682: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
5683: $file = 'userfiles/'.$file;
5684: $dir = &propath($udom,$uname);
5685: }
5686: if ($uri =~ m-^/res/-) {
5687: ($udom,$uname) =
5688: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
5689: $file = $uri;
5690: }
5691:
5692: if (!$udom || !$uname || !$file) {
5693: # unable to handle the uri
5694: return ();
5695: }
5696:
5697: my ($result) = &dirlist($file,$udom,$uname,$dir);
5698: my @stats = split('&', $result);
5699:
5700: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5701: shift(@stats); #filename is first
5702: return @stats;
5703: }
5704: return ();
5705: }
5706:
5707: # -------------------------------------------------------- Value of a Condition
5708:
5709: # gets the value of a specific preevaluated condition
5710: # stored in the string $env{user.state.<cid>}
5711: # or looks up a condition reference in the bighash and if if hasn't
5712: # already been evaluated recurses into docondval to get the value of
5713: # the condition, then memoizing it to
5714: # $env{user.state.<cid>.<condition>}
5715: sub directcondval {
5716: my $number=shift;
5717: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5718: &Apache::lonuserstate::evalstate();
5719: }
5720: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5721: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5722: } elsif ($number =~ /^_/) {
5723: my $sub_condition;
5724: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5725: &GDBM_READER(),0640)) {
5726: $sub_condition=$bighash{'conditions'.$number};
5727: untie(%bighash);
5728: }
5729: my $value = &docondval($sub_condition);
5730: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5731: return $value;
5732: }
5733: if ($env{'user.state.'.$env{'request.course.id'}}) {
5734: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5735: } else {
5736: return 2;
5737: }
5738: }
5739:
5740: # get the collection of conditions for this resource
5741: sub condval {
5742: my $condidx=shift;
5743: my $allpathcond='';
5744: foreach my $cond (split(/\|/,$condidx)) {
5745: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5746: $allpathcond.=
5747: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5748: }
5749: }
5750: $allpathcond=~s/\|$//;
5751: return &docondval($allpathcond);
5752: }
5753:
5754: #evaluates an expression of conditions
5755: sub docondval {
5756: my ($allpathcond) = @_;
5757: my $result=0;
5758: if ($env{'request.course.id'}
5759: && defined($allpathcond)) {
5760: my $operand='|';
5761: my @stack;
5762: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5763: if ($chunk eq '(') {
5764: push @stack,($operand,$result);
5765: } elsif ($chunk eq ')') {
5766: my $before=pop @stack;
5767: if (pop @stack eq '&') {
5768: $result=$result>$before?$before:$result;
5769: } else {
5770: $result=$result>$before?$result:$before;
5771: }
5772: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5773: $operand=$chunk;
5774: } else {
5775: my $new=directcondval($chunk);
5776: if ($operand eq '&') {
5777: $result=$result>$new?$new:$result;
5778: } else {
5779: $result=$result>$new?$result:$new;
5780: }
5781: }
5782: }
5783: }
5784: return $result;
5785: }
5786:
5787: # ---------------------------------------------------- Devalidate courseresdata
5788:
5789: sub devalidatecourseresdata {
5790: my ($coursenum,$coursedomain)=@_;
5791: my $hashid=$coursenum.':'.$coursedomain;
5792: &devalidate_cache_new('courseres',$hashid);
5793: }
5794:
5795:
5796: # --------------------------------------------------- Course Resourcedata Query
5797:
5798: sub get_courseresdata {
5799: my ($coursenum,$coursedomain)=@_;
5800: my $coursehom=&homeserver($coursenum,$coursedomain);
5801: my $hashid=$coursenum.':'.$coursedomain;
5802: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5803: my %dumpreply;
5804: unless (defined($cached)) {
5805: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5806: $result=\%dumpreply;
5807: my ($tmp) = keys(%dumpreply);
5808: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5809: &do_cache_new('courseres',$hashid,$result,600);
5810: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5811: return $tmp;
5812: } elsif ($tmp =~ /^(error)/) {
5813: $result=undef;
5814: &do_cache_new('courseres',$hashid,$result,600);
5815: }
5816: }
5817: return $result;
5818: }
5819:
5820: sub devalidateuserresdata {
5821: my ($uname,$udom)=@_;
5822: my $hashid="$udom:$uname";
5823: &devalidate_cache_new('userres',$hashid);
5824: }
5825:
5826: sub get_userresdata {
5827: my ($uname,$udom)=@_;
5828: #most student don\'t have any data set, check if there is some data
5829: if (&EXT_cache_status($udom,$uname)) { return undef; }
5830:
5831: my $hashid="$udom:$uname";
5832: my ($result,$cached)=&is_cached_new('userres',$hashid);
5833: if (!defined($cached)) {
5834: my %resourcedata=&dump('resourcedata',$udom,$uname);
5835: $result=\%resourcedata;
5836: &do_cache_new('userres',$hashid,$result,600);
5837: }
5838: my ($tmp)=keys(%$result);
5839: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5840: return $result;
5841: }
5842: #error 2 occurs when the .db doesn't exist
5843: if ($tmp!~/error: 2 /) {
5844: &logthis("<font color=\"blue\">WARNING:".
5845: " Trying to get resource data for ".
5846: $uname." at ".$udom.": ".
5847: $tmp."</font>");
5848: } elsif ($tmp=~/error: 2 /) {
5849: #&EXT_cache_set($udom,$uname);
5850: &do_cache_new('userres',$hashid,undef,600);
5851: undef($tmp); # not really an error so don't send it back
5852: }
5853: return $tmp;
5854: }
5855:
5856: sub resdata {
5857: my ($name,$domain,$type,@which)=@_;
5858: my $result;
5859: if ($type eq 'course') {
5860: $result=&get_courseresdata($name,$domain);
5861: } elsif ($type eq 'user') {
5862: $result=&get_userresdata($name,$domain);
5863: }
5864: if (!ref($result)) { return $result; }
5865: foreach my $item (@which) {
5866: if (defined($result->{$item})) {
5867: return $result->{$item};
5868: }
5869: }
5870: return undef;
5871: }
5872:
5873: #
5874: # EXT resource caching routines
5875: #
5876:
5877: sub clear_EXT_cache_status {
5878: &delenv('cache.EXT.');
5879: }
5880:
5881: sub EXT_cache_status {
5882: my ($target_domain,$target_user) = @_;
5883: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5884: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
5885: # We know already the user has no data
5886: return 1;
5887: } else {
5888: return 0;
5889: }
5890: }
5891:
5892: sub EXT_cache_set {
5893: my ($target_domain,$target_user) = @_;
5894: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5895: #&appenv($cachename => time);
5896: }
5897:
5898: # --------------------------------------------------------- Value of a Variable
5899: sub EXT {
5900:
5901: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5902: unless ($varname) { return ''; }
5903: #get real user name/domain, courseid and symb
5904: my $courseid;
5905: my $publicuser;
5906: if ($symbparm) {
5907: $symbparm=&get_symb_from_alias($symbparm);
5908: }
5909: if (!($uname && $udom)) {
5910: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
5911: if (!$symbparm) { $symbparm=$cursymb; }
5912: } else {
5913: $courseid=$env{'request.course.id'};
5914: }
5915: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5916: my $rest;
5917: if (defined($therest[0])) {
5918: $rest=join('.',@therest);
5919: } else {
5920: $rest='';
5921: }
5922:
5923: my $qualifierrest=$qualifier;
5924: if ($rest) { $qualifierrest.='.'.$rest; }
5925: my $spacequalifierrest=$space;
5926: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
5927: if ($realm eq 'user') {
5928: # --------------------------------------------------------------- user.resource
5929: if ($space eq 'resource') {
5930: if ( (defined($Apache::lonhomework::parsing_a_problem)
5931: || defined($Apache::lonhomework::parsing_a_task))
5932: &&
5933: ($symbparm eq &symbread()) ) {
5934: # if we are in the middle of processing the resource the
5935: # get the value we are planning on committing
5936: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5937: return $Apache::lonhomework::results{$qualifierrest};
5938: } else {
5939: return $Apache::lonhomework::history{$qualifierrest};
5940: }
5941: } else {
5942: my %restored;
5943: if ($publicuser || $env{'request.state'} eq 'construct') {
5944: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5945: } else {
5946: %restored=&restore($symbparm,$courseid,$udom,$uname);
5947: }
5948: return $restored{$qualifierrest};
5949: }
5950: # ----------------------------------------------------------------- user.access
5951: } elsif ($space eq 'access') {
5952: # FIXME - not supporting calls for a specific user
5953: return &allowed($qualifier,$rest);
5954: # ------------------------------------------ user.preferences, user.environment
5955: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
5956: if (($uname eq $env{'user.name'}) &&
5957: ($udom eq $env{'user.domain'})) {
5958: return $env{join('.',('environment',$qualifierrest))};
5959: } else {
5960: my %returnhash;
5961: if (!$publicuser) {
5962: %returnhash=&userenvironment($udom,$uname,
5963: $qualifierrest);
5964: }
5965: return $returnhash{$qualifierrest};
5966: }
5967: # ----------------------------------------------------------------- user.course
5968: } elsif ($space eq 'course') {
5969: # FIXME - not supporting calls for a specific user
5970: return $env{join('.',('request.course',$qualifier))};
5971: # ------------------------------------------------------------------- user.role
5972: } elsif ($space eq 'role') {
5973: # FIXME - not supporting calls for a specific user
5974: my ($role,$where)=split(/\./,$env{'request.role'});
5975: if ($qualifier eq 'value') {
5976: return $role;
5977: } elsif ($qualifier eq 'extent') {
5978: return $where;
5979: }
5980: # ----------------------------------------------------------------- user.domain
5981: } elsif ($space eq 'domain') {
5982: return $udom;
5983: # ------------------------------------------------------------------- user.name
5984: } elsif ($space eq 'name') {
5985: return $uname;
5986: # ---------------------------------------------------- Any other user namespace
5987: } else {
5988: my %reply;
5989: if (!$publicuser) {
5990: %reply=&get($space,[$qualifierrest],$udom,$uname);
5991: }
5992: return $reply{$qualifierrest};
5993: }
5994: } elsif ($realm eq 'query') {
5995: # ---------------------------------------------- pull stuff out of query string
5996: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5997: [$spacequalifierrest]);
5998: return $env{'form.'.$spacequalifierrest};
5999: } elsif ($realm eq 'request') {
6000: # ------------------------------------------------------------- request.browser
6001: if ($space eq 'browser') {
6002: if ($qualifier eq 'textremote') {
6003: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
6004: return 1;
6005: } else {
6006: return 0;
6007: }
6008: } else {
6009: return $env{'browser.'.$qualifier};
6010: }
6011: # ------------------------------------------------------------ request.filename
6012: } else {
6013: return $env{'request.'.$spacequalifierrest};
6014: }
6015: } elsif ($realm eq 'course') {
6016: # ---------------------------------------------------------- course.description
6017: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
6018: } elsif ($realm eq 'resource') {
6019:
6020: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
6021: if (!$symbparm) { $symbparm=&symbread(); }
6022: }
6023:
6024: if ($space eq 'title') {
6025: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6026: return &gettitle($symbparm);
6027: }
6028:
6029: if ($space eq 'map') {
6030: my ($map) = &decode_symb($symbparm);
6031: return &symbread($map);
6032: }
6033:
6034: my ($section, $group, @groups);
6035: my ($courselevelm,$courselevel);
6036: if ($symbparm && defined($courseid) &&
6037: $courseid eq $env{'request.course.id'}) {
6038:
6039: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
6040:
6041: # ----------------------------------------------------- Cascading lookup scheme
6042: my $symbp=$symbparm;
6043: my $mapp=&deversion((&decode_symb($symbp))[0]);
6044:
6045: my $symbparm=$symbp.'.'.$spacequalifierrest;
6046: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6047:
6048: if (($env{'user.name'} eq $uname) &&
6049: ($env{'user.domain'} eq $udom)) {
6050: $section=$env{'request.course.sec'};
6051: @groups = split(/:/,$env{'request.course.groups'});
6052: @groups=&sort_course_groups($courseid,@groups);
6053: } else {
6054: if (! defined($usection)) {
6055: $section=&getsection($udom,$uname,$courseid);
6056: } else {
6057: $section = $usection;
6058: }
6059: @groups = &get_users_groups($udom,$uname,$courseid);
6060: }
6061:
6062: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6063: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6064: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6065:
6066: $courselevel=$courseid.'.'.$spacequalifierrest;
6067: my $courselevelr=$courseid.'.'.$symbparm;
6068: $courselevelm=$courseid.'.'.$mapparm;
6069:
6070: # ----------------------------------------------------------- first, check user
6071:
6072: my $userreply=&resdata($uname,$udom,'user',
6073: ($courselevelr,$courselevelm,
6074: $courselevel));
6075: if (defined($userreply)) { return $userreply; }
6076:
6077: # ------------------------------------------------ second, check some of course
6078: my $coursereply;
6079: if (@groups > 0) {
6080: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6081: $mapparm,$spacequalifierrest);
6082: if (defined($coursereply)) { return $coursereply; }
6083: }
6084:
6085: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6086: $env{'course.'.$courseid.'.domain'},
6087: 'course',
6088: ($seclevelr,$seclevelm,$seclevel,
6089: $courselevelr));
6090: if (defined($coursereply)) { return $coursereply; }
6091:
6092: # ------------------------------------------------------ third, check map parms
6093: my %parmhash=();
6094: my $thisparm='';
6095: if (tie(%parmhash,'GDBM_File',
6096: $env{'request.course.fn'}.'_parms.db',
6097: &GDBM_READER(),0640)) {
6098: $thisparm=$parmhash{$symbparm};
6099: untie(%parmhash);
6100: }
6101: if ($thisparm) { return $thisparm; }
6102: }
6103: # ------------------------------------------ fourth, look in resource metadata
6104:
6105: $spacequalifierrest=~s/\./\_/;
6106: my $filename;
6107: if (!$symbparm) { $symbparm=&symbread(); }
6108: if ($symbparm) {
6109: $filename=(&decode_symb($symbparm))[2];
6110: } else {
6111: $filename=$env{'request.filename'};
6112: }
6113: my $metadata=&metadata($filename,$spacequalifierrest);
6114: if (defined($metadata)) { return $metadata; }
6115: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
6116: if (defined($metadata)) { return $metadata; }
6117:
6118: # ---------------------------------------------- fourth, look in rest pf course
6119: if ($symbparm && defined($courseid) &&
6120: $courseid eq $env{'request.course.id'}) {
6121: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6122: $env{'course.'.$courseid.'.domain'},
6123: 'course',
6124: ($courselevelm,$courselevel));
6125: if (defined($coursereply)) { return $coursereply; }
6126: }
6127: # ------------------------------------------------------------------ Cascade up
6128: unless ($space eq '0') {
6129: my @parts=split(/_/,$space);
6130: my $id=pop(@parts);
6131: my $part=join('_',@parts);
6132: if ($part eq '') { $part='0'; }
6133: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
6134: $symbparm,$udom,$uname,$section,1);
6135: if (defined($partgeneral)) { return $partgeneral; }
6136: }
6137: if ($recurse) { return undef; }
6138: my $pack_def=&packages_tab_default($filename,$varname);
6139: if (defined($pack_def)) { return $pack_def; }
6140:
6141: # ---------------------------------------------------- Any other user namespace
6142: } elsif ($realm eq 'environment') {
6143: # ----------------------------------------------------------------- environment
6144: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6145: return $env{'environment.'.$spacequalifierrest};
6146: } else {
6147: if ($uname eq 'anonymous' && $udom eq '') {
6148: return '';
6149: }
6150: my %returnhash=&userenvironment($udom,$uname,
6151: $spacequalifierrest);
6152: return $returnhash{$spacequalifierrest};
6153: }
6154: } elsif ($realm eq 'system') {
6155: # ----------------------------------------------------------------- system.time
6156: if ($space eq 'time') {
6157: return time;
6158: }
6159: } elsif ($realm eq 'server') {
6160: # ----------------------------------------------------------------- system.time
6161: if ($space eq 'name') {
6162: return $ENV{'SERVER_NAME'};
6163: }
6164: }
6165: return '';
6166: }
6167:
6168: sub check_group_parms {
6169: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6170: my @groupitems = ();
6171: my $resultitem;
6172: my @levels = ($symbparm,$mapparm,$what);
6173: foreach my $group (@{$groups}) {
6174: foreach my $level (@levels) {
6175: my $item = $courseid.'.['.$group.'].'.$level;
6176: push(@groupitems,$item);
6177: }
6178: }
6179: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6180: $env{'course.'.$courseid.'.domain'},
6181: 'course',@groupitems);
6182: return $coursereply;
6183: }
6184:
6185: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
6186: my ($courseid,@groups) = @_;
6187: @groups = sort(@groups);
6188: return @groups;
6189: }
6190:
6191: sub packages_tab_default {
6192: my ($uri,$varname)=@_;
6193: my (undef,$part,$name)=split(/\./,$varname);
6194:
6195: my (@extension,@specifics,$do_default);
6196: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
6197: my ($pack_type,$pack_part)=split(/_/,$package,2);
6198: if ($pack_type eq 'default') {
6199: $do_default=1;
6200: } elsif ($pack_type eq 'extension') {
6201: push(@extension,[$package,$pack_type,$pack_part]);
6202: } elsif ($pack_part eq $part) {
6203: # only look at packages defaults for packages that this id is
6204: push(@specifics,[$package,$pack_type,$pack_part]);
6205: }
6206: }
6207: # first look for a package that matches the requested part id
6208: foreach my $package (@specifics) {
6209: my (undef,$pack_type,$pack_part)=@{$package};
6210: next if ($pack_part ne $part);
6211: if (defined($packagetab{"$pack_type&$name&default"})) {
6212: return $packagetab{"$pack_type&$name&default"};
6213: }
6214: }
6215: # look for any possible matching non extension_ package
6216: foreach my $package (@specifics) {
6217: my (undef,$pack_type,$pack_part)=@{$package};
6218: if (defined($packagetab{"$pack_type&$name&default"})) {
6219: return $packagetab{"$pack_type&$name&default"};
6220: }
6221: if ($pack_type eq 'part') { $pack_part='0'; }
6222: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6223: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
6224: }
6225: }
6226: # look for any posible extension_ match
6227: foreach my $package (@extension) {
6228: my ($package,$pack_type)=@{$package};
6229: if (defined($packagetab{"$pack_type&$name&default"})) {
6230: return $packagetab{"$pack_type&$name&default"};
6231: }
6232: if (defined($packagetab{$package."&$name&default"})) {
6233: return $packagetab{$package."&$name&default"};
6234: }
6235: }
6236: # look for a global default setting
6237: if ($do_default && defined($packagetab{"default&$name&default"})) {
6238: return $packagetab{"default&$name&default"};
6239: }
6240: return undef;
6241: }
6242:
6243: sub add_prefix_and_part {
6244: my ($prefix,$part)=@_;
6245: my $keyroot;
6246: if (defined($prefix) && $prefix !~ /^__/) {
6247: # prefix that has a part already
6248: $keyroot=$prefix;
6249: } elsif (defined($prefix)) {
6250: # prefix that is missing a part
6251: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6252: } else {
6253: # no prefix at all
6254: if (defined($part)) { $keyroot='_'.$part; }
6255: }
6256: return $keyroot;
6257: }
6258:
6259: # ---------------------------------------------------------------- Get metadata
6260:
6261: my %metaentry;
6262: sub metadata {
6263: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
6264: $uri=&declutter($uri);
6265: # if it is a non metadata possible uri return quickly
6266: if (($uri eq '') ||
6267: (($uri =~ m|^/*adm/|) &&
6268: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
6269: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
6270: ($uri =~ m|home/$match_username/public_html/|)) {
6271: return undef;
6272: }
6273: my $filename=$uri;
6274: $uri=~s/\.meta$//;
6275: #
6276: # Is the metadata already cached?
6277: # Look at timestamp of caching
6278: # Everything is cached by the main uri, libraries are never directly cached
6279: #
6280: if (!defined($liburi)) {
6281: my ($result,$cached)=&is_cached_new('meta',$uri);
6282: if (defined($cached)) { return $result->{':'.$what}; }
6283: }
6284: {
6285: #
6286: # Is this a recursive call for a library?
6287: #
6288: # if (! exists($metacache{$uri})) {
6289: # $metacache{$uri}={};
6290: # }
6291: if ($liburi) {
6292: $liburi=&declutter($liburi);
6293: $filename=$liburi;
6294: } else {
6295: &devalidate_cache_new('meta',$uri);
6296: undef(%metaentry);
6297: }
6298: my %metathesekeys=();
6299: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
6300: my $metastring;
6301: if ($uri !~ m -^(editupload)/-) {
6302: my $file=&filelocation('',&clutter($filename));
6303: #push(@{$metaentry{$uri.'.file'}},$file);
6304: $metastring=&getfile($file);
6305: }
6306: my $parser=HTML::LCParser->new(\$metastring);
6307: my $token;
6308: undef %metathesekeys;
6309: while ($token=$parser->get_token) {
6310: if ($token->[0] eq 'S') {
6311: if (defined($token->[2]->{'package'})) {
6312: #
6313: # This is a package - get package info
6314: #
6315: my $package=$token->[2]->{'package'};
6316: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6317: if (defined($token->[2]->{'id'})) {
6318: $keyroot.='_'.$token->[2]->{'id'};
6319: }
6320: if ($metaentry{':packages'}) {
6321: $metaentry{':packages'}.=','.$package.$keyroot;
6322: } else {
6323: $metaentry{':packages'}=$package.$keyroot;
6324: }
6325: foreach my $pack_entry (keys(%packagetab)) {
6326: my $part=$keyroot;
6327: $part=~s/^\_//;
6328: if ($pack_entry=~/^\Q$package\E\&/ ||
6329: $pack_entry=~/^\Q$package\E_0\&/) {
6330: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
6331: # ignore package.tab specified default values
6332: # here &package_tab_default() will fetch those
6333: if ($subp eq 'default') { next; }
6334: my $value=$packagetab{$pack_entry};
6335: my $unikey;
6336: if ($pack =~ /_0$/) {
6337: $unikey='parameter_0_'.$name;
6338: $part=0;
6339: } else {
6340: $unikey='parameter'.$keyroot.'_'.$name;
6341: }
6342: if ($subp eq 'display') {
6343: $value.=' [Part: '.$part.']';
6344: }
6345: $metaentry{':'.$unikey.'.part'}=$part;
6346: $metathesekeys{$unikey}=1;
6347: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6348: $metaentry{':'.$unikey.'.'.$subp}=$value;
6349: }
6350: if (defined($metaentry{':'.$unikey.'.default'})) {
6351: $metaentry{':'.$unikey}=
6352: $metaentry{':'.$unikey.'.default'};
6353: }
6354: }
6355: }
6356: } else {
6357: #
6358: # This is not a package - some other kind of start tag
6359: #
6360: my $entry=$token->[1];
6361: my $unikey;
6362: if ($entry eq 'import') {
6363: $unikey='';
6364: } else {
6365: $unikey=$entry;
6366: }
6367: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6368:
6369: if (defined($token->[2]->{'id'})) {
6370: $unikey.='_'.$token->[2]->{'id'};
6371: }
6372:
6373: if ($entry eq 'import') {
6374: #
6375: # Importing a library here
6376: #
6377: if ($depthcount<20) {
6378: my $location=$parser->get_text('/import');
6379: my $dir=$filename;
6380: $dir=~s|[^/]*$||;
6381: $location=&filelocation($dir,$location);
6382: my $metadata =
6383: &metadata($uri,'keys', $location,$unikey,
6384: $depthcount+1);
6385: foreach my $meta (split(',',$metadata)) {
6386: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6387: $metathesekeys{$meta}=1;
6388: }
6389: }
6390: } else {
6391:
6392: if (defined($token->[2]->{'name'})) {
6393: $unikey.='_'.$token->[2]->{'name'};
6394: }
6395: $metathesekeys{$unikey}=1;
6396: foreach my $param (@{$token->[3]}) {
6397: $metaentry{':'.$unikey.'.'.$param} =
6398: $token->[2]->{$param};
6399: }
6400: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
6401: my $default=$metaentry{':'.$unikey.'.default'};
6402: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6403: # only ws inside the tag, and not in default, so use default
6404: # as value
6405: $metaentry{':'.$unikey}=$default;
6406: } else {
6407: # either something interesting inside the tag or default
6408: # uninteresting
6409: $metaentry{':'.$unikey}=$internaltext;
6410: }
6411: # end of not-a-package not-a-library import
6412: }
6413: # end of not-a-package start tag
6414: }
6415: # the next is the end of "start tag"
6416: }
6417: }
6418: my ($extension) = ($uri =~ /\.(\w+)$/);
6419: foreach my $key (keys(%packagetab)) {
6420: #no specific packages #how's our extension
6421: if ($key!~/^extension_\Q$extension\E&/) { next; }
6422: &metadata_create_package_def($uri,$key,'extension_'.$extension,
6423: \%metathesekeys);
6424: }
6425: if (!exists($metaentry{':packages'})) {
6426: foreach my $key (keys(%packagetab)) {
6427: #no specific packages well let's get default then
6428: if ($key!~/^default&/) { next; }
6429: &metadata_create_package_def($uri,$key,'default',
6430: \%metathesekeys);
6431: }
6432: }
6433: # are there custom rights to evaluate
6434: if ($metaentry{':copyright'} eq 'custom') {
6435:
6436: #
6437: # Importing a rights file here
6438: #
6439: unless ($depthcount) {
6440: my $location=$metaentry{':customdistributionfile'};
6441: my $dir=$filename;
6442: $dir=~s|[^/]*$||;
6443: $location=&filelocation($dir,$location);
6444: my $rights_metadata =
6445: &metadata($uri,'keys',$location,'_rights',
6446: $depthcount+1);
6447: foreach my $rights (split(',',$rights_metadata)) {
6448: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6449: $metathesekeys{$rights}=1;
6450: }
6451: }
6452: }
6453: # uniqifiy package listing
6454: my %seen;
6455: my @uniq_packages =
6456: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6457: $metaentry{':packages'} = join(',',@uniq_packages);
6458:
6459: $metaentry{':keys'} = join(',',keys(%metathesekeys));
6460: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6461: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
6462: &do_cache_new('meta',$uri,\%metaentry,60*60);
6463: # this is the end of "was not already recently cached
6464: }
6465: return $metaentry{':'.$what};
6466: }
6467:
6468: sub metadata_create_package_def {
6469: my ($uri,$key,$package,$metathesekeys)=@_;
6470: my ($pack,$name,$subp)=split(/\&/,$key);
6471: if ($subp eq 'default') { next; }
6472:
6473: if (defined($metaentry{':packages'})) {
6474: $metaentry{':packages'}.=','.$package;
6475: } else {
6476: $metaentry{':packages'}=$package;
6477: }
6478: my $value=$packagetab{$key};
6479: my $unikey;
6480: $unikey='parameter_0_'.$name;
6481: $metaentry{':'.$unikey.'.part'}=0;
6482: $$metathesekeys{$unikey}=1;
6483: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6484: $metaentry{':'.$unikey.'.'.$subp}=$value;
6485: }
6486: if (defined($metaentry{':'.$unikey.'.default'})) {
6487: $metaentry{':'.$unikey}=
6488: $metaentry{':'.$unikey.'.default'};
6489: }
6490: }
6491:
6492: sub metadata_generate_part0 {
6493: my ($metadata,$metacache,$uri) = @_;
6494: my %allnames;
6495: foreach my $metakey (keys(%$metadata)) {
6496: if ($metakey=~/^parameter\_(.*)/) {
6497: my $part=$$metacache{':'.$metakey.'.part'};
6498: my $name=$$metacache{':'.$metakey.'.name'};
6499: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
6500: $allnames{$name}=$part;
6501: }
6502: }
6503: }
6504: foreach my $name (keys(%allnames)) {
6505: $$metadata{"parameter_0_$name"}=1;
6506: my $key=":parameter_0_$name";
6507: $$metacache{"$key.part"}='0';
6508: $$metacache{"$key.name"}=$name;
6509: $$metacache{"$key.type"}=$$metacache{':parameter_'.
6510: $allnames{$name}.'_'.$name.
6511: '.type'};
6512: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
6513: '.display'};
6514: my $expr='[Part: '.$allnames{$name}.']';
6515: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
6516: $$metacache{"$key.display"}=$olddis;
6517: }
6518: }
6519:
6520: # ------------------------------------------------------ Devalidate title cache
6521:
6522: sub devalidate_title_cache {
6523: my ($url)=@_;
6524: if (!$env{'request.course.id'}) { return; }
6525: my $symb=&symbread($url);
6526: if (!$symb) { return; }
6527: my $key=$env{'request.course.id'}."\0".$symb;
6528: &devalidate_cache_new('title',$key);
6529: }
6530:
6531: # ------------------------------------------------- Get the title of a resource
6532:
6533: sub gettitle {
6534: my $urlsymb=shift;
6535: my $symb=&symbread($urlsymb);
6536: if ($symb) {
6537: my $key=$env{'request.course.id'}."\0".$symb;
6538: my ($result,$cached)=&is_cached_new('title',$key);
6539: if (defined($cached)) {
6540: return $result;
6541: }
6542: my ($map,$resid,$url)=&decode_symb($symb);
6543: my $title='';
6544: my %bighash;
6545: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6546: &GDBM_READER(),0640)) {
6547: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6548: $title=$bighash{'title_'.$mapid.'.'.$resid};
6549: untie %bighash;
6550: }
6551: $title=~s/\&colon\;/\:/gs;
6552: if ($title) {
6553: return &do_cache_new('title',$key,$title,600);
6554: }
6555: $urlsymb=$url;
6556: }
6557: my $title=&metadata($urlsymb,'title');
6558: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6559: return $title;
6560: }
6561:
6562: sub get_slot {
6563: my ($which,$cnum,$cdom)=@_;
6564: if (!$cnum || !$cdom) {
6565: (undef,my $courseid)=&whichuser();
6566: $cdom=$env{'course.'.$courseid.'.domain'};
6567: $cnum=$env{'course.'.$courseid.'.num'};
6568: }
6569: my $key=join("\0",'slots',$cdom,$cnum,$which);
6570: my %slotinfo;
6571: if (exists($remembered{$key})) {
6572: $slotinfo{$which} = $remembered{$key};
6573: } else {
6574: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6575: &Apache::lonhomework::showhash(%slotinfo);
6576: my ($tmp)=keys(%slotinfo);
6577: if ($tmp=~/^error:/) { return (); }
6578: $remembered{$key} = $slotinfo{$which};
6579: }
6580: if (ref($slotinfo{$which}) eq 'HASH') {
6581: return %{$slotinfo{$which}};
6582: }
6583: return $slotinfo{$which};
6584: }
6585: # ------------------------------------------------- Update symbolic store links
6586:
6587: sub symblist {
6588: my ($mapname,%newhash)=@_;
6589: $mapname=&deversion(&declutter($mapname));
6590: my %hash;
6591: if (($env{'request.course.fn'}) && (%newhash)) {
6592: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6593: &GDBM_WRCREAT(),0640)) {
6594: foreach my $url (keys %newhash) {
6595: next if ($url eq 'last_known'
6596: && $env{'form.no_update_last_known'});
6597: $hash{declutter($url)}=&encode_symb($mapname,
6598: $newhash{$url}->[1],
6599: $newhash{$url}->[0]);
6600: }
6601: if (untie(%hash)) {
6602: return 'ok';
6603: }
6604: }
6605: }
6606: return 'error';
6607: }
6608:
6609: # --------------------------------------------------------------- Verify a symb
6610:
6611: sub symbverify {
6612: my ($symb,$thisurl)=@_;
6613: my $thisfn=$thisurl;
6614: $thisfn=&declutter($thisfn);
6615: # direct jump to resource in page or to a sequence - will construct own symbs
6616: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6617: # check URL part
6618: my ($map,$resid,$url)=&decode_symb($symb);
6619:
6620: unless ($url eq $thisfn) { return 0; }
6621:
6622: $symb=&symbclean($symb);
6623: $thisurl=&deversion($thisurl);
6624: $thisfn=&deversion($thisfn);
6625:
6626: my %bighash;
6627: my $okay=0;
6628:
6629: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6630: &GDBM_READER(),0640)) {
6631: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6632: unless ($ids) {
6633: $ids=$bighash{'ids_/'.$thisurl};
6634: }
6635: if ($ids) {
6636: # ------------------------------------------------------------------- Has ID(s)
6637: foreach my $id (split(/\,/,$ids)) {
6638: my ($mapid,$resid)=split(/\./,$id);
6639: if (
6640: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6641: eq $symb) {
6642: if (($env{'request.role.adv'}) ||
6643: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
6644: $okay=1;
6645: }
6646: }
6647: }
6648: }
6649: untie(%bighash);
6650: }
6651: return $okay;
6652: }
6653:
6654: # --------------------------------------------------------------- Clean-up symb
6655:
6656: sub symbclean {
6657: my $symb=shift;
6658: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6659: # remove version from map
6660: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6661:
6662: # remove version from URL
6663: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6664:
6665: # remove wrapper
6666:
6667: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6668: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6669: return $symb;
6670: }
6671:
6672: # ---------------------------------------------- Split symb to find map and url
6673:
6674: sub encode_symb {
6675: my ($map,$resid,$url)=@_;
6676: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6677: }
6678:
6679: sub decode_symb {
6680: my $symb=shift;
6681: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6682: my ($map,$resid,$url)=split(/___/,$symb);
6683: return (&fixversion($map),$resid,&fixversion($url));
6684: }
6685:
6686: sub fixversion {
6687: my $fn=shift;
6688: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6689: my %bighash;
6690: my $uri=&clutter($fn);
6691: my $key=$env{'request.course.id'}.'_'.$uri;
6692: # is this cached?
6693: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6694: if (defined($cached)) { return $result; }
6695: # unfortunately not cached, or expired
6696: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6697: &GDBM_READER(),0640)) {
6698: if ($bighash{'version_'.$uri}) {
6699: my $version=$bighash{'version_'.$uri};
6700: unless (($version eq 'mostrecent') ||
6701: ($version==&getversion($uri))) {
6702: $uri=~s/\.(\w+)$/\.$version\.$1/;
6703: }
6704: }
6705: untie %bighash;
6706: }
6707: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6708: }
6709:
6710: sub deversion {
6711: my $url=shift;
6712: $url=~s/\.\d+\.(\w+)$/\.$1/;
6713: return $url;
6714: }
6715:
6716: # ------------------------------------------------------ Return symb list entry
6717:
6718: sub symbread {
6719: my ($thisfn,$donotrecurse)=@_;
6720: my $cache_str='request.symbread.cached.'.$thisfn;
6721: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6722: # no filename provided? try from environment
6723: unless ($thisfn) {
6724: if ($env{'request.symb'}) {
6725: return $env{$cache_str}=&symbclean($env{'request.symb'});
6726: }
6727: $thisfn=$env{'request.filename'};
6728: }
6729: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6730: # is that filename actually a symb? Verify, clean, and return
6731: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6732: if (&symbverify($thisfn,$1)) {
6733: return $env{$cache_str}=&symbclean($thisfn);
6734: }
6735: }
6736: $thisfn=declutter($thisfn);
6737: my %hash;
6738: my %bighash;
6739: my $syval='';
6740: if (($env{'request.course.fn'}) && ($thisfn)) {
6741: my $targetfn = $thisfn;
6742: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6743: $targetfn = 'adm/wrapper/'.$thisfn;
6744: }
6745: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6746: $targetfn=$1;
6747: }
6748: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6749: &GDBM_READER(),0640)) {
6750: $syval=$hash{$targetfn};
6751: untie(%hash);
6752: }
6753: # ---------------------------------------------------------- There was an entry
6754: if ($syval) {
6755: #unless ($syval=~/\_\d+$/) {
6756: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6757: #&appenv('request.ambiguous' => $thisfn);
6758: #return $env{$cache_str}='';
6759: #}
6760: #$syval.=$1;
6761: #}
6762: } else {
6763: # ------------------------------------------------------- Was not in symb table
6764: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6765: &GDBM_READER(),0640)) {
6766: # ---------------------------------------------- Get ID(s) for current resource
6767: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6768: unless ($ids) {
6769: $ids=$bighash{'ids_/'.$thisfn};
6770: }
6771: unless ($ids) {
6772: # alias?
6773: $ids=$bighash{'mapalias_'.$thisfn};
6774: }
6775: if ($ids) {
6776: # ------------------------------------------------------------------- Has ID(s)
6777: my @possibilities=split(/\,/,$ids);
6778: if ($#possibilities==0) {
6779: # ----------------------------------------------- There is only one possibility
6780: my ($mapid,$resid)=split(/\./,$ids);
6781: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6782: $resid,$thisfn);
6783: } elsif (!$donotrecurse) {
6784: # ------------------------------------------ There is more than one possibility
6785: my $realpossible=0;
6786: foreach my $id (@possibilities) {
6787: my $file=$bighash{'src_'.$id};
6788: if (&allowed('bre',$file)) {
6789: my ($mapid,$resid)=split(/\./,$id);
6790: if ($bighash{'map_type_'.$mapid} ne 'page') {
6791: $realpossible++;
6792: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6793: $resid,$thisfn);
6794: }
6795: }
6796: }
6797: if ($realpossible!=1) { $syval=''; }
6798: } else {
6799: $syval='';
6800: }
6801: }
6802: untie(%bighash)
6803: }
6804: }
6805: if ($syval) {
6806: return $env{$cache_str}=$syval;
6807: }
6808: }
6809: &appenv('request.ambiguous' => $thisfn);
6810: return $env{$cache_str}='';
6811: }
6812:
6813: # ---------------------------------------------------------- Return random seed
6814:
6815: sub numval {
6816: my $txt=shift;
6817: $txt=~tr/A-J/0-9/;
6818: $txt=~tr/a-j/0-9/;
6819: $txt=~tr/K-T/0-9/;
6820: $txt=~tr/k-t/0-9/;
6821: $txt=~tr/U-Z/0-5/;
6822: $txt=~tr/u-z/0-5/;
6823: $txt=~s/\D//g;
6824: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6825: return int($txt);
6826: }
6827:
6828: sub numval2 {
6829: my $txt=shift;
6830: $txt=~tr/A-J/0-9/;
6831: $txt=~tr/a-j/0-9/;
6832: $txt=~tr/K-T/0-9/;
6833: $txt=~tr/k-t/0-9/;
6834: $txt=~tr/U-Z/0-5/;
6835: $txt=~tr/u-z/0-5/;
6836: $txt=~s/\D//g;
6837: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6838: my $total;
6839: foreach my $val (@txts) { $total+=$val; }
6840: if ($_64bit) { if ($total > 2**32) { return -1; } }
6841: return int($total);
6842: }
6843:
6844: sub numval3 {
6845: use integer;
6846: my $txt=shift;
6847: $txt=~tr/A-J/0-9/;
6848: $txt=~tr/a-j/0-9/;
6849: $txt=~tr/K-T/0-9/;
6850: $txt=~tr/k-t/0-9/;
6851: $txt=~tr/U-Z/0-5/;
6852: $txt=~tr/u-z/0-5/;
6853: $txt=~s/\D//g;
6854: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6855: my $total;
6856: foreach my $val (@txts) { $total+=$val; }
6857: if ($_64bit) { $total=(($total<<32)>>32); }
6858: return $total;
6859: }
6860:
6861: sub digest {
6862: my ($data)=@_;
6863: my $digest=&Digest::MD5::md5($data);
6864: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6865: my ($e,$f);
6866: {
6867: use integer;
6868: $e=($a+$b);
6869: $f=($c+$d);
6870: if ($_64bit) {
6871: $e=(($e<<32)>>32);
6872: $f=(($f<<32)>>32);
6873: }
6874: }
6875: if (wantarray) {
6876: return ($e,$f);
6877: } else {
6878: my $g;
6879: {
6880: use integer;
6881: $g=($e+$f);
6882: if ($_64bit) {
6883: $g=(($g<<32)>>32);
6884: }
6885: }
6886: return $g;
6887: }
6888: }
6889:
6890: sub latest_rnd_algorithm_id {
6891: return '64bit5';
6892: }
6893:
6894: sub get_rand_alg {
6895: my ($courseid)=@_;
6896: if (!$courseid) { $courseid=(&whichuser())[1]; }
6897: if ($courseid) {
6898: return $env{"course.$courseid.rndseed"};
6899: }
6900: return &latest_rnd_algorithm_id();
6901: }
6902:
6903: sub validCODE {
6904: my ($CODE)=@_;
6905: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6906: return 0;
6907: }
6908:
6909: sub getCODE {
6910: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
6911: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6912: defined($Apache::lonhomework::parsing_a_task) ) &&
6913: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
6914: return $Apache::lonhomework::history{'resource.CODE'};
6915: }
6916: return undef;
6917: }
6918:
6919: sub rndseed {
6920: my ($symb,$courseid,$domain,$username)=@_;
6921:
6922: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
6923: if (!$symb) {
6924: unless ($symb=$wsymb) { return time; }
6925: }
6926: if (!$courseid) { $courseid=$wcourseid; }
6927: if (!$domain) { $domain=$wdomain; }
6928: if (!$username) { $username=$wusername }
6929: my $which=&get_rand_alg();
6930:
6931: if (defined(&getCODE())) {
6932: if ($which eq '64bit5') {
6933: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6934: } elsif ($which eq '64bit4') {
6935: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6936: } else {
6937: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6938: }
6939: } elsif ($which eq '64bit5') {
6940: return &rndseed_64bit5($symb,$courseid,$domain,$username);
6941: } elsif ($which eq '64bit4') {
6942: return &rndseed_64bit4($symb,$courseid,$domain,$username);
6943: } elsif ($which eq '64bit3') {
6944: return &rndseed_64bit3($symb,$courseid,$domain,$username);
6945: } elsif ($which eq '64bit2') {
6946: return &rndseed_64bit2($symb,$courseid,$domain,$username);
6947: } elsif ($which eq '64bit') {
6948: return &rndseed_64bit($symb,$courseid,$domain,$username);
6949: }
6950: return &rndseed_32bit($symb,$courseid,$domain,$username);
6951: }
6952:
6953: sub rndseed_32bit {
6954: my ($symb,$courseid,$domain,$username)=@_;
6955: {
6956: use integer;
6957: my $symbchck=unpack("%32C*",$symb) << 27;
6958: my $symbseed=numval($symb) << 22;
6959: my $namechck=unpack("%32C*",$username) << 17;
6960: my $nameseed=numval($username) << 12;
6961: my $domainseed=unpack("%32C*",$domain) << 7;
6962: my $courseseed=unpack("%32C*",$courseid);
6963: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6964: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6965: #&logthis("rndseed :$num:$symb");
6966: if ($_64bit) { $num=(($num<<32)>>32); }
6967: return $num;
6968: }
6969: }
6970:
6971: sub rndseed_64bit {
6972: my ($symb,$courseid,$domain,$username)=@_;
6973: {
6974: use integer;
6975: my $symbchck=unpack("%32S*",$symb) << 21;
6976: my $symbseed=numval($symb) << 10;
6977: my $namechck=unpack("%32S*",$username);
6978:
6979: my $nameseed=numval($username) << 21;
6980: my $domainseed=unpack("%32S*",$domain) << 10;
6981: my $courseseed=unpack("%32S*",$courseid);
6982:
6983: my $num1=$symbchck+$symbseed+$namechck;
6984: my $num2=$nameseed+$domainseed+$courseseed;
6985: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6986: #&logthis("rndseed :$num:$symb");
6987: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6988: return "$num1,$num2";
6989: }
6990: }
6991:
6992: sub rndseed_64bit2 {
6993: my ($symb,$courseid,$domain,$username)=@_;
6994: {
6995: use integer;
6996: # strings need to be an even # of cahracters long, it it is odd the
6997: # last characters gets thrown away
6998: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6999: my $symbseed=numval($symb) << 10;
7000: my $namechck=unpack("%32S*",$username.' ');
7001:
7002: my $nameseed=numval($username) << 21;
7003: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7004: my $courseseed=unpack("%32S*",$courseid.' ');
7005:
7006: my $num1=$symbchck+$symbseed+$namechck;
7007: my $num2=$nameseed+$domainseed+$courseseed;
7008: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7009: #&logthis("rndseed :$num:$symb");
7010: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7011: return "$num1,$num2";
7012: }
7013: }
7014:
7015: sub rndseed_64bit3 {
7016: my ($symb,$courseid,$domain,$username)=@_;
7017: {
7018: use integer;
7019: # strings need to be an even # of cahracters long, it it is odd the
7020: # last characters gets thrown away
7021: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7022: my $symbseed=numval2($symb) << 10;
7023: my $namechck=unpack("%32S*",$username.' ');
7024:
7025: my $nameseed=numval2($username) << 21;
7026: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7027: my $courseseed=unpack("%32S*",$courseid.' ');
7028:
7029: my $num1=$symbchck+$symbseed+$namechck;
7030: my $num2=$nameseed+$domainseed+$courseseed;
7031: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7032: #&logthis("rndseed :$num1:$num2:$_64bit");
7033: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7034:
7035: return "$num1:$num2";
7036: }
7037: }
7038:
7039: sub rndseed_64bit4 {
7040: my ($symb,$courseid,$domain,$username)=@_;
7041: {
7042: use integer;
7043: # strings need to be an even # of cahracters long, it it is odd the
7044: # last characters gets thrown away
7045: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7046: my $symbseed=numval3($symb) << 10;
7047: my $namechck=unpack("%32S*",$username.' ');
7048:
7049: my $nameseed=numval3($username) << 21;
7050: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7051: my $courseseed=unpack("%32S*",$courseid.' ');
7052:
7053: my $num1=$symbchck+$symbseed+$namechck;
7054: my $num2=$nameseed+$domainseed+$courseseed;
7055: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7056: #&logthis("rndseed :$num1:$num2:$_64bit");
7057: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7058:
7059: return "$num1:$num2";
7060: }
7061: }
7062:
7063: sub rndseed_64bit5 {
7064: my ($symb,$courseid,$domain,$username)=@_;
7065: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7066: return "$num1:$num2";
7067: }
7068:
7069: sub rndseed_CODE_64bit {
7070: my ($symb,$courseid,$domain,$username)=@_;
7071: {
7072: use integer;
7073: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7074: my $symbseed=numval2($symb);
7075: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7076: my $CODEseed=numval(&getCODE());
7077: my $courseseed=unpack("%32S*",$courseid.' ');
7078: my $num1=$symbseed+$CODEchck;
7079: my $num2=$CODEseed+$courseseed+$symbchck;
7080: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7081: #&logthis("rndseed :$num1:$num2:$symb");
7082: if ($_64bit) { $num1=(($num1<<32)>>32); }
7083: if ($_64bit) { $num2=(($num2<<32)>>32); }
7084: return "$num1:$num2";
7085: }
7086: }
7087:
7088: sub rndseed_CODE_64bit4 {
7089: my ($symb,$courseid,$domain,$username)=@_;
7090: {
7091: use integer;
7092: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7093: my $symbseed=numval3($symb);
7094: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7095: my $CODEseed=numval3(&getCODE());
7096: my $courseseed=unpack("%32S*",$courseid.' ');
7097: my $num1=$symbseed+$CODEchck;
7098: my $num2=$CODEseed+$courseseed+$symbchck;
7099: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7100: #&logthis("rndseed :$num1:$num2:$symb");
7101: if ($_64bit) { $num1=(($num1<<32)>>32); }
7102: if ($_64bit) { $num2=(($num2<<32)>>32); }
7103: return "$num1:$num2";
7104: }
7105: }
7106:
7107: sub rndseed_CODE_64bit5 {
7108: my ($symb,$courseid,$domain,$username)=@_;
7109: my $code = &getCODE();
7110: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7111: return "$num1:$num2";
7112: }
7113:
7114: sub setup_random_from_rndseed {
7115: my ($rndseed)=@_;
7116: if ($rndseed =~/([,:])/) {
7117: my ($num1,$num2)=split(/[,:]/,$rndseed);
7118: &Math::Random::random_set_seed(abs($num1),abs($num2));
7119: } else {
7120: &Math::Random::random_set_seed_from_phrase($rndseed);
7121: }
7122: }
7123:
7124: sub latest_receipt_algorithm_id {
7125: return 'receipt3';
7126: }
7127:
7128: sub recunique {
7129: my $fucourseid=shift;
7130: my $unique;
7131: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7132: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7133: $unique=$env{"course.$fucourseid.internal.encseed"};
7134: } else {
7135: $unique=$perlvar{'lonReceipt'};
7136: }
7137: return unpack("%32C*",$unique);
7138: }
7139:
7140: sub recprefix {
7141: my $fucourseid=shift;
7142: my $prefix;
7143: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7144: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
7145: $prefix=$env{"course.$fucourseid.internal.encpref"};
7146: } else {
7147: $prefix=$perlvar{'lonHostID'};
7148: }
7149: return unpack("%32C*",$prefix);
7150: }
7151:
7152: sub ireceipt {
7153: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
7154:
7155: my $return =&recprefix($fucourseid).'-';
7156:
7157: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7158: $env{'request.state'} eq 'construct') {
7159: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7160: return $return;
7161: }
7162:
7163: my $cuname=unpack("%32C*",$funame);
7164: my $cudom=unpack("%32C*",$fudom);
7165: my $cucourseid=unpack("%32C*",$fucourseid);
7166: my $cusymb=unpack("%32C*",$fusymb);
7167: my $cunique=&recunique($fucourseid);
7168: my $cpart=unpack("%32S*",$part);
7169: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7170:
7171: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
7172:
7173: $return.= ($cunique%$cuname+
7174: $cunique%$cudom+
7175: $cusymb%$cuname+
7176: $cusymb%$cudom+
7177: $cucourseid%$cuname+
7178: $cucourseid%$cudom+
7179: $cpart%$cuname+
7180: $cpart%$cudom);
7181: } else {
7182: $return.= ($cunique%$cuname+
7183: $cunique%$cudom+
7184: $cusymb%$cuname+
7185: $cusymb%$cudom+
7186: $cucourseid%$cuname+
7187: $cucourseid%$cudom);
7188: }
7189: return $return;
7190: }
7191:
7192: sub receipt {
7193: my ($part)=@_;
7194: my ($symb,$courseid,$domain,$name) = &whichuser();
7195: return &ireceipt($name,$domain,$courseid,$symb,$part);
7196: }
7197:
7198: sub whichuser {
7199: my ($passedsymb)=@_;
7200: my ($symb,$courseid,$domain,$name,$publicuser);
7201: if (defined($env{'form.grade_symb'})) {
7202: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7203: my $allowed=&allowed('vgr',$tmp_courseid);
7204: if (!$allowed &&
7205: exists($env{'request.course.sec'}) &&
7206: $env{'request.course.sec'} !~ /^\s*$/) {
7207: $allowed=&allowed('vgr',$tmp_courseid.
7208: '/'.$env{'request.course.sec'});
7209: }
7210: if ($allowed) {
7211: ($symb)=&get_env_multiple('form.grade_symb');
7212: $courseid=$tmp_courseid;
7213: ($domain)=&get_env_multiple('form.grade_domain');
7214: ($name)=&get_env_multiple('form.grade_username');
7215: return ($symb,$courseid,$domain,$name,$publicuser);
7216: }
7217: }
7218: if (!$passedsymb) {
7219: $symb=&symbread();
7220: } else {
7221: $symb=$passedsymb;
7222: }
7223: $courseid=$env{'request.course.id'};
7224: $domain=$env{'user.domain'};
7225: $name=$env{'user.name'};
7226: if ($name eq 'public' && $domain eq 'public') {
7227: if (!defined($env{'form.username'})) {
7228: $env{'form.username'}.=time.rand(10000000);
7229: }
7230: $name.=$env{'form.username'};
7231: }
7232: return ($symb,$courseid,$domain,$name,$publicuser);
7233:
7234: }
7235:
7236: # ------------------------------------------------------------ Serves up a file
7237: # returns either the contents of the file or
7238: # -1 if the file doesn't exist
7239: #
7240: # if the target is a file that was uploaded via DOCS,
7241: # a check will be made to see if a current copy exists on the local server,
7242: # if it does this will be served, otherwise a copy will be retrieved from
7243: # the home server for the course and stored in /home/httpd/html/userfiles on
7244: # the local server.
7245:
7246: sub getfile {
7247: my ($file) = @_;
7248: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7249: &repcopy($file);
7250: return &readfile($file);
7251: }
7252:
7253: sub repcopy_userfile {
7254: my ($file)=@_;
7255: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
7256: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
7257: my ($cdom,$cnum,$filename) =
7258: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
7259: my $uri="/uploaded/$cdom/$cnum/$filename";
7260: if (-e "$file") {
7261: # we already have a local copy, check it out
7262: my @fileinfo = stat($file);
7263: my $rtncode;
7264: my $info;
7265: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
7266: if ($lwpresp ne 'ok') {
7267: # there is no such file anymore, even though we had a local copy
7268: if ($rtncode eq '404') {
7269: unlink($file);
7270: }
7271: return -1;
7272: }
7273: if ($info < $fileinfo[9]) {
7274: # nice, the file we have is up-to-date, just say okay
7275: return 'ok';
7276: } else {
7277: # the file is outdated, get rid of it
7278: unlink($file);
7279: }
7280: }
7281: # one way or the other, at this point, we don't have the file
7282: # construct the correct path for the file
7283: my @parts = ($cdom,$cnum);
7284: if ($filename =~ m|^(.+)/[^/]+$|) {
7285: push @parts, split(/\//,$1);
7286: }
7287: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7288: foreach my $part (@parts) {
7289: $path .= '/'.$part;
7290: if (!-e $path) {
7291: mkdir($path,0770);
7292: }
7293: }
7294: # now the path exists for sure
7295: # get a user agent
7296: my $ua=new LWP::UserAgent;
7297: my $transferfile=$file.'.in.transfer';
7298: # FIXME: this should flock
7299: if (-e $transferfile) { return 'ok'; }
7300: my $request;
7301: $uri=~s/^\///;
7302: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
7303: my $response=$ua->request($request,$transferfile);
7304: # did it work?
7305: if ($response->is_error()) {
7306: unlink($transferfile);
7307: &logthis("Userfile repcopy failed for $uri");
7308: return -1;
7309: }
7310: # worked, rename the transfer file
7311: rename($transferfile,$file);
7312: return 'ok';
7313: }
7314:
7315: sub tokenwrapper {
7316: my $uri=shift;
7317: $uri=~s|^http\://([^/]+)||;
7318: $uri=~s|^/||;
7319: $env{'user.environment'}=~/\/([^\/]+)\.id/;
7320: my $token=$1;
7321: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7322: if ($udom && $uname && $file) {
7323: $file=~s|(\?\.*)*$||;
7324: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
7325: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
7326: (($uri=~/\?/)?'&':'?').'token='.$token.
7327: '&tokenissued='.$perlvar{'lonHostID'};
7328: } else {
7329: return '/adm/notfound.html';
7330: }
7331: }
7332:
7333: # call with reqtype HEAD: get last modification time
7334: # call with reqtype GET: get the file contents
7335: # Do not call this with reqtype GET for large files! It loads everything into memory
7336: #
7337: sub getuploaded {
7338: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7339: $uri=~s/^\///;
7340: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
7341: my $ua=new LWP::UserAgent;
7342: my $request=new HTTP::Request($reqtype,$uri);
7343: my $response=$ua->request($request);
7344: $$rtncode = $response->code;
7345: if (! $response->is_success()) {
7346: return 'failed';
7347: }
7348: if ($reqtype eq 'HEAD') {
7349: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
7350: } elsif ($reqtype eq 'GET') {
7351: $$info = $response->content;
7352: }
7353: return 'ok';
7354: }
7355:
7356: sub readfile {
7357: my $file = shift;
7358: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7359: my $fh;
7360: open($fh,"<$file");
7361: my $a='';
7362: while (my $line = <$fh>) { $a .= $line; }
7363: return $a;
7364: }
7365:
7366: sub filelocation {
7367: my ($dir,$file) = @_;
7368: my $location;
7369: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
7370:
7371: if ($file =~ m-^/adm/-) {
7372: $file=~s-^/adm/wrapper/-/-;
7373: $file=~s-^/adm/coursedocs/showdoc/-/-;
7374: }
7375: if ($file=~m:^/~:) { # is a contruction space reference
7376: $location = $file;
7377: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
7378: } elsif ($file=~m{^/home/$match_username/public_html/}) {
7379: # is a correct contruction space reference
7380: $location = $file;
7381: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
7382: my ($udom,$uname,$filename)=
7383: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
7384: my $home=&homeserver($uname,$udom);
7385: my $is_me=0;
7386: my @ids=¤t_machine_ids();
7387: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7388: if ($is_me) {
7389: $location=&propath($udom,$uname).
7390: '/userfiles/'.$filename;
7391: } else {
7392: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7393: $udom.'/'.$uname.'/'.$filename;
7394: }
7395: } else {
7396: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7397: $file=~s:^/res/:/:;
7398: if ( !( $file =~ m:^/:) ) {
7399: $location = $dir. '/'.$file;
7400: } else {
7401: $location = '/home/httpd/html/res'.$file;
7402: }
7403: }
7404: $location=~s://+:/:g; # remove duplicate /
7405: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7406: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7407: return $location;
7408: }
7409:
7410: sub hreflocation {
7411: my ($dir,$file)=@_;
7412: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
7413: $file=filelocation($dir,$file);
7414: } elsif ($file=~m-^/adm/-) {
7415: $file=~s-^/adm/wrapper/-/-;
7416: $file=~s-^/adm/coursedocs/showdoc/-/-;
7417: }
7418: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7419: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7420: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7421: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
7422: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7423: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
7424: -/uploaded/$1/$2/-x;
7425: }
7426: return $file;
7427: }
7428:
7429: sub current_machine_domains {
7430: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7431: }
7432:
7433: sub machine_domains {
7434: my ($hostname) = @_;
7435: my @domains;
7436: my %hostname = &all_hostnames();
7437: while( my($id, $name) = each(%hostname)) {
7438: # &logthis("-$id-$name-$hostname-");
7439: if ($hostname eq $name) {
7440: push(@domains,&host_domain($id));
7441: }
7442: }
7443: return @domains;
7444: }
7445:
7446: sub current_machine_ids {
7447: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7448: }
7449:
7450: sub machine_ids {
7451: my ($hostname) = @_;
7452: $hostname ||= &hostname($perlvar{'lonHostID'});
7453: my @ids;
7454: my %hostname = &all_hostnames();
7455: while( my($id, $name) = each(%hostname)) {
7456: # &logthis("-$id-$name-$hostname-");
7457: if ($hostname eq $name) {
7458: push(@ids,$id);
7459: }
7460: }
7461: return @ids;
7462: }
7463:
7464: sub additional_machine_domains {
7465: my @domains;
7466: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7467: while( my $line = <$fh>) {
7468: $line =~ s/\s//g;
7469: push(@domains,$line);
7470: }
7471: return @domains;
7472: }
7473:
7474: sub default_login_domain {
7475: my $domain = $perlvar{'lonDefDomain'};
7476: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7477: foreach my $posdom (¤t_machine_domains(),
7478: &additional_machine_domains()) {
7479: if (lc($posdom) eq lc($testdomain)) {
7480: $domain=$posdom;
7481: last;
7482: }
7483: }
7484: return $domain;
7485: }
7486:
7487: # ------------------------------------------------------------- Declutters URLs
7488:
7489: sub declutter {
7490: my $thisfn=shift;
7491: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7492: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7493: $thisfn=~s/^\///;
7494: $thisfn=~s|^adm/wrapper/||;
7495: $thisfn=~s|^adm/coursedocs/showdoc/||;
7496: $thisfn=~s/^res\///;
7497: $thisfn=~s/\?.+$//;
7498: return $thisfn;
7499: }
7500:
7501: # ------------------------------------------------------------- Clutter up URLs
7502:
7503: sub clutter {
7504: my $thisfn='/'.&declutter(shift);
7505: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
7506: $thisfn='/res'.$thisfn;
7507: }
7508: if ($thisfn !~m|/adm|) {
7509: if ($thisfn =~ m|/ext/|) {
7510: $thisfn='/adm/wrapper'.$thisfn;
7511: } else {
7512: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7513: my $embstyle=&Apache::loncommon::fileembstyle($ext);
7514: if ($embstyle eq 'ssi'
7515: || ($embstyle eq 'hdn')
7516: || ($embstyle eq 'rat')
7517: || ($embstyle eq 'prv')
7518: || ($embstyle eq 'ign')) {
7519: #do nothing with these
7520: } elsif (($embstyle eq 'img')
7521: || ($embstyle eq 'emb')
7522: || ($embstyle eq 'wrp')) {
7523: $thisfn='/adm/wrapper'.$thisfn;
7524: } elsif ($embstyle eq 'unk'
7525: && $thisfn!~/\.(sequence|page)$/) {
7526: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
7527: } else {
7528: # &logthis("Got a blank emb style");
7529: }
7530: }
7531: }
7532: return $thisfn;
7533: }
7534:
7535: sub clutter_with_no_wrapper {
7536: my $uri = &clutter(shift);
7537: if ($uri =~ m-^/adm/-) {
7538: $uri =~ s-^/adm/wrapper/-/-;
7539: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7540: }
7541: return $uri;
7542: }
7543:
7544: sub freeze_escape {
7545: my ($value)=@_;
7546: if (ref($value)) {
7547: $value=&nfreeze($value);
7548: return '__FROZEN__'.&escape($value);
7549: }
7550: return &escape($value);
7551: }
7552:
7553:
7554: sub thaw_unescape {
7555: my ($value)=@_;
7556: if ($value =~ /^__FROZEN__/) {
7557: substr($value,0,10,undef);
7558: $value=&unescape($value);
7559: return &thaw($value);
7560: }
7561: return &unescape($value);
7562: }
7563:
7564: sub correct_line_ends {
7565: my ($result)=@_;
7566: $$result =~s/\r\n/\n/mg;
7567: $$result =~s/\r/\n/mg;
7568: }
7569: # ================================================================ Main Program
7570:
7571: sub goodbye {
7572: &logthis("Starting Shut down");
7573: #not converted to using infrastruture and probably shouldn't be
7574: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
7575: #converted
7576: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7577: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7578: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7579: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
7580: #1.1 only
7581: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7582: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7583: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7584: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7585: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7586: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7587: &logthis(sprintf("%-20s is %s",'hits',$hits));
7588: &flushcourselogs();
7589: &logthis("Shutting down");
7590: }
7591:
7592: BEGIN {
7593: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7594: unless ($readit) {
7595: {
7596: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7597: %perlvar = (%perlvar,%{$configvars});
7598: }
7599:
7600: sub get_dns {
7601: my ($url,$func) = @_;
7602: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7603: foreach my $dns (<$config>) {
7604: next if ($dns !~ /^\^(\S*)/x);
7605: $dns = $1;
7606: my $ua=new LWP::UserAgent;
7607: my $request=new HTTP::Request('GET',"http://$dns$url");
7608: my $response=$ua->request($request);
7609: next if ($response->is_error());
7610: my @content = split("\n",$response->content);
7611: &$func(\@content);
7612: }
7613: close($config);
7614: }
7615: # ------------------------------------------------------------ Read domain file
7616: {
7617: my $loaded;
7618: my %domain;
7619:
7620: sub parse_domain_tab {
7621: my ($lines) = @_;
7622: foreach my $line (@$lines) {
7623: next if ($line =~ /^(\#|\s*$ )/x);
7624:
7625: chomp($line);
7626: my ($name,@elements) = split(/:/,$line,9);
7627: my %this_domain;
7628: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7629: 'lang_def', 'city', 'longi', 'lati',
7630: 'primary') {
7631: $this_domain{$field} = shift(@elements);
7632: }
7633: $domain{$name} = \%this_domain;
7634: &logthis("Domain.tab: $name ".$domain{$name}{'description'} );
7635: }
7636: }
7637:
7638: sub load_domain_tab {
7639: &get_dns('/adm/dns/domain',\&parse_domain_tab);
7640: my $fh;
7641: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7642: my @lines = <$fh>;
7643: &parse_domain_tab(\@lines);
7644: }
7645: close($fh);
7646: $loaded = 1;
7647: }
7648:
7649: sub domain {
7650: &load_domain_tab() if (!$loaded);
7651:
7652: my ($name,$what) = @_;
7653: return if ( !exists($domain{$name}) );
7654:
7655: if (!$what) {
7656: return $domain{$name}{'description'};
7657: }
7658: return $domain{$name}{$what};
7659: }
7660: }
7661:
7662:
7663: # ------------------------------------------------------------- Read hosts file
7664: {
7665: my %hostname;
7666: my %hostdom;
7667: my %libserv;
7668: my $loaded;
7669:
7670: sub parse_hosts_tab {
7671: my ($file) = @_;
7672: foreach my $configline (@$file) {
7673: next if ($configline =~ /^(\#|\s*$ )/x);
7674: next if ($configline =~ /^\^/);
7675: chomp($configline);
7676: my ($id,$domain,$role,$name)=split(/:/,$configline);
7677: $name=~s/\s//g;
7678: if ($id && $domain && $role && $name) {
7679: $hostname{$id}=$name;
7680: $hostdom{$id}=$domain;
7681: if ($role eq 'library') { $libserv{$id}=$name; }
7682: }
7683: &logthis("Hosts.tab: $name ".$id );
7684: }
7685: }
7686:
7687: sub load_hosts_tab {
7688: &get_dns('/adm/dns/hosts',\&parse_hosts_tab);
7689: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7690: my @config = <$config>;
7691: &parse_hosts_tab(\@config);
7692: close($config);
7693: $loaded=1;
7694: }
7695:
7696: # FIXME: dev server don't want this, production servers _do_ want this
7697: #&get_iphost();
7698:
7699: sub hostname {
7700: &load_hosts_tab() if (!$loaded);
7701:
7702: my ($lonid) = @_;
7703: return $hostname{$lonid};
7704: }
7705:
7706: sub all_hostnames {
7707: &load_hosts_tab() if (!$loaded);
7708:
7709: return %hostname;
7710: }
7711:
7712: sub is_library {
7713: &load_hosts_tab() if (!$loaded);
7714:
7715: return exists($libserv{$_[0]});
7716: }
7717:
7718: sub all_library {
7719: &load_hosts_tab() if (!$loaded);
7720:
7721: return %libserv;
7722: }
7723:
7724: sub get_servers {
7725: &load_hosts_tab() if (!$loaded);
7726:
7727: my ($domain,$type) = @_;
7728: my %possible_hosts = ($type eq 'library') ? %libserv
7729: : %hostname;
7730: my %result;
7731: if (ref($domain) eq 'ARRAY') {
7732: while ( my ($host,$hostname) = each(%possible_hosts)) {
7733: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
7734: $result{$host} = $hostname;
7735: }
7736: }
7737: } else {
7738: while ( my ($host,$hostname) = each(%possible_hosts)) {
7739: if ($hostdom{$host} eq $domain) {
7740: $result{$host} = $hostname;
7741: }
7742: }
7743: }
7744: return %result;
7745: }
7746:
7747: sub host_domain {
7748: &load_hosts_tab() if (!$loaded);
7749:
7750: my ($lonid) = @_;
7751: return $hostdom{$lonid};
7752: }
7753:
7754: sub all_domains {
7755: &load_hosts_tab() if (!$loaded);
7756:
7757: my %seen;
7758: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7759: return @uniq;
7760: }
7761: }
7762:
7763: {
7764: my %iphost;
7765: sub get_hosts_from_ip {
7766: my ($ip) = @_;
7767: my %iphosts = &get_iphost();
7768: if (ref($iphosts{$ip})) {
7769: return @{$iphosts{$ip}};
7770: }
7771: return;
7772: }
7773:
7774: sub get_iphost {
7775: if (%iphost) { return %iphost; }
7776: my %name_to_ip;
7777: my %hostname = &all_hostnames();
7778: foreach my $id (keys(%hostname)) {
7779: my $name=$hostname{$id};
7780: my $ip;
7781: if (!exists($name_to_ip{$name})) {
7782: $ip = gethostbyname($name);
7783: if (!$ip || length($ip) ne 4) {
7784: &logthis("Skipping host $id name $name no IP found");
7785: next;
7786: }
7787: $ip=inet_ntoa($ip);
7788: $name_to_ip{$name} = $ip;
7789: } else {
7790: $ip = $name_to_ip{$name};
7791: }
7792: push(@{$iphost{$ip}},$id);
7793: }
7794: return %iphost;
7795: }
7796: }
7797:
7798: # ------------------------------------------------------ Read spare server file
7799: {
7800: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7801:
7802: while (my $configline=<$config>) {
7803: chomp($configline);
7804: if ($configline) {
7805: my ($host,$type) = split(':',$configline,2);
7806: if (!defined($type) || $type eq '') { $type = 'default' };
7807: push(@{ $spareid{$type} }, $host);
7808: }
7809: }
7810: close($config);
7811: }
7812: # ------------------------------------------------------------ Read permissions
7813: {
7814: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7815:
7816: while (my $configline=<$config>) {
7817: chomp($configline);
7818: if ($configline) {
7819: my ($role,$perm)=split(/ /,$configline);
7820: if ($perm ne '') { $pr{$role}=$perm; }
7821: }
7822: }
7823: close($config);
7824: }
7825:
7826: # -------------------------------------------- Read plain texts for permissions
7827: {
7828: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7829:
7830: while (my $configline=<$config>) {
7831: chomp($configline);
7832: if ($configline) {
7833: my ($short,@plain)=split(/:/,$configline);
7834: %{$prp{$short}} = ();
7835: if (@plain > 0) {
7836: $prp{$short}{'std'} = $plain[0];
7837: for (my $i=1; $i<@plain; $i++) {
7838: $prp{$short}{'alt'.$i} = $plain[$i];
7839: }
7840: }
7841: }
7842: }
7843: close($config);
7844: }
7845:
7846: # ---------------------------------------------------------- Read package table
7847: {
7848: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7849:
7850: while (my $configline=<$config>) {
7851: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
7852: chomp($configline);
7853: my ($short,$plain)=split(/:/,$configline);
7854: my ($pack,$name)=split(/\&/,$short);
7855: if ($plain ne '') {
7856: $packagetab{$pack.'&'.$name.'&name'}=$name;
7857: $packagetab{$short}=$plain;
7858: }
7859: }
7860: close($config);
7861: }
7862:
7863: # ------------- set up temporary directory
7864: {
7865: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7866:
7867: }
7868:
7869: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7870: 'compress_threshold'=> 20_000,
7871: });
7872:
7873: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7874: $dumpcount=0;
7875:
7876: &logtouch();
7877: &logthis('<font color="yellow">INFO: Read configuration</font>');
7878: $readit=1;
7879: {
7880: use integer;
7881: my $test=(2**32)+1;
7882: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
7883: &logthis(" Detected 64bit platform ($_64bit)");
7884: }
7885: }
7886: }
7887:
7888: 1;
7889: __END__
7890:
7891: =pod
7892:
7893: =head1 NAME
7894:
7895: Apache::lonnet - Subroutines to ask questions about things in the network.
7896:
7897: =head1 SYNOPSIS
7898:
7899: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
7900:
7901: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7902:
7903: Common parameters:
7904:
7905: =over 4
7906:
7907: =item *
7908:
7909: $uname : an internal username (if $cname expecting a course Id specifically)
7910:
7911: =item *
7912:
7913: $udom : a domain (if $cdom expecting a course's domain specifically)
7914:
7915: =item *
7916:
7917: $symb : a resource instance identifier
7918:
7919: =item *
7920:
7921: $namespace : the name of a .db file that contains the data needed or
7922: being set.
7923:
7924: =back
7925:
7926: =head1 OVERVIEW
7927:
7928: lonnet provides subroutines which interact with the
7929: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7930: about classes, users, and resources.
7931:
7932: For many of these objects you can also use this to store data about
7933: them or modify them in various ways.
7934:
7935: =head2 Symbs
7936:
7937: To identify a specific instance of a resource, LON-CAPA uses symbols
7938: or "symbs"X<symb>. These identifiers are built from the URL of the
7939: map, the resource number of the resource in the map, and the URL of
7940: the resource itself. The latter is somewhat redundant, but might help
7941: if maps change.
7942:
7943: An example is
7944:
7945: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7946:
7947: The respective map entry is
7948:
7949: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7950: title="Problem 2">
7951: </resource>
7952:
7953: Symbs are used by the random number generator, as well as to store and
7954: restore data specific to a certain instance of for example a problem.
7955:
7956: =head2 Storing And Retrieving Data
7957:
7958: X<store()>X<cstore()>X<restore()>Three of the most important functions
7959: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7960: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7961: is is the non-critical message twin of cstore. These functions are for
7962: handlers to store a perl hash to a user's permanent data space in an
7963: easy manner, and to retrieve it again on another call. It is expected
7964: that a handler would use this once at the beginning to retrieve data,
7965: and then again once at the end to send only the new data back.
7966:
7967: The data is stored in the user's data directory on the user's
7968: homeserver under the ID of the course.
7969:
7970: The hash that is returned by restore will have all of the previous
7971: value for all of the elements of the hash.
7972:
7973: Example:
7974:
7975: #creating a hash
7976: my %hash;
7977: $hash{'foo'}='bar';
7978:
7979: #storing it
7980: &Apache::lonnet::cstore(\%hash);
7981:
7982: #changing a value
7983: $hash{'foo'}='notbar';
7984:
7985: #adding a new value
7986: $hash{'bar'}='foo';
7987: &Apache::lonnet::cstore(\%hash);
7988:
7989: #retrieving the hash
7990: my %history=&Apache::lonnet::restore();
7991:
7992: #print the hash
7993: foreach my $key (sort(keys(%history))) {
7994: print("\%history{$key} = $history{$key}");
7995: }
7996:
7997: Will print out:
7998:
7999: %history{1:foo} = bar
8000: %history{1:keys} = foo:timestamp
8001: %history{1:timestamp} = 990455579
8002: %history{2:bar} = foo
8003: %history{2:foo} = notbar
8004: %history{2:keys} = foo:bar:timestamp
8005: %history{2:timestamp} = 990455580
8006: %history{bar} = foo
8007: %history{foo} = notbar
8008: %history{timestamp} = 990455580
8009: %history{version} = 2
8010:
8011: Note that the special hash entries C<keys>, C<version> and
8012: C<timestamp> were added to the hash. C<version> will be equal to the
8013: total number of versions of the data that have been stored. The
8014: C<timestamp> attribute will be the UNIX time the hash was
8015: stored. C<keys> is available in every historical section to list which
8016: keys were added or changed at a specific historical revision of a
8017: hash.
8018:
8019: B<Warning>: do not store the hash that restore returns directly. This
8020: will cause a mess since it will restore the historical keys as if the
8021: were new keys. I.E. 1:foo will become 1:1:foo etc.
8022:
8023: Calling convention:
8024:
8025: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8026: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
8027:
8028: For more detailed information, see lonnet specific documentation.
8029:
8030: =head1 RETURN MESSAGES
8031:
8032: =over 4
8033:
8034: =item * B<con_lost>: unable to contact remote host
8035:
8036: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8037: when the connection is brought back up
8038:
8039: =item * B<con_failed>: unable to contact remote host and unable to save message
8040: for later delivery
8041:
8042: =item * B<error:>: an error a occured, a description of the error follows the :
8043:
8044: =item * B<no_such_host>: unable to fund a host associated with the user/domain
8045: that was requested
8046:
8047: =back
8048:
8049: =head1 PUBLIC SUBROUTINES
8050:
8051: =head2 Session Environment Functions
8052:
8053: =over 4
8054:
8055: =item *
8056: X<appenv()>
8057: B<appenv(%hash)>: the value of %hash is written to
8058: the user envirnoment file, and will be restored for each access this
8059: user makes during this session, also modifies the %env for the current
8060: process
8061:
8062: =item *
8063: X<delenv()>
8064: B<delenv($regexp)>: removes all items from the session
8065: environment file that matches the regular expression in $regexp. The
8066: values are also delted from the current processes %env.
8067:
8068: =item * get_env_multiple($name)
8069:
8070: gets $name from the %env hash, it seemlessly handles the cases where multiple
8071: values may be defined and end up as an array ref.
8072:
8073: returns an array of values
8074:
8075: =back
8076:
8077: =head2 User Information
8078:
8079: =over 4
8080:
8081: =item *
8082: X<queryauthenticate()>
8083: B<queryauthenticate($uname,$udom)>: try to determine user's current
8084: authentication scheme
8085:
8086: =item *
8087: X<authenticate()>
8088: B<authenticate($uname,$upass,$udom)>: try to
8089: authenticate user from domain's lib servers (first use the current
8090: one). C<$upass> should be the users password.
8091:
8092: =item *
8093: X<homeserver()>
8094: B<homeserver($uname,$udom)>: find the server which has
8095: the user's directory and files (there must be only one), this caches
8096: the answer, and also caches if there is a borken connection.
8097:
8098: =item *
8099: X<idget()>
8100: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8101: (IDs are a unique resource in a domain, there must be only 1 ID per
8102: username, and only 1 username per ID in a specific domain) (returns
8103: hash: id=>name,id=>name)
8104:
8105: =item *
8106: X<idrget()>
8107: B<idrget($udom,@unames)>: find the IDs behind a list of
8108: usernames (returns hash: name=>id,name=>id)
8109:
8110: =item *
8111: X<idput()>
8112: B<idput($udom,%ids)>: store away a list of names and associated IDs
8113:
8114: =item *
8115: X<rolesinit()>
8116: B<rolesinit($udom,$username,$authhost)>: get user privileges
8117:
8118: =item *
8119: X<getsection()>
8120: B<getsection($udom,$uname,$cname)>: finds the section of student in the
8121: course $cname, return section name/number or '' for "not in course"
8122: and '-1' for "no section"
8123:
8124: =item *
8125: X<userenvironment()>
8126: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
8127: passed in @what from the requested user's environment, returns a hash
8128:
8129: =back
8130:
8131: =head2 User Roles
8132:
8133: =over 4
8134:
8135: =item *
8136:
8137: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
8138: F: full access
8139: U,I,K: authentication modes (cxx only)
8140: '': forbidden
8141: 1: user needs to choose course
8142: 2: browse allowed
8143: A: passphrase authentication needed
8144:
8145: =item *
8146:
8147: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8148: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8149: and course level
8150:
8151: =item *
8152:
8153: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8154: explanation of a user role term
8155:
8156: =item *
8157:
8158: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
8159: optional. Returns a hash of a user's roles, with keys set to
8160: colon-sparated $uname,$udom,and $role, and value set to
8161: colon-separated start and end times for the role. If no username and
8162: domain are specified, will default to current user/domain. Types,
8163: roles, and roledoms are references to arrays, of role statuses
8164: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
8165: of the roles which can be used to restrict the list if roles
8166: reported. If no array ref is provided for types, will default to
8167: return only active roles.
8168:
8169: =back
8170:
8171: =head2 User Modification
8172:
8173: =over 4
8174:
8175: =item *
8176:
8177: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8178: user for the level given by URL. Optional start and end dates (leave empty
8179: string or zero for "no date")
8180:
8181: =item *
8182:
8183: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8184: change a users, password, possible return values are: ok,
8185: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8186: refused
8187:
8188: =item *
8189:
8190: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
8191:
8192: =item *
8193:
8194: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8195: modify user
8196:
8197: =item *
8198:
8199: modifystudent
8200:
8201: modify a students enrollment and identification information.
8202: The course id is resolved based on the current users environment.
8203: This means the envoking user must be a course coordinator or otherwise
8204: associated with a course.
8205:
8206: This call is essentially a wrapper for lonnet::modifyuser and
8207: lonnet::modify_student_enrollment
8208:
8209: Inputs:
8210:
8211: =over 4
8212:
8213: =item B<$udom> Students loncapa domain
8214:
8215: =item B<$uname> Students loncapa login name
8216:
8217: =item B<$uid> Students id/student number
8218:
8219: =item B<$umode> Students authentication mode
8220:
8221: =item B<$upass> Students password
8222:
8223: =item B<$first> Students first name
8224:
8225: =item B<$middle> Students middle name
8226:
8227: =item B<$last> Students last name
8228:
8229: =item B<$gene> Students generation
8230:
8231: =item B<$usec> Students section in course
8232:
8233: =item B<$end> Unix time of the roles expiration
8234:
8235: =item B<$start> Unix time of the roles start date
8236:
8237: =item B<$forceid> If defined, allow $uid to be changed
8238:
8239: =item B<$desiredhome> server to use as home server for student
8240:
8241: =back
8242:
8243: =item *
8244:
8245: modify_student_enrollment
8246:
8247: Change a students enrollment status in a class. The environment variable
8248: 'role.request.course' must be defined for this function to proceed.
8249:
8250: Inputs:
8251:
8252: =over 4
8253:
8254: =item $udom, students domain
8255:
8256: =item $uname, students name
8257:
8258: =item $uid, students user id
8259:
8260: =item $first, students first name
8261:
8262: =item $middle
8263:
8264: =item $last
8265:
8266: =item $gene
8267:
8268: =item $usec
8269:
8270: =item $end
8271:
8272: =item $start
8273:
8274: =back
8275:
8276:
8277: =item *
8278:
8279: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8280: custom role; give a custom role to a user for the level given by URL. Specify
8281: name and domain of role author, and role name
8282:
8283: =item *
8284:
8285: revokerole($udom,$uname,$url,$role) : revoke a role for url
8286:
8287: =item *
8288:
8289: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8290:
8291: =back
8292:
8293: =head2 Course Infomation
8294:
8295: =over 4
8296:
8297: =item *
8298:
8299: coursedescription($courseid) : returns a hash of information about the
8300: specified course id, including all environment settings for the
8301: course, the description of the course will be in the hash under the
8302: key 'description'
8303:
8304: =item *
8305:
8306: resdata($name,$domain,$type,@which) : request for current parameter
8307: setting for a specific $type, where $type is either 'course' or 'user',
8308: @what should be a list of parameters to ask about. This routine caches
8309: answers for 5 minutes.
8310:
8311: =back
8312:
8313: =head2 Course Modification
8314:
8315: =over 4
8316:
8317: =item *
8318:
8319: writecoursepref($courseid,%prefs) : write preferences (environment
8320: database) for a course
8321:
8322: =item *
8323:
8324: createcourse($udom,$description,$url) : make/modify course
8325:
8326: =back
8327:
8328: =head2 Resource Subroutines
8329:
8330: =over 4
8331:
8332: =item *
8333:
8334: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
8335:
8336: =item *
8337:
8338: repcopy($filename) : subscribes to the requested file, and attempts to
8339: replicate from the owning library server, Might return
8340: 'unavailable', 'not_found', 'forbidden', 'ok', or
8341: 'bad_request', also attempts to grab the metadata for the
8342: resource. Expects the local filesystem pathname
8343: (/home/httpd/html/res/....)
8344:
8345: =back
8346:
8347: =head2 Resource Information
8348:
8349: =over 4
8350:
8351: =item *
8352:
8353: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8354: a vairety of different possible values, $varname should be a request
8355: string, and the other parameters can be used to specify who and what
8356: one is asking about.
8357:
8358: Possible values for $varname are environment.lastname (or other item
8359: from the envirnment hash), user.name (or someother aspect about the
8360: user), resource.0.maxtries (or some other part and parameter of a
8361: resource)
8362:
8363: =item *
8364:
8365: directcondval($number) : get current value of a condition; reads from a state
8366: string
8367:
8368: =item *
8369:
8370: condval($condidx) : value of condition index based on state
8371:
8372: =item *
8373:
8374: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8375: resource's metadata, $what should be either a specific key, or either
8376: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8377: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8378:
8379: this function automatically caches all requests
8380:
8381: =item *
8382:
8383: metadata_query($query,$custom,$customshow) : make a metadata query against the
8384: network of library servers; returns file handle of where SQL and regex results
8385: will be stored for query
8386:
8387: =item *
8388:
8389: symbread($filename) : return symbolic list entry (filename argument optional);
8390: returns the data handle
8391:
8392: =item *
8393:
8394: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
8395: a possible symb for the URL in $thisfn, and if is an encryypted
8396: resource that the user accessed using /enc/ returns a 1 on success, 0
8397: on failure, user must be in a course, as it assumes the existance of
8398: the course initial hash, and uses $env('request.course.id'}
8399:
8400:
8401: =item *
8402:
8403: symbclean($symb) : removes versions numbers from a symb, returns the
8404: cleaned symb
8405:
8406: =item *
8407:
8408: is_on_map($uri) : checks if the $uri is somewhere on the current
8409: course map, user must be in a course for it to work.
8410:
8411: =item *
8412:
8413: numval($salt) : return random seed value (addend for rndseed)
8414:
8415: =item *
8416:
8417: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8418: a random seed, all arguments are optional, if they aren't sent it uses the
8419: environment to derive them. Note: if symb isn't sent and it can't get one
8420: from &symbread it will use the current time as its return value
8421:
8422: =item *
8423:
8424: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8425: unfakeable, receipt
8426:
8427: =item *
8428:
8429: receipt() : API to ireceipt working off of env values; given out to users
8430:
8431: =item *
8432:
8433: countacc($url) : count the number of accesses to a given URL
8434:
8435: =item *
8436:
8437: 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
8438:
8439: =item *
8440:
8441: 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)
8442:
8443: =item *
8444:
8445: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
8446:
8447: =item *
8448:
8449: devalidate($symb) : devalidate temporary spreadsheet calculations,
8450: forcing spreadsheet to reevaluate the resource scores next time.
8451:
8452: =back
8453:
8454: =head2 Storing/Retreiving Data
8455:
8456: =over 4
8457:
8458: =item *
8459:
8460: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8461: for this url; hashref needs to be given and should be a \%hashname; the
8462: remaining args aren't required and if they aren't passed or are '' they will
8463: be derived from the env
8464:
8465: =item *
8466:
8467: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8468: uses critical subroutine
8469:
8470: =item *
8471:
8472: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8473: all args are optional
8474:
8475: =item *
8476:
8477: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8478: dumps the complete (or key matching regexp) namespace into a hash
8479: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8480: normally &store()ed into
8481:
8482: $range should be either an integer '100' (give me the first 100
8483: matching records)
8484: or be two integers sperated by a - with no spaces
8485: '30-50' (give me the 30th through the 50th matching
8486: records)
8487:
8488:
8489: =item *
8490:
8491: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8492: replaces a &store() version of data with a replacement set of data
8493: for a particular resource in a namespace passed in the $storehash hash
8494: reference
8495:
8496: =item *
8497:
8498: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8499: works very similar to store/cstore, but all data is stored in a
8500: temporary location and can be reset using tmpreset, $storehash should
8501: be a hash reference, returns nothing on success
8502:
8503: =item *
8504:
8505: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8506: similar to restore, but all data is stored in a temporary location and
8507: can be reset using tmpreset. Returns a hash of values on success,
8508: error string otherwise.
8509:
8510: =item *
8511:
8512: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8513: deltes all keys for $symb form the temporary storage hash.
8514:
8515: =item *
8516:
8517: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8518: reference filled in from namesp ($udom and $uname are optional)
8519:
8520: =item *
8521:
8522: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8523: namesp ($udom and $uname are optional)
8524:
8525: =item *
8526:
8527: dump($namespace,$udom,$uname,$regexp,$range) :
8528: dumps the complete (or key matching regexp) namespace into a hash
8529: ($udom, $uname, $regexp, $range are optional)
8530:
8531: $range should be either an integer '100' (give me the first 100
8532: matching records)
8533: or be two integers sperated by a - with no spaces
8534: '30-50' (give me the 30th through the 50th matching
8535: records)
8536: =item *
8537:
8538: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8539: $store can be a scalar, an array reference, or if the amount to be
8540: incremented is > 1, a hash reference.
8541:
8542: ($udom and $uname are optional)
8543:
8544: =item *
8545:
8546: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8547: ($udom and $uname are optional)
8548:
8549: =item *
8550:
8551: cput($namespace,$storehash,$udom,$uname) : critical put
8552: ($udom and $uname are optional)
8553:
8554: =item *
8555:
8556: newput($namespace,$storehash,$udom,$uname) :
8557:
8558: Attempts to store the items in the $storehash, but only if they don't
8559: currently exist, if this succeeds you can be certain that you have
8560: successfully created a new key value pair in the $namespace db.
8561:
8562:
8563: Args:
8564: $namespace: name of database to store values to
8565: $storehash: hashref to store to the db
8566: $udom: (optional) domain of user containing the db
8567: $uname: (optional) name of user caontaining the db
8568:
8569: Returns:
8570: 'ok' -> succeeded in storing all keys of $storehash
8571: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8572: least <key> already existed in the db (other
8573: requested keys may also already exist)
8574: 'error: <msg>' -> unable to tie the DB or other erorr occured
8575: 'con_lost' -> unable to contact request server
8576: 'refused' -> action was not allowed by remote machine
8577:
8578:
8579: =item *
8580:
8581: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8582: reference filled in from namesp (encrypts the return communication)
8583: ($udom and $uname are optional)
8584:
8585: =item *
8586:
8587: log($udom,$name,$home,$message) : write to permanent log for user; use
8588: critical subroutine
8589:
8590: =item *
8591:
8592: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
8593: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
8594:
8595: =item *
8596:
8597: put_dom($namespace,$storehash,$udomain) : stores hash in namespace at domain level on primary domain server ($udomain is optional)
8598:
8599: =back
8600:
8601: =head2 Network Status Functions
8602:
8603: =over 4
8604:
8605: =item *
8606:
8607: dirlist($uri) : return directory list based on URI
8608:
8609: =item *
8610:
8611: spareserver() : find server with least workload from spare.tab
8612:
8613: =back
8614:
8615: =head2 Apache Request
8616:
8617: =over 4
8618:
8619: =item *
8620:
8621: ssi($url,%hash) : server side include, does a complete request cycle on url to
8622: localhost, posts hash
8623:
8624: =back
8625:
8626: =head2 Data to String to Data
8627:
8628: =over 4
8629:
8630: =item *
8631:
8632: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8633: and '&' separators, supports elements that are arrayrefs and hashrefs
8634:
8635: =item *
8636:
8637: hashref2str($hashref) : convert a hashref into a string complete with
8638: escaping and '=' and '&' separators, supports elements that are
8639: arrayrefs and hashrefs
8640:
8641: =item *
8642:
8643: arrayref2str($arrayref) : convert an arrayref into a string complete
8644: with escaping and '&' separators, supports elements that are arrayrefs
8645: and hashrefs
8646:
8647: =item *
8648:
8649: str2hash($string) : convert string to hash using unescaping and
8650: splitting on '=' and '&', supports elements that are arrayrefs and
8651: hashrefs
8652:
8653: =item *
8654:
8655: str2array($string) : convert string to hash using unescaping and
8656: splitting on '&', supports elements that are arrayrefs and hashrefs
8657:
8658: =back
8659:
8660: =head2 Logging Routines
8661:
8662: =over 4
8663:
8664: These routines allow one to make log messages in the lonnet.log and
8665: lonnet.perm logfiles.
8666:
8667: =item *
8668:
8669: logtouch() : make sure the logfile, lonnet.log, exists
8670:
8671: =item *
8672:
8673: logthis() : append message to the normal lonnet.log file, it gets
8674: preiodically rolled over and deleted.
8675:
8676: =item *
8677:
8678: logperm() : append a permanent message to lonnet.perm.log, this log
8679: file never gets deleted by any automated portion of the system, only
8680: messages of critical importance should go in here.
8681:
8682: =back
8683:
8684: =head2 General File Helper Routines
8685:
8686: =over 4
8687:
8688: =item *
8689:
8690: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8691: (a) files in /uploaded
8692: (i) If a local copy of the file exists -
8693: compares modification date of local copy with last-modified date for
8694: definitive version stored on home server for course. If local copy is
8695: stale, requests a new version from the home server and stores it.
8696: If the original has been removed from the home server, then local copy
8697: is unlinked.
8698: (ii) If local copy does not exist -
8699: requests the file from the home server and stores it.
8700:
8701: If $caller is 'uploadrep':
8702: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8703: for request for files originally uploaded via DOCS.
8704: - returns 'ok' if fresh local copy now available, -1 otherwise.
8705:
8706: Otherwise:
8707: This indicates a call from the content generation phase of the request.
8708: - returns the entire contents of the file or -1.
8709:
8710: (b) files in /res
8711: - returns the entire contents of a file or -1;
8712: it properly subscribes to and replicates the file if neccessary.
8713:
8714:
8715: =item *
8716:
8717: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8718: reference
8719:
8720: returns either a stat() list of data about the file or an empty list
8721: if the file doesn't exist or couldn't find out about it (connection
8722: problems or user unknown)
8723:
8724: =item *
8725:
8726: filelocation($dir,$file) : returns file system location of a file
8727: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8728: directory that relative $file lookups are to looked in ($dir of /a/dir
8729: and a file of ../bob will become /a/bob)
8730:
8731: =item *
8732:
8733: hreflocation($dir,$file) : returns file system location or a URL; same as
8734: filelocation except for hrefs
8735:
8736: =item *
8737:
8738: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8739:
8740: =back
8741:
8742: =head2 Usererfile file routines (/uploaded*)
8743:
8744: =over 4
8745:
8746: =item *
8747:
8748: userfileupload(): main rotine for putting a file in a user or course's
8749: filespace, arguments are,
8750:
8751: formname - required - this is the name of the element in $env where the
8752: filename, and the contents of the file to create/modifed exist
8753: the filename is in $env{'form.'.$formname.'.filename'} and the
8754: contents of the file is located in $env{'form.'.$formname}
8755: coursedoc - if true, store the file in the course of the active role
8756: of the current user
8757: subdir - required - subdirectory to put the file in under ../userfiles/
8758: if undefined, it will be placed in "unknown"
8759:
8760: (This routine calls clean_filename() to remove any dangerous
8761: characters from the filename, and then calls finuserfileupload() to
8762: complete the transaction)
8763:
8764: returns either the url of the uploaded file (/uploaded/....) if successful
8765: and /adm/notfound.html if unsuccessful
8766:
8767: =item *
8768:
8769: clean_filename(): routine for cleaing a filename up for storage in
8770: userfile space, argument is:
8771:
8772: filename - proposed filename
8773:
8774: returns: the new clean filename
8775:
8776: =item *
8777:
8778: finishuserfileupload(): routine that creaes and sends the file to
8779: userspace, probably shouldn't be called directly
8780:
8781: docuname: username or courseid of destination for the file
8782: docudom: domain of user/course of destination for the file
8783: formname: same as for userfileupload()
8784: fname: filename (inculding subdirectories) for the file
8785:
8786: returns either the url of the uploaded file (/uploaded/....) if successful
8787: and /adm/notfound.html if unsuccessful
8788:
8789: =item *
8790:
8791: renameuserfile(): renames an existing userfile to a new name
8792:
8793: Args:
8794: docuname: username or courseid of destination for the file
8795: docudom: domain of user/course of destination for the file
8796: old: current file name (including any subdirs under userfiles)
8797: new: desired file name (including any subdirs under userfiles)
8798:
8799: =item *
8800:
8801: mkdiruserfile(): creates a directory is a userfiles dir
8802:
8803: Args:
8804: docuname: username or courseid of destination for the file
8805: docudom: domain of user/course of destination for the file
8806: dir: dir to create (including any subdirs under userfiles)
8807:
8808: =item *
8809:
8810: removeuserfile(): removes a file that exists in userfiles
8811:
8812: Args:
8813: docuname: username or courseid of destination for the file
8814: docudom: domain of user/course of destination for the file
8815: fname: filname to delete (including any subdirs under userfiles)
8816:
8817: =item *
8818:
8819: removeuploadedurl(): convience function for removeuserfile()
8820:
8821: Args:
8822: url: a full /uploaded/... url to delete
8823:
8824: =item *
8825:
8826: get_portfile_permissions():
8827: Args:
8828: domain: domain of user or course contain the portfolio files
8829: user: name of user or num of course contain the portfolio files
8830: Returns:
8831: hashref of a dump of the proper file_permissions.db
8832:
8833:
8834: =item *
8835:
8836: get_access_controls():
8837:
8838: Args:
8839: current_permissions: the hash ref returned from get_portfile_permissions()
8840: group: (optional) the group you want the files associated with
8841: file: (optional) the file you want access info on
8842:
8843: Returns:
8844: a hash (keys are file names) of hashes containing
8845: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8846: values are XML containing access control settings (see below)
8847:
8848: Internal notes:
8849:
8850: access controls are stored in file_permissions.db as key=value pairs.
8851: key -> path to file/file_name\0uniqueID:scope_end_start
8852: where scope -> public,guest,course,group,domains or users.
8853: end -> UNIX time for end of access (0 -> no end date)
8854: start -> UNIX time for start of access
8855:
8856: value -> XML description of access control
8857: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8858: <start></start>
8859: <end></end>
8860:
8861: <password></password> for scope type = guest
8862:
8863: <domain></domain> for scope type = course or group
8864: <number></number>
8865: <roles id="">
8866: <role></role>
8867: <access></access>
8868: <section></section>
8869: <group></group>
8870: </roles>
8871:
8872: <dom></dom> for scope type = domains
8873:
8874: <users> for scope type = users
8875: <user>
8876: <uname></uname>
8877: <udom></udom>
8878: </user>
8879: </users>
8880: </scope>
8881:
8882: Access data is also aggregated for each file in an additional key=value pair:
8883: key -> path to file/file_name\0accesscontrol
8884: value -> reference to hash
8885: hash contains key = value pairs
8886: where key = uniqueID:scope_end_start
8887: value = UNIX time record was last updated
8888:
8889: Used to improve speed of look-ups of access controls for each file.
8890:
8891: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8892:
8893: modify_access_controls():
8894:
8895: Modifies access controls for a portfolio file
8896: Args
8897: 1. file name
8898: 2. reference to hash of required changes,
8899: 3. domain
8900: 4. username
8901: where domain,username are the domain of the portfolio owner
8902: (either a user or a course)
8903:
8904: Returns:
8905: 1. result of additions or updates ('ok' or 'error', with error message).
8906: 2. result of deletions ('ok' or 'error', with error message).
8907: 3. reference to hash of any new or updated access controls.
8908: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8909: key = integer (inbound ID)
8910: value = uniqueID
8911:
8912: =back
8913:
8914: =head2 HTTP Helper Routines
8915:
8916: =over 4
8917:
8918: =item *
8919:
8920: escape() : unpack non-word characters into CGI-compatible hex codes
8921:
8922: =item *
8923:
8924: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8925:
8926: =back
8927:
8928: =head1 PRIVATE SUBROUTINES
8929:
8930: =head2 Underlying communication routines (Shouldn't call)
8931:
8932: =over 4
8933:
8934: =item *
8935:
8936: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8937:
8938: =item *
8939:
8940: reply() : uses subreply to send a message to remote machine, logs all failures
8941:
8942: =item *
8943:
8944: critical() : passes a critical message to another server; if cannot
8945: get through then place message in connection buffer directory and
8946: returns con_delayed, if incapable of saving message, returns
8947: con_failed
8948:
8949: =item *
8950:
8951: reconlonc() : tries to reconnect lonc client processes.
8952:
8953: =back
8954:
8955: =head2 Resource Access Logging
8956:
8957: =over 4
8958:
8959: =item *
8960:
8961: flushcourselogs() : flush (save) buffer logs and access logs
8962:
8963: =item *
8964:
8965: courselog($what) : save message for course in hash
8966:
8967: =item *
8968:
8969: courseacclog($what) : save message for course using &courselog(). Perform
8970: special processing for specific resource types (problems, exams, quizzes, etc).
8971:
8972: =item *
8973:
8974: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8975: as a PerlChildExitHandler
8976:
8977: =back
8978:
8979: =head2 Other
8980:
8981: =over 4
8982:
8983: =item *
8984:
8985: symblist($mapname,%newhash) : update symbolic storage links
8986:
8987: =back
8988:
8989: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>