File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.297:
download - view:
text,
annotated -
select for diffs
Mon Oct 14 15:33:26 2002 UTC (21 years, 9 months ago) by
matthew
Branches:
MAIN
CVS tags:
HEAD
Added function &modify_student_enrollment which handles strictly the
enrollment aspect of adding a student. Fixed bone-headed error of
calling 'dump' instead of 'get' and being puzzled by the results.
Fixed another bone-headed error in using 'genename' instead of 'generation'.
Updated POD to (somewhat) reflect the new function.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.297 2002/10/14 15:33:26 matthew 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: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
30: # 11/8,11/16,11/18,11/22,11/23,12/22,
31: # 01/06,01/13,02/24,02/28,02/29,
32: # 03/01,03/02,03/06,03/07,03/13,
33: # 04/05,05/29,05/31,06/01,
34: # 06/05,06/26 Gerd Kortemeyer
35: # 06/26 Ben Tyszka
36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
37: # 08/14 Ben Tyszka
38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
39: # 10/04 Gerd Kortemeyer
40: # 10/04 Guy Albertelli
41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29,
42: # 10/30,10/31,
43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
45: # 05/01/01 Guy Albertelli
46: # 05/01,06/01,09/01 Gerd Kortemeyer
47: # 09/01 Guy Albertelli
48: # 09/01,10/01,11/01 Gerd Kortemeyer
49: # YEAR=2001
50: # 02/27/01 Scott Harrison
51: # 3/2 Gerd Kortemeyer
52: # 3/15,3/19 Scott Harrison
53: # 3/19,3/20 Gerd Kortemeyer
54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
55: # 5/26,5/28 Gerd Kortemeyer
56: # 5/30 H. K. Ng
57: # 6/1 Gerd Kortemeyer
58: # July Guy Albertelli
59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
60: # 10/2 Gerd Kortemeyer
61: # 10/5,10/10,11/13,11/15 Scott Harrison
62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
63: # 12/5 Matthew Hall
64: # 12/5 Guy Albertelli
65: # 12/6,12/7,12/12 Gerd Kortemeyer
66: # 12/18 Scott Harrison
67: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
68: # YEAR=2002
69: # 1/4,2/4,2/7 Gerd Kortemeyer
70: #
71: ###
72:
73: package Apache::lonnet;
74:
75: use strict;
76: use Apache::File;
77: use LWP::UserAgent();
78: use HTTP::Headers;
79: use vars
80: qw(%perlvar %hostname %homecache %badServerCache %hostip %spareid %hostdom
81: %libserv %pr %prp %metacache %packagetab
82: %courselogs %accesshash $processmarker $dumpcount
83: %coursedombuf %coursehombuf %courseresdatacache %domaindescription);
84: use IO::Socket;
85: use GDBM_File;
86: use Apache::Constants qw(:common :http);
87: use HTML::LCParser;
88: use Fcntl qw(:flock);
89: use Apache::loncoursedata;
90:
91: my $readit;
92:
93: # --------------------------------------------------------------------- Logging
94:
95: sub logtouch {
96: my $execdir=$perlvar{'lonDaemons'};
97: unless (-e "$execdir/logs/lonnet.log") {
98: my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
99: close $fh;
100: }
101: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
102: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
103: }
104:
105: sub logthis {
106: my $message=shift;
107: my $execdir=$perlvar{'lonDaemons'};
108: my $now=time;
109: my $local=localtime($now);
110: my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
111: print $fh "$local ($$): $message\n";
112: return 1;
113: }
114:
115: sub logperm {
116: my $message=shift;
117: my $execdir=$perlvar{'lonDaemons'};
118: my $now=time;
119: my $local=localtime($now);
120: my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
121: print $fh "$now:$message:$local\n";
122: return 1;
123: }
124:
125: # -------------------------------------------------- Non-critical communication
126: sub subreply {
127: my ($cmd,$server)=@_;
128: my $peerfile="$perlvar{'lonSockDir'}/$server";
129: my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
130: Type => SOCK_STREAM,
131: Timeout => 10)
132: or return "con_lost";
133: print $client "$cmd\n";
134: my $answer=<$client>;
135: if (!$answer) { $answer="con_lost"; }
136: chomp($answer);
137: return $answer;
138: }
139:
140: sub reply {
141: my ($cmd,$server)=@_;
142: unless (defined($hostname{$server})) { return 'no_such_host'; }
143: my $answer=subreply($cmd,$server);
144: if ($answer eq 'con_lost') {
145: #sleep 5;
146: #$answer=subreply($cmd,$server);
147: #if ($answer eq 'con_lost') {
148: # &logthis("Second attempt con_lost on $server");
149: # my $peerfile="$perlvar{'lonSockDir'}/$server";
150: # my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
151: # Type => SOCK_STREAM,
152: # Timeout => 10)
153: # or return "con_lost";
154: # &logthis("Killing socket");
155: # print $client "close_connection_exit\n";
156: #sleep 5;
157: # $answer=subreply($cmd,$server);
158: #}
159: }
160: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
161: &logthis("<font color=blue>WARNING:".
162: " $cmd to $server returned $answer</font>");
163: }
164: return $answer;
165: }
166:
167: # ----------------------------------------------------------- Send USR1 to lonc
168:
169: sub reconlonc {
170: my $peerfile=shift;
171: &logthis("Trying to reconnect for $peerfile");
172: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
173: if (my $fh=Apache::File->new("$loncfile")) {
174: my $loncpid=<$fh>;
175: chomp($loncpid);
176: if (kill 0 => $loncpid) {
177: &logthis("lonc at pid $loncpid responding, sending USR1");
178: kill USR1 => $loncpid;
179: sleep 1;
180: if (-e "$peerfile") { return; }
181: &logthis("$peerfile still not there, give it another try");
182: sleep 5;
183: if (-e "$peerfile") { return; }
184: &logthis(
185: "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
186: } else {
187: &logthis(
188: "<font color=blue>WARNING:".
189: " lonc at pid $loncpid not responding, giving up</font>");
190: }
191: } else {
192: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
193: }
194: }
195:
196: # ------------------------------------------------------ Critical communication
197:
198: sub critical {
199: my ($cmd,$server)=@_;
200: unless ($hostname{$server}) {
201: &logthis("<font color=blue>WARNING:".
202: " Critical message to unknown server ($server)</font>");
203: return 'no_such_host';
204: }
205: my $answer=reply($cmd,$server);
206: if ($answer eq 'con_lost') {
207: my $pingreply=reply('ping',$server);
208: &reconlonc("$perlvar{'lonSockDir'}/$server");
209: my $pongreply=reply('pong',$server);
210: &logthis("Ping/Pong for $server: $pingreply/$pongreply");
211: $answer=reply($cmd,$server);
212: if ($answer eq 'con_lost') {
213: my $now=time;
214: my $middlename=$cmd;
215: $middlename=substr($middlename,0,16);
216: $middlename=~s/\W//g;
217: my $dfilename=
218: "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
219: {
220: my $dfh;
221: if ($dfh=Apache::File->new(">$dfilename")) {
222: print $dfh "$cmd\n";
223: }
224: }
225: sleep 2;
226: my $wcmd='';
227: {
228: my $dfh;
229: if ($dfh=Apache::File->new("$dfilename")) {
230: $wcmd=<$dfh>;
231: }
232: }
233: chomp($wcmd);
234: if ($wcmd eq $cmd) {
235: &logthis("<font color=blue>WARNING: ".
236: "Connection buffer $dfilename: $cmd</font>");
237: &logperm("D:$server:$cmd");
238: return 'con_delayed';
239: } else {
240: &logthis("<font color=red>CRITICAL:"
241: ." Critical connection failed: $server $cmd</font>");
242: &logperm("F:$server:$cmd");
243: return 'con_failed';
244: }
245: }
246: }
247: return $answer;
248: }
249:
250: # ---------------------------------------------------------- Append Environment
251:
252: sub appenv {
253: my %newenv=@_;
254: foreach (keys %newenv) {
255: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
256: &logthis("<font color=blue>WARNING: ".
257: "Attempt to modify environment ".$_." to ".$newenv{$_}
258: .'</font>');
259: delete($newenv{$_});
260: } else {
261: $ENV{$_}=$newenv{$_};
262: }
263: }
264:
265: my $lockfh;
266: unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
267: return 'error: '.$!;
268: }
269: unless (flock($lockfh,LOCK_EX)) {
270: &logthis("<font color=blue>WARNING: ".
271: 'Could not obtain exclusive lock in appenv: '.$!);
272: $lockfh->close();
273: return 'error: '.$!;
274: }
275:
276: my @oldenv;
277: {
278: my $fh;
279: unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
280: return 'error: '.$!;
281: }
282: @oldenv=<$fh>;
283: $fh->close();
284: }
285: for (my $i=0; $i<=$#oldenv; $i++) {
286: chomp($oldenv[$i]);
287: if ($oldenv[$i] ne '') {
288: my ($name,$value)=split(/=/,$oldenv[$i]);
289: unless (defined($newenv{$name})) {
290: $newenv{$name}=$value;
291: }
292: }
293: }
294: {
295: my $fh;
296: unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
297: return 'error';
298: }
299: my $newname;
300: foreach $newname (keys %newenv) {
301: print $fh "$newname=$newenv{$newname}\n";
302: }
303: $fh->close();
304: }
305:
306: $lockfh->close();
307: return 'ok';
308: }
309: # ----------------------------------------------------- Delete from Environment
310:
311: sub delenv {
312: my $delthis=shift;
313: my %newenv=();
314: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
315: &logthis("<font color=blue>WARNING: ".
316: "Attempt to delete from environment ".$delthis);
317: return 'error';
318: }
319: my @oldenv;
320: {
321: my $fh;
322: unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
323: return 'error';
324: }
325: unless (flock($fh,LOCK_SH)) {
326: &logthis("<font color=blue>WARNING: ".
327: 'Could not obtain shared lock in delenv: '.$!);
328: $fh->close();
329: return 'error: '.$!;
330: }
331: @oldenv=<$fh>;
332: $fh->close();
333: }
334: {
335: my $fh;
336: unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
337: return 'error';
338: }
339: unless (flock($fh,LOCK_EX)) {
340: &logthis("<font color=blue>WARNING: ".
341: 'Could not obtain exclusive lock in delenv: '.$!);
342: $fh->close();
343: return 'error: '.$!;
344: }
345: foreach (@oldenv) {
346: unless ($_=~/^$delthis/) { print $fh $_; }
347: }
348: $fh->close();
349: }
350: return 'ok';
351: }
352:
353: # ------------------------------------------ Fight off request when overloaded
354:
355: sub overloaderror {
356: my ($r,$checkserver)=@_;
357: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
358: my $loadavg;
359: if ($checkserver eq $perlvar{'lonHostID'}) {
360: my $loadfile=Apache::File->new('/proc/loadavg');
361: $loadavg=<$loadfile>;
362: $loadavg =~ s/\s.*//g;
363: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
364: } else {
365: $loadavg=&reply('load',$checkserver);
366: }
367: my $overload=$loadavg-100;
368: if ($overload>0) {
369: $r->err_headers_out->{'Retry-After'}=$overload;
370: $r->log_error('Overload of '.$overload.' on '.$checkserver);
371: return 413;
372: }
373: return '';
374: }
375:
376: # ------------------------------ Find server with least workload from spare.tab
377:
378: sub spareserver {
379: my $loadpercent = shift;
380: my $tryserver;
381: my $spareserver='';
382: my $lowestserver=$loadpercent;
383: foreach $tryserver (keys %spareid) {
384: my $answer=reply('load',$tryserver);
385: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
386: $spareserver="http://$hostname{$tryserver}";
387: $lowestserver=$answer;
388: }
389: }
390: return $spareserver;
391: }
392:
393: # --------------------------------------------- Try to change a user's password
394:
395: sub changepass {
396: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
397: $currentpass = &escape($currentpass);
398: $newpass = &escape($newpass);
399: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
400: $server);
401: if (! $answer) {
402: &logthis("No reply on password change request to $server ".
403: "by $uname in domain $udom.");
404: } elsif ($answer =~ "^ok") {
405: &logthis("$uname in $udom successfully changed their password ".
406: "on $server.");
407: } elsif ($answer =~ "^pwchange_failure") {
408: &logthis("$uname in $udom was unable to change their password ".
409: "on $server. The action was blocked by either lcpasswd ".
410: "or pwchange");
411: } elsif ($answer =~ "^non_authorized") {
412: &logthis("$uname in $udom did not get their password correct when ".
413: "attempting to change it on $server.");
414: } elsif ($answer =~ "^auth_mode_error") {
415: &logthis("$uname in $udom attempted to change their password despite ".
416: "not being locally or internally authenticated on $server.");
417: } elsif ($answer =~ "^unknown_user") {
418: &logthis("$uname in $udom attempted to change their password ".
419: "on $server but were unable to because $server is not ".
420: "their home server.");
421: } elsif ($answer =~ "^refused") {
422: &logthis("$server refused to change $uname in $udom password because ".
423: "it was sent an unencrypted request to change the password.");
424: }
425: return $answer;
426: }
427:
428: # ----------------------- Try to determine user's current authentication scheme
429:
430: sub queryauthenticate {
431: my ($uname,$udom)=@_;
432: if (($perlvar{'lonRole'} eq 'library') &&
433: ($udom eq $perlvar{'lonDefDomain'})) {
434: my $answer=reply("encrypt:currentauth:$udom:$uname",
435: $perlvar{'lonHostID'});
436: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
437: if (length($answer)) {
438: return $answer;
439: }
440: else {
441: &logthis("User $uname at $udom lacks an authentication mechanism");
442: return 'no_host';
443: }
444: }
445: }
446:
447: my $tryserver;
448: foreach $tryserver (keys %libserv) {
449: if ($hostdom{$tryserver} eq $udom) {
450: my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
451: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
452: if (length($answer)) {
453: return $answer;
454: }
455: else {
456: &logthis("User $uname at $udom lacks an authentication mechanism");
457: return 'no_host';
458: }
459: }
460: }
461: }
462: &logthis("User $uname at $udom lacks an authentication mechanism");
463: return 'no_host';
464: }
465:
466: # --------- Try to authenticate user from domain's lib servers (first this one)
467:
468: sub authenticate {
469: my ($uname,$upass,$udom)=@_;
470: $upass=escape($upass);
471: $uname=~s/\W//g;
472: if (($perlvar{'lonRole'} eq 'library') &&
473: ($udom eq $perlvar{'lonDefDomain'})) {
474: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
475: if ($answer =~ /authorized/) {
476: if ($answer eq 'authorized') {
477: &logthis("User $uname at $udom authorized by local server");
478: return $perlvar{'lonHostID'};
479: }
480: if ($answer eq 'non_authorized') {
481: &logthis("User $uname at $udom rejected by local server");
482: return 'no_host';
483: }
484: }
485: }
486:
487: my $tryserver;
488: foreach $tryserver (keys %libserv) {
489: if ($hostdom{$tryserver} eq $udom) {
490: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
491: if ($answer =~ /authorized/) {
492: if ($answer eq 'authorized') {
493: &logthis("User $uname at $udom authorized by $tryserver");
494: return $tryserver;
495: }
496: if ($answer eq 'non_authorized') {
497: &logthis("User $uname at $udom rejected by $tryserver");
498: return 'no_host';
499: }
500: }
501: }
502: }
503: &logthis("User $uname at $udom could not be authenticated");
504: return 'no_host';
505: }
506:
507: # ---------------------- Find the homebase for a user from domain's lib servers
508:
509: sub homeserver {
510: my ($uname,$udom,$ignoreBadCache)=@_;
511: my $index="$uname:$udom";
512: if ($homecache{$index}) {
513: return "$homecache{$index}";
514: }
515: my $tryserver;
516: foreach $tryserver (keys %libserv) {
517: next if ($ignoreBadCache ne 'true' &&
518: exists($badServerCache{$tryserver}));
519: if ($hostdom{$tryserver} eq $udom) {
520: my $answer=reply("home:$udom:$uname",$tryserver);
521: if ($answer eq 'found') {
522: $homecache{$index}=$tryserver;
523: return $tryserver;
524: } elsif ($answer eq 'no_host') {
525: $badServerCache{$tryserver}=1;
526: }
527: }
528: }
529: return 'no_host';
530: }
531:
532: # ------------------------------------- Find the usernames behind a list of IDs
533:
534: sub idget {
535: my ($udom,@ids)=@_;
536: my %returnhash=();
537:
538: my $tryserver;
539: foreach $tryserver (keys %libserv) {
540: if ($hostdom{$tryserver} eq $udom) {
541: my $idlist=join('&',@ids);
542: $idlist=~tr/A-Z/a-z/;
543: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
544: my @answer=();
545: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
546: @answer=split(/\&/,$reply);
547: } ;
548: my $i;
549: for ($i=0;$i<=$#ids;$i++) {
550: if ($answer[$i]) {
551: $returnhash{$ids[$i]}=$answer[$i];
552: }
553: }
554: }
555: }
556: return %returnhash;
557: }
558:
559: # ------------------------------------- Find the IDs behind a list of usernames
560:
561: sub idrget {
562: my ($udom,@unames)=@_;
563: my %returnhash=();
564: foreach (@unames) {
565: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
566: }
567: return %returnhash;
568: }
569:
570: # ------------------------------- Store away a list of names and associated IDs
571:
572: sub idput {
573: my ($udom,%ids)=@_;
574: my %servers=();
575: foreach (keys %ids) {
576: my $uhom=&homeserver($_,$udom);
577: if ($uhom ne 'no_host') {
578: my $id=&escape($ids{$_});
579: $id=~tr/A-Z/a-z/;
580: my $unam=&escape($_);
581: if ($servers{$uhom}) {
582: $servers{$uhom}.='&'.$id.'='.$unam;
583: } else {
584: $servers{$uhom}=$id.'='.$unam;
585: }
586: &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
587: }
588: }
589: foreach (keys %servers) {
590: &critical('idput:'.$udom.':'.$servers{$_},$_);
591: }
592: }
593:
594: # ------------------------------------- Find the section of student in a course
595:
596: sub usection {
597: my ($udom,$unam,$courseid)=@_;
598: $courseid=~s/\_/\//g;
599: $courseid=~s/^(\w)/\/$1/;
600: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
601: &homeserver($unam,$udom)))) {
602: my ($key,$value)=split(/\=/,$_);
603: $key=&unescape($key);
604: if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
605: my $section=$1;
606: if ($key eq $courseid.'_st') { $section=''; }
607: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
608: my $now=time;
609: my $notactive=0;
610: if ($start) {
611: if ($now<$start) { $notactive=1; }
612: }
613: if ($end) {
614: if ($now>$end) { $notactive=1; }
615: }
616: unless ($notactive) { return $section; }
617: }
618: }
619: return '-1';
620: }
621:
622: # ------------------------------------- Read an entry from a user's environment
623:
624: sub userenvironment {
625: my ($udom,$unam,@what)=@_;
626: my %returnhash=();
627: my @answer=split(/\&/,
628: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
629: &homeserver($unam,$udom)));
630: my $i;
631: for ($i=0;$i<=$#what;$i++) {
632: $returnhash{$what[$i]}=&unescape($answer[$i]);
633: }
634: return %returnhash;
635: }
636:
637: # -------------------------------------------------------------------- New chat
638:
639: sub chatsend {
640: my ($newentry,$anon)=@_;
641: my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
642: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
643: my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
644: &reply('chatsend:'.$cdom.':'.$cnum.':'.
645: &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
646: &escape($newentry)),$chome);
647: }
648:
649: # ------------------------------------------ Find current version of a resource
650:
651: sub getversion {
652: my $fname=&clutter(shift);
653: unless ($fname=~/^\/res\//) { return -1; }
654: return ¤tversion(&filelocation('',$fname));
655: }
656:
657: sub currentversion {
658: my $fname=shift;
659: my $author=$fname;
660: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
661: my ($udom,$uname)=split(/\//,$author);
662: my $home=homeserver($uname,$udom);
663: if ($home eq 'no_host') {
664: return -1;
665: }
666: my $answer=reply("currentversion:$fname",$home);
667: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
668: return -1;
669: }
670: return $answer;
671: }
672:
673: # ----------------------------- Subscribe to a resource, return URL if possible
674:
675: sub subscribe {
676: my $fname=shift;
677: my $author=$fname;
678: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
679: my ($udom,$uname)=split(/\//,$author);
680: my $home=homeserver($uname,$udom);
681: if ($home eq 'no_host') {
682: return 'not_found';
683: }
684: my $answer=reply("sub:$fname",$home);
685: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
686: $answer.=' by '.$home;
687: }
688: return $answer;
689: }
690:
691: # -------------------------------------------------------------- Replicate file
692:
693: sub repcopy {
694: my $filename=shift;
695: $filename=~s/\/+/\//g;
696: if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
697: my $transname="$filename.in.transfer";
698: if ((-e $filename) || (-e $transname)) { return OK; }
699: my $remoteurl=subscribe($filename);
700: if ($remoteurl =~ /^con_lost by/) {
701: &logthis("Subscribe returned $remoteurl: $filename");
702: return HTTP_SERVICE_UNAVAILABLE;
703: } elsif ($remoteurl eq 'not_found') {
704: &logthis("Subscribe returned not_found: $filename");
705: return HTTP_NOT_FOUND;
706: } elsif ($remoteurl =~ /^rejected by/) {
707: &logthis("Subscribe returned $remoteurl: $filename");
708: return FORBIDDEN;
709: } elsif ($remoteurl eq 'directory') {
710: return OK;
711: } else {
712: my $author=$filename;
713: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
714: my ($udom,$uname)=split(/\//,$author);
715: my $home=homeserver($uname,$udom);
716: unless ($home eq $perlvar{'lonHostID'}) {
717: my @parts=split(/\//,$filename);
718: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
719: if ($path ne "$perlvar{'lonDocRoot'}/res") {
720: &logthis("Malconfiguration for replication: $filename");
721: return HTTP_BAD_REQUEST;
722: }
723: my $count;
724: for ($count=5;$count<$#parts;$count++) {
725: $path.="/$parts[$count]";
726: if ((-e $path)!=1) {
727: mkdir($path,0777);
728: }
729: }
730: my $ua=new LWP::UserAgent;
731: my $request=new HTTP::Request('GET',"$remoteurl");
732: my $response=$ua->request($request,$transname);
733: if ($response->is_error()) {
734: unlink($transname);
735: my $message=$response->status_line;
736: &logthis("<font color=blue>WARNING:"
737: ." LWP get: $message: $filename</font>");
738: return HTTP_SERVICE_UNAVAILABLE;
739: } else {
740: if ($remoteurl!~/\.meta$/) {
741: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
742: my $mresponse=$ua->request($mrequest,$filename.'.meta');
743: if ($mresponse->is_error()) {
744: unlink($filename.'.meta');
745: &logthis(
746: "<font color=yellow>INFO: No metadata: $filename</font>");
747: }
748: }
749: rename($transname,$filename);
750: return OK;
751: }
752: }
753: }
754: }
755:
756: # --------------------------------------------------------- Server Side Include
757:
758: sub ssi {
759:
760: my ($fn,%form)=@_;
761:
762: my $ua=new LWP::UserAgent;
763:
764: my $request;
765:
766: if (%form) {
767: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
768: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
769: } else {
770: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
771: }
772:
773: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
774: my $response=$ua->request($request);
775:
776: return $response->content;
777: }
778:
779: # ------- Add a token to a remote URI's query string to vouch for access rights
780:
781: sub tokenwrapper {
782: my $uri=shift;
783: $uri=~s/^http\:\/\/([^\/]+)//;
784: $uri=~s/^\///;
785: $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
786: my $token=$1;
787: if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
788: &appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
789: return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
790: (($uri=~/\?/)?'&':'?').'token='.$token;
791: } else {
792: return '/adm/notfound.html';
793: }
794: }
795:
796: # --------------- Take an uploaded file and put it into the userfiles directory
797: # input: name of form element, coursedoc=1 means this is for the course
798: # output: url of file in userspace
799:
800: sub userfileupload {
801: my ($formname,$coursedoc)=@_;
802: my $fname=$ENV{'form.'.$formname.'.filename'};
803: $fname=~s/\\/\//g;
804: $fname=~s/^.*\/([^\/]+)$/$1/;
805: unless ($fname) { return 'error: no uploaded file'; }
806: chop($ENV{'form.'.$formname});
807: # Create the directory if not present
808: my $docuname='';
809: my $docudom='';
810: my $docuhome='';
811: if ($coursedoc) {
812: $docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
813: $docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
814: $docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
815: } else {
816: $docuname=$ENV{'user.name'};
817: $docudom=$ENV{'user.domain'};
818: $docuhome=$ENV{'user.home'};
819: }
820: return
821: &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
822: }
823:
824: sub finishuserfileupload {
825: my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
826: my $path=$docudom.'/'.$docuname.'/';
827: my $filepath=$perlvar{'lonDocRoot'};
828: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
829: my $count;
830: for ($count=4;$count<=$#parts;$count++) {
831: $filepath.="/$parts[$count]";
832: if ((-e $filepath)!=1) {
833: mkdir($filepath,0777);
834: }
835: }
836: # Save the file
837: {
838: my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
839: print $fh $ENV{'form.'.$formname};
840: }
841: # Notify homeserver to grep it
842: #
843:
844: my $fetchresult=
845: &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
846: if ($fetchresult eq 'ok') {
847: #
848: # Return the URL to it
849: return '/uploaded/'.$path.$fname;
850: } else {
851: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
852: ' to host '.$docuhome.': '.$fetchresult);
853: return '/adm/notfound.html';
854: }
855: }
856:
857: # ------------------------------------------------------------------------- Log
858:
859: sub log {
860: my ($dom,$nam,$hom,$what)=@_;
861: return critical("log:$dom:$nam:$what",$hom);
862: }
863:
864: # ------------------------------------------------------------------ Course Log
865:
866: sub flushcourselogs {
867: &logthis('Flushing course log buffers');
868: foreach (keys %courselogs) {
869: my $crsid=$_;
870: if (&reply('log:'.$coursedombuf{$crsid}.':'.
871: &escape($courselogs{$crsid}),
872: $coursehombuf{$crsid}) eq 'ok') {
873: delete $courselogs{$crsid};
874: } else {
875: &logthis('Failed to flush log buffer for '.$crsid);
876: if (length($courselogs{$crsid})>40000) {
877: &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
878: " exceeded maximum size, deleting.</font>");
879: delete $courselogs{$crsid};
880: }
881: }
882: }
883: &logthis('Flushing access logs');
884: foreach (keys %accesshash) {
885: my $entry=$_;
886: $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
887: my %temphash=($entry => $accesshash{$entry});
888: if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
889: delete $accesshash{$entry};
890: }
891: }
892: $dumpcount++;
893: }
894:
895: sub courselog {
896: my $what=shift;
897: $what=time.':'.$what;
898: unless ($ENV{'request.course.id'}) { return ''; }
899: $coursedombuf{$ENV{'request.course.id'}}=
900: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
901: $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
902: $coursehombuf{$ENV{'request.course.id'}}=
903: $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
904: if (defined $courselogs{$ENV{'request.course.id'}}) {
905: $courselogs{$ENV{'request.course.id'}}.='&'.$what;
906: } else {
907: $courselogs{$ENV{'request.course.id'}}.=$what;
908: }
909: if (length($courselogs{$ENV{'request.course.id'}})>4048) {
910: &flushcourselogs();
911: }
912: }
913:
914: sub courseacclog {
915: my $fnsymb=shift;
916: unless ($ENV{'request.course.id'}) { return ''; }
917: my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
918: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
919: $what.=':POST';
920: foreach (keys %ENV) {
921: if ($_=~/^form\.(.*)/) {
922: $what.=':'.$1.'='.$ENV{$_};
923: }
924: }
925: }
926: &courselog($what);
927: }
928:
929: sub countacc {
930: my $url=&declutter(shift);
931: unless ($ENV{'request.course.id'}) { return ''; }
932: $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
933: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
934: if (defined($accesshash{$key})) {
935: $accesshash{$key}++;
936: } else {
937: $accesshash{$key}=1;
938: }
939: }
940:
941: # ----------------------------------------------------------- Check out an item
942:
943: sub checkout {
944: my ($symb,$tuname,$tudom,$tcrsid)=@_;
945: my $now=time;
946: my $lonhost=$perlvar{'lonHostID'};
947: my $infostr=&escape(
948: 'CHECKOUTTOKEN&'.
949: $tuname.'&'.
950: $tudom.'&'.
951: $tcrsid.'&'.
952: $symb.'&'.
953: $now.'&'.$ENV{'REMOTE_ADDR'});
954: my $token=&reply('tmpput:'.$infostr,$lonhost);
955: if ($token=~/^error\:/) {
956: &logthis("<font color=blue>WARNING: ".
957: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
958: "</font>");
959: return '';
960: }
961:
962: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
963: $token=~tr/a-z/A-Z/;
964:
965: my %infohash=('resource.0.outtoken' => $token,
966: 'resource.0.checkouttime' => $now,
967: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
968:
969: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
970: return '';
971: } else {
972: &logthis("<font color=blue>WARNING: ".
973: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
974: "</font>");
975: }
976:
977: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
978: &escape('Checkout '.$infostr.' - '.
979: $token)) ne 'ok') {
980: return '';
981: } else {
982: &logthis("<font color=blue>WARNING: ".
983: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
984: "</font>");
985: }
986: return $token;
987: }
988:
989: # ------------------------------------------------------------ Check in an item
990:
991: sub checkin {
992: my $token=shift;
993: my $now=time;
994: my ($ta,$tb,$lonhost)=split(/\*/,$token);
995: $lonhost=~tr/A-Z/a-z/;
996: my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
997: $dtoken=~s/\W/\_/g;
998: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
999: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
1000:
1001: unless (($tuname) && ($tudom)) {
1002: &logthis('Check in '.$token.' ('.$dtoken.') failed');
1003: return '';
1004: }
1005:
1006: unless (&allowed('mgr',$tcrsid)) {
1007: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1008: $ENV{'user.name'}.' - '.$ENV{'user.domain'});
1009: return '';
1010: }
1011:
1012: my %infohash=('resource.0.intoken' => $token,
1013: 'resource.0.checkintime' => $now,
1014: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1015:
1016: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1017: return '';
1018: }
1019:
1020: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1021: &escape('Checkin - '.$token)) ne 'ok') {
1022: return '';
1023: }
1024:
1025: return ($symb,$tuname,$tudom,$tcrsid);
1026: }
1027:
1028: # --------------------------------------------- Set Expire Date for Spreadsheet
1029:
1030: sub expirespread {
1031: my ($uname,$udom,$stype,$usymb)=@_;
1032: my $cid=$ENV{'request.course.id'};
1033: if ($cid) {
1034: my $now=time;
1035: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1036: return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1037: $ENV{'course.'.$cid.'.num'}.
1038: ':nohist_expirationdates:'.
1039: &escape($key).'='.$now,
1040: $ENV{'course.'.$cid.'.home'})
1041: }
1042: return 'ok';
1043: }
1044:
1045: # ----------------------------------------------------- Devalidate Spreadsheets
1046:
1047: sub devalidate {
1048: my $symb=shift;
1049: my $cid=$ENV{'request.course.id'};
1050: if ($cid) {
1051: my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
1052: my $status=
1053: &del('nohist_calculatedsheet',
1054: [$key.'studentcalc'],
1055: $ENV{'course.'.$cid.'.domain'},
1056: $ENV{'course.'.$cid.'.num'})
1057: .' '.
1058: &del('nohist_calculatedsheets_'.$cid,
1059: [$key.'assesscalc:'.$symb]);
1060: unless ($status eq 'ok ok') {
1061: &logthis('Could not devalidate spreadsheet '.
1062: $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
1063: $symb.': '.$status);
1064: }
1065: }
1066: }
1067:
1068: sub get_scalar {
1069: my ($string,$end) = @_;
1070: my $value;
1071: if ($$string =~ s/^([^&]*?)($end)/$2/) {
1072: $value = $1;
1073: } elsif ($$string =~ s/^([^&]*?)&//) {
1074: $value = $1;
1075: }
1076: return &unescape($value);
1077: }
1078:
1079: sub array2str {
1080: my (@array) = @_;
1081: my $result=&arrayref2str(\@array);
1082: $result=~s/^__ARRAY_REF__//;
1083: $result=~s/__END_ARRAY_REF__$//;
1084: return $result;
1085: }
1086:
1087: sub arrayref2str {
1088: my ($arrayref) = @_;
1089: my $result='__ARRAY_REF__';
1090: foreach my $elem (@$arrayref) {
1091: if(ref($elem) eq 'ARRAY') {
1092: $result.=&arrayref2str($elem).'&';
1093: } elsif(ref($elem) eq 'HASH') {
1094: $result.=&hashref2str($elem).'&';
1095: } elsif(ref($elem)) {
1096: #print("Got a ref of ".(ref($elem))." skipping.");
1097: } else {
1098: $result.=&escape($elem).'&';
1099: }
1100: }
1101: $result=~s/\&$//;
1102: $result .= '__END_ARRAY_REF__';
1103: return $result;
1104: }
1105:
1106: sub hash2str {
1107: my (%hash) = @_;
1108: my $result=&hashref2str(\%hash);
1109: $result=~s/^__HASH_REF__//;
1110: $result=~s/__END_HASH_REF__$//;
1111: return $result;
1112: }
1113:
1114: sub hashref2str {
1115: my ($hashref)=@_;
1116: my $result='__HASH_REF__';
1117: foreach (keys(%$hashref)) {
1118: if (ref($_) eq 'ARRAY') {
1119: $result.=&arrayref2str($_).'=';
1120: } elsif (ref($_) eq 'HASH') {
1121: $result.=&hashref2str($_).'=';
1122: } elsif (ref($_)) {
1123: $result.='=';
1124: #print("Got a ref of ".(ref($_))." skipping.");
1125: } else {
1126: if ($_) {$result.=&escape($_).'=';} else { last; }
1127: }
1128:
1129: if(ref($hashref->{$_}) eq 'ARRAY') {
1130: $result.=&arrayref2str($hashref->{$_}).'&';
1131: } elsif(ref($hashref->{$_}) eq 'HASH') {
1132: $result.=&hashref2str($hashref->{$_}).'&';
1133: } elsif(ref($hashref->{$_})) {
1134: $result.='&';
1135: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1136: } else {
1137: $result.=&escape($hashref->{$_}).'&';
1138: }
1139: }
1140: $result=~s/\&$//;
1141: $result .= '__END_HASH_REF__';
1142: return $result;
1143: }
1144:
1145: sub str2hash {
1146: my ($string)=@_;
1147: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
1148: return %$hash;
1149: }
1150:
1151: sub str2hashref {
1152: my ($string) = @_;
1153:
1154: my %hash;
1155:
1156: if($string !~ /^__HASH_REF__/) {
1157: if (! ($string eq '' || !defined($string))) {
1158: $hash{'error'}='Not hash reference';
1159: }
1160: return (\%hash, $string);
1161: }
1162:
1163: $string =~ s/^__HASH_REF__//;
1164:
1165: while($string !~ /^__END_HASH_REF__/) {
1166: #key
1167: my $key='';
1168: if($string =~ /^__HASH_REF__/) {
1169: ($key, $string)=&str2hashref($string);
1170: if(defined($key->{'error'})) {
1171: $hash{'error'}='Bad data';
1172: return (\%hash, $string);
1173: }
1174: } elsif($string =~ /^__ARRAY_REF__/) {
1175: ($key, $string)=&str2arrayref($string);
1176: if($key->[0] eq 'Array reference error') {
1177: $hash{'error'}='Bad data';
1178: return (\%hash, $string);
1179: }
1180: } else {
1181: $string =~ s/^(.*?)=//;
1182: $key=&unescape($1);
1183: }
1184: $string =~ s/^=//;
1185:
1186: #value
1187: my $value='';
1188: if($string =~ /^__HASH_REF__/) {
1189: ($value, $string)=&str2hashref($string);
1190: if(defined($value->{'error'})) {
1191: $hash{'error'}='Bad data';
1192: return (\%hash, $string);
1193: }
1194: } elsif($string =~ /^__ARRAY_REF__/) {
1195: ($value, $string)=&str2arrayref($string);
1196: if($value->[0] eq 'Array reference error') {
1197: $hash{'error'}='Bad data';
1198: return (\%hash, $string);
1199: }
1200: } else {
1201: $value=&get_scalar(\$string,'__END_HASH_REF__');
1202: }
1203: $string =~ s/^&//;
1204:
1205: $hash{$key}=$value;
1206: }
1207:
1208: $string =~ s/^__END_HASH_REF__//;
1209:
1210: return (\%hash, $string);
1211: }
1212:
1213: sub str2array {
1214: my ($string)=@_;
1215: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
1216: return @$array;
1217: }
1218:
1219: sub str2arrayref {
1220: my ($string) = @_;
1221: my @array;
1222:
1223: if($string !~ /^__ARRAY_REF__/) {
1224: if (! ($string eq '' || !defined($string))) {
1225: $array[0]='Array reference error';
1226: }
1227: return (\@array, $string);
1228: }
1229:
1230: $string =~ s/^__ARRAY_REF__//;
1231:
1232: while($string !~ /^__END_ARRAY_REF__/) {
1233: my $value='';
1234: if($string =~ /^__HASH_REF__/) {
1235: ($value, $string)=&str2hashref($string);
1236: if(defined($value->{'error'})) {
1237: $array[0] ='Array reference error';
1238: return (\@array, $string);
1239: }
1240: } elsif($string =~ /^__ARRAY_REF__/) {
1241: ($value, $string)=&str2arrayref($string);
1242: if($value->[0] eq 'Array reference error') {
1243: $array[0] ='Array reference error';
1244: return (\@array, $string);
1245: }
1246: } else {
1247: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
1248: }
1249: $string =~ s/^&//;
1250:
1251: push(@array, $value);
1252: }
1253:
1254: $string =~ s/^__END_ARRAY_REF__//;
1255:
1256: return (\@array, $string);
1257: }
1258:
1259: # -------------------------------------------------------------------Temp Store
1260:
1261: sub tmpreset {
1262: my ($symb,$namespace,$domain,$stuname) = @_;
1263: if (!$symb) {
1264: $symb=&symbread();
1265: if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
1266: }
1267: $symb=escape($symb);
1268:
1269: if (!$namespace) { $namespace=$ENV{'request.state'}; }
1270: $namespace=~s/\//\_/g;
1271: $namespace=~s/\W//g;
1272:
1273: #FIXME needs to do something for /pub resources
1274: if (!$domain) { $domain=$ENV{'user.domain'}; }
1275: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1276: my $path=$perlvar{'lonDaemons'}.'/tmp';
1277: my %hash;
1278: if (tie(%hash,'GDBM_File',
1279: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1280: &GDBM_WRCREAT(),0640)) {
1281: foreach my $key (keys %hash) {
1282: if ($key=~ /:$symb/) {
1283: delete($hash{$key});
1284: }
1285: }
1286: }
1287: }
1288:
1289: sub tmpstore {
1290: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1291:
1292: if (!$symb) {
1293: $symb=&symbread();
1294: if (!$symb) { $symb= $ENV{'request.url'}; }
1295: }
1296: $symb=escape($symb);
1297:
1298: if (!$namespace) {
1299: # I don't think we would ever want to store this for a course.
1300: # it seems this will only be used if we don't have a course.
1301: #$namespace=$ENV{'request.course.id'};
1302: #if (!$namespace) {
1303: $namespace=$ENV{'request.state'};
1304: #}
1305: }
1306: $namespace=~s/\//\_/g;
1307: $namespace=~s/\W//g;
1308: #FIXME needs to do something for /pub resources
1309: if (!$domain) { $domain=$ENV{'user.domain'}; }
1310: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1311: my $now=time;
1312: my %hash;
1313: my $path=$perlvar{'lonDaemons'}.'/tmp';
1314: if (tie(%hash,'GDBM_File',
1315: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1316: &GDBM_WRCREAT(),0640)) {
1317: $hash{"version:$symb"}++;
1318: my $version=$hash{"version:$symb"};
1319: my $allkeys='';
1320: foreach my $key (keys(%$storehash)) {
1321: $allkeys.=$key.':';
1322: $hash{"$version:$symb:$key"}=$$storehash{$key};
1323: }
1324: $hash{"$version:$symb:timestamp"}=$now;
1325: $allkeys.='timestamp';
1326: $hash{"$version:keys:$symb"}=$allkeys;
1327: if (untie(%hash)) {
1328: return 'ok';
1329: } else {
1330: return "error:$!";
1331: }
1332: } else {
1333: return "error:$!";
1334: }
1335: }
1336:
1337: # -----------------------------------------------------------------Temp Restore
1338:
1339: sub tmprestore {
1340: my ($symb,$namespace,$domain,$stuname) = @_;
1341:
1342: if (!$symb) {
1343: $symb=&symbread();
1344: if (!$symb) { $symb= $ENV{'request.url'}; }
1345: }
1346: $symb=escape($symb);
1347:
1348: if (!$namespace) { $namespace=$ENV{'request.state'}; }
1349: #FIXME needs to do something for /pub resources
1350: if (!$domain) { $domain=$ENV{'user.domain'}; }
1351: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1352:
1353: my %returnhash;
1354: $namespace=~s/\//\_/g;
1355: $namespace=~s/\W//g;
1356: my %hash;
1357: my $path=$perlvar{'lonDaemons'}.'/tmp';
1358: if (tie(%hash,'GDBM_File',
1359: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1360: &GDBM_READER(),0640)) {
1361: my $version=$hash{"version:$symb"};
1362: $returnhash{'version'}=$version;
1363: my $scope;
1364: for ($scope=1;$scope<=$version;$scope++) {
1365: my $vkeys=$hash{"$scope:keys:$symb"};
1366: my @keys=split(/:/,$vkeys);
1367: my $key;
1368: $returnhash{"$scope:keys"}=$vkeys;
1369: foreach $key (@keys) {
1370: $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
1371: $returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1372: }
1373: }
1374: if (!(untie(%hash))) {
1375: return "error:$!";
1376: }
1377: } else {
1378: return "error:$!";
1379: }
1380: return %returnhash;
1381: }
1382:
1383: # ----------------------------------------------------------------------- Store
1384:
1385: sub store {
1386: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1387: my $home='';
1388:
1389: if ($stuname) { $home=&homeserver($stuname,$domain); }
1390:
1391: $symb=&symbclean($symb);
1392: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1393:
1394: &devalidate($symb);
1395:
1396: $symb=escape($symb);
1397: if (!$namespace) {
1398: unless ($namespace=$ENV{'request.course.id'}) {
1399: return '';
1400: }
1401: }
1402: if (!$domain) { $domain=$ENV{'user.domain'}; }
1403: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1404: if (!$home) { $home=$ENV{'user.home'}; }
1405: my $namevalue='';
1406: foreach (keys %$storehash) {
1407: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1408: }
1409: $namevalue=~s/\&$//;
1410: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1411: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1412: }
1413:
1414: # -------------------------------------------------------------- Critical Store
1415:
1416: sub cstore {
1417: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1418: my $home='';
1419:
1420: if ($stuname) { $home=&homeserver($stuname,$domain); }
1421:
1422: $symb=&symbclean($symb);
1423: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1424:
1425: &devalidate($symb);
1426:
1427: $symb=escape($symb);
1428: if (!$namespace) {
1429: unless ($namespace=$ENV{'request.course.id'}) {
1430: return '';
1431: }
1432: }
1433: if (!$domain) { $domain=$ENV{'user.domain'}; }
1434: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1435: if (!$home) { $home=$ENV{'user.home'}; }
1436:
1437: my $namevalue='';
1438: foreach (keys %$storehash) {
1439: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1440: }
1441: $namevalue=~s/\&$//;
1442: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1443: return critical
1444: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1445: }
1446:
1447: # --------------------------------------------------------------------- Restore
1448:
1449: sub restore {
1450: my ($symb,$namespace,$domain,$stuname) = @_;
1451: my $home='';
1452:
1453: if ($stuname) { $home=&homeserver($stuname,$domain); }
1454:
1455: if (!$symb) {
1456: unless ($symb=escape(&symbread())) { return ''; }
1457: } else {
1458: $symb=&escape(&symbclean($symb));
1459: }
1460: if (!$namespace) {
1461: unless ($namespace=$ENV{'request.course.id'}) {
1462: return '';
1463: }
1464: }
1465: if (!$domain) { $domain=$ENV{'user.domain'}; }
1466: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1467: if (!$home) { $home=$ENV{'user.home'}; }
1468: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
1469:
1470: my %returnhash=();
1471: foreach (split(/\&/,$answer)) {
1472: my ($name,$value)=split(/\=/,$_);
1473: $returnhash{&unescape($name)}=&unescape($value);
1474: }
1475: my $version;
1476: for ($version=1;$version<=$returnhash{'version'};$version++) {
1477: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1478: $returnhash{$_}=$returnhash{$version.':'.$_};
1479: }
1480: }
1481: return %returnhash;
1482: }
1483:
1484: # ---------------------------------------------------------- Course Description
1485:
1486: sub coursedescription {
1487: my $courseid=shift;
1488: $courseid=~s/^\///;
1489: $courseid=~s/\_/\//g;
1490: my ($cdomain,$cnum)=split(/\//,$courseid);
1491: my $chome=&homeserver($cnum,$cdomain);
1492: if ($chome ne 'no_host') {
1493: my %returnhash=&dump('environment',$cdomain,$cnum);
1494: if (!exists($returnhash{'con_lost'})) {
1495: my $normalid=$cdomain.'_'.$cnum;
1496: my %envhash=();
1497: $returnhash{'home'}= $chome;
1498: $returnhash{'domain'} = $cdomain;
1499: $returnhash{'num'} = $cnum;
1500: while (my ($name,$value) = each %returnhash) {
1501: $envhash{'course.'.$normalid.'.'.$name}=$value;
1502: }
1503: $returnhash{'url'}=&clutter($returnhash{'url'});
1504: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1505: $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1506: $envhash{'course.'.$normalid.'.last_cache'}=time;
1507: $envhash{'course.'.$normalid.'.home'}=$chome;
1508: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
1509: $envhash{'course.'.$normalid.'.num'}=$cnum;
1510: &appenv(%envhash);
1511: return %returnhash;
1512: }
1513: }
1514: return ();
1515: }
1516:
1517: # -------------------------------------------------------- Get user privileges
1518:
1519: sub rolesinit {
1520: my ($domain,$username,$authhost)=@_;
1521: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1522: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1523: my %allroles=();
1524: my %thesepriv=();
1525: my $now=time;
1526: my $userroles="user.login.time=$now\n";
1527: my $thesestr;
1528:
1529: if ($rolesdump ne '') {
1530: foreach (split(/&/,$rolesdump)) {
1531: if ($_!~/^rolesdef\&/) {
1532: my ($area,$role)=split(/=/,$_);
1533: $area=~s/\_\w\w$//;
1534: my ($trole,$tend,$tstart)=split(/_/,$role);
1535: $userroles.='user.role.'.$trole.'.'.$area.'='.
1536: $tstart.'.'.$tend."\n";
1537: if ($tend!=0) {
1538: if ($tend<$now) {
1539: $trole='';
1540: }
1541: }
1542: if ($tstart!=0) {
1543: if ($tstart>$now) {
1544: $trole='';
1545: }
1546: }
1547: if (($area ne '') && ($trole ne '')) {
1548: my $spec=$trole.'.'.$area;
1549: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
1550: if ($trole =~ /^cr\//) {
1551: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1552: my $homsvr=homeserver($rauthor,$rdomain);
1553: if ($hostname{$homsvr} ne '') {
1554: my $roledef=
1555: reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
1556: $homsvr);
1557: if (($roledef ne 'con_lost') && ($roledef ne '')) {
1558: my ($syspriv,$dompriv,$coursepriv)=
1559: split(/\_/,unescape($roledef));
1560: $allroles{'cm./'}.=':'.$syspriv;
1561: $allroles{$spec.'./'}.=':'.$syspriv;
1562: if ($tdomain ne '') {
1563: $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
1564: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
1565: if ($trest ne '') {
1566: $allroles{'cm.'.$area}.=':'.$coursepriv;
1567: $allroles{$spec.'.'.$area}.=':'.$coursepriv;
1568: }
1569: }
1570: }
1571: }
1572: } else {
1573: $allroles{'cm./'}.=':'.$pr{$trole.':s'};
1574: $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
1575: if ($tdomain ne '') {
1576: $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1577: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1578: if ($trest ne '') {
1579: $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
1580: $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
1581: }
1582: }
1583: }
1584: }
1585: }
1586: }
1587: my $adv=0;
1588: my $author=0;
1589: foreach (keys %allroles) {
1590: %thesepriv=();
1591: if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1592: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1593: foreach (split(/:/,$allroles{$_})) {
1594: if ($_ ne '') {
1595: my ($privilege,$restrictions)=split(/&/,$_);
1596: if ($restrictions eq '') {
1597: $thesepriv{$privilege}='F';
1598: } else {
1599: if ($thesepriv{$privilege} ne 'F') {
1600: $thesepriv{$privilege}.=$restrictions;
1601: }
1602: }
1603: }
1604: }
1605: $thesestr='';
1606: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1607: $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1608: }
1609: $userroles.='user.adv='.$adv."\n".
1610: 'user.author='.$author."\n";
1611: $ENV{'user.adv'}=$adv;
1612: }
1613: return $userroles;
1614: }
1615:
1616: # --------------------------------------------------------------- get interface
1617:
1618: sub get {
1619: my ($namespace,$storearr,$udomain,$uname)=@_;
1620: my $items='';
1621: foreach (@$storearr) {
1622: $items.=escape($_).'&';
1623: }
1624: $items=~s/\&$//;
1625: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1626: if (!$uname) { $uname=$ENV{'user.name'}; }
1627: my $uhome=&homeserver($uname,$udomain);
1628:
1629: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1630: my @pairs=split(/\&/,$rep);
1631: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1632: return @pairs;
1633: }
1634: my %returnhash=();
1635: my $i=0;
1636: foreach (@$storearr) {
1637: $returnhash{$_}=unescape($pairs[$i]);
1638: $i++;
1639: }
1640: return %returnhash;
1641: }
1642:
1643: # --------------------------------------------------------------- del interface
1644:
1645: sub del {
1646: my ($namespace,$storearr,$udomain,$uname)=@_;
1647: my $items='';
1648: foreach (@$storearr) {
1649: $items.=escape($_).'&';
1650: }
1651: $items=~s/\&$//;
1652: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1653: if (!$uname) { $uname=$ENV{'user.name'}; }
1654: my $uhome=&homeserver($uname,$udomain);
1655:
1656: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1657: }
1658:
1659: # -------------------------------------------------------------- dump interface
1660:
1661: sub dump {
1662: my ($namespace,$udomain,$uname,$regexp)=@_;
1663: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1664: if (!$uname) { $uname=$ENV{'user.name'}; }
1665: my $uhome=&homeserver($uname,$udomain);
1666: if ($regexp) {
1667: $regexp=&escape($regexp);
1668: } else {
1669: $regexp='.';
1670: }
1671: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1672: my @pairs=split(/\&/,$rep);
1673: my %returnhash=();
1674: foreach (@pairs) {
1675: my ($key,$value)=split(/=/,$_);
1676: $returnhash{unescape($key)}=unescape($value);
1677: }
1678: return %returnhash;
1679: }
1680:
1681: # --------------------------------------------------------------- put interface
1682:
1683: sub put {
1684: my ($namespace,$storehash,$udomain,$uname)=@_;
1685: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1686: if (!$uname) { $uname=$ENV{'user.name'}; }
1687: my $uhome=&homeserver($uname,$udomain);
1688: my $items='';
1689: foreach (keys %$storehash) {
1690: $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1691: }
1692: $items=~s/\&$//;
1693: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1694: }
1695:
1696: # ------------------------------------------------------ critical put interface
1697:
1698: sub cput {
1699: my ($namespace,$storehash,$udomain,$uname)=@_;
1700: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1701: if (!$uname) { $uname=$ENV{'user.name'}; }
1702: my $uhome=&homeserver($uname,$udomain);
1703: my $items='';
1704: foreach (keys %$storehash) {
1705: $items.=escape($_).'='.escape($$storehash{$_}).'&';
1706: }
1707: $items=~s/\&$//;
1708: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1709: }
1710:
1711: # -------------------------------------------------------------- eget interface
1712:
1713: sub eget {
1714: my ($namespace,$storearr,$udomain,$uname)=@_;
1715: my $items='';
1716: foreach (@$storearr) {
1717: $items.=escape($_).'&';
1718: }
1719: $items=~s/\&$//;
1720: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1721: if (!$uname) { $uname=$ENV{'user.name'}; }
1722: my $uhome=&homeserver($uname,$udomain);
1723: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1724: my @pairs=split(/\&/,$rep);
1725: my %returnhash=();
1726: my $i=0;
1727: foreach (@$storearr) {
1728: $returnhash{$_}=unescape($pairs[$i]);
1729: $i++;
1730: }
1731: return %returnhash;
1732: }
1733:
1734: # ------------------------------------------------- Check for a user privilege
1735:
1736: sub allowed {
1737: my ($priv,$uri)=@_;
1738:
1739: my $orguri=$uri;
1740: $uri=&declutter($uri);
1741:
1742: # Free bre access to adm and meta resources
1743:
1744: if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1745: return 'F';
1746: }
1747:
1748: # Free bre to public access
1749:
1750: if ($priv eq 'bre') {
1751: my $copyright=&metadata($uri,'copyright');
1752: if ($copyright eq 'public') { return 'F'; }
1753: if ($copyright eq 'priv') {
1754: $uri=~/([^\/]+)\/([^\/]+)\//;
1755: unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
1756: return '';
1757: }
1758: }
1759: if ($copyright eq 'domain') {
1760: $uri=~/([^\/]+)\/([^\/]+)\//;
1761: unless (($ENV{'user.domain'} eq $1) ||
1762: ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
1763: return '';
1764: }
1765: }
1766: if ($ENV{'request.role'}=~ /li\.\//) {
1767: # Library role, so allow browsing of resources in this domain.
1768: return 'F';
1769: }
1770: }
1771: # Domain coordinator is trying to create a course
1772: if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
1773: # uri is the requested domain in this case.
1774: # comparison to 'request.role.domain' shows if the user has selected
1775: # a role of dc for the domain in question.
1776: return 'F' if ($uri eq $ENV{'request.role.domain'});
1777: }
1778:
1779: my $thisallowed='';
1780: my $statecond=0;
1781: my $courseprivid='';
1782:
1783: # Course
1784:
1785: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
1786: $thisallowed.=$1;
1787: }
1788:
1789: # Domain
1790:
1791: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1792: =~/$priv\&([^\:]*)/) {
1793: $thisallowed.=$1;
1794: }
1795:
1796: # Course: uri itself is a course
1797: my $courseuri=$uri;
1798: $courseuri=~s/\_(\d)/\/$1/;
1799: $courseuri=~s/^([^\/])/\/$1/;
1800:
1801: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1802: =~/$priv\&([^\:]*)/) {
1803: $thisallowed.=$1;
1804: }
1805:
1806: # Full access at system, domain or course-wide level? Exit.
1807:
1808: if ($thisallowed=~/F/) {
1809: return 'F';
1810: }
1811:
1812: # If this is generating or modifying users, exit with special codes
1813:
1814: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1815: return $thisallowed;
1816: }
1817: #
1818: # Gathered so far: system, domain and course wide privileges
1819: #
1820: # Course: See if uri or referer is an individual resource that is part of
1821: # the course
1822:
1823: if ($ENV{'request.course.id'}) {
1824:
1825: $courseprivid=$ENV{'request.course.id'};
1826: if ($ENV{'request.course.sec'}) {
1827: $courseprivid.='/'.$ENV{'request.course.sec'};
1828: }
1829: $courseprivid=~s/\_/\//;
1830: my $checkreferer=1;
1831: my ($match,$cond)=&is_on_map($uri);
1832: if ($match) {
1833: $statecond=$cond;
1834: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1835: =~/$priv\&([^\:]*)/) {
1836: $thisallowed.=$1;
1837: $checkreferer=0;
1838: }
1839: }
1840:
1841: if ($checkreferer) {
1842: my $refuri=$ENV{'httpref.'.$orguri};
1843: unless ($refuri) {
1844: foreach (keys %ENV) {
1845: if ($_=~/^httpref\..*\*/) {
1846: my $pattern=$_;
1847: $pattern=~s/^httpref\.\/res\///;
1848: $pattern=~s/\*/\[\^\/\]\+/g;
1849: $pattern=~s/\//\\\//g;
1850: if ($orguri=~/$pattern/) {
1851: $refuri=$ENV{$_};
1852: }
1853: }
1854: }
1855: }
1856:
1857: if ($refuri) {
1858: $refuri=&declutter($refuri);
1859: my ($match,$cond)=&is_on_map($refuri);
1860: if ($match) {
1861: my $refstatecond=$cond;
1862: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1863: =~/$priv\&([^\:]*)/) {
1864: $thisallowed.=$1;
1865: $uri=$refuri;
1866: $statecond=$refstatecond;
1867: }
1868: }
1869: }
1870: }
1871: }
1872:
1873: #
1874: # Gathered now: all privileges that could apply, and condition number
1875: #
1876: #
1877: # Full or no access?
1878: #
1879:
1880: if ($thisallowed=~/F/) {
1881: return 'F';
1882: }
1883:
1884: unless ($thisallowed) {
1885: return '';
1886: }
1887:
1888: # Restrictions exist, deal with them
1889: #
1890: # C:according to course preferences
1891: # R:according to resource settings
1892: # L:unless locked
1893: # X:according to user session state
1894: #
1895:
1896: # Possibly locked functionality, check all courses
1897: # Locks might take effect only after 10 minutes cache expiration for other
1898: # courses, and 2 minutes for current course
1899:
1900: my $envkey;
1901: if ($thisallowed=~/L/) {
1902: foreach $envkey (keys %ENV) {
1903: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
1904: my $courseid=$2;
1905: my $roleid=$1.'.'.$2;
1906: $courseid=~s/^\///;
1907: my $expiretime=600;
1908: if ($ENV{'request.role'} eq $roleid) {
1909: $expiretime=120;
1910: }
1911: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
1912: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1913: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
1914: &coursedescription($courseid);
1915: }
1916: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
1917: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
1918: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1919: &log($ENV{'user.domain'},$ENV{'user.name'},
1920: $ENV{'user.home'},
1921: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1922: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1923: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1924: return '';
1925: }
1926: }
1927: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
1928: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1929: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1930: &log($ENV{'user.domain'},$ENV{'user.name'},
1931: $ENV{'user.home'},
1932: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1933: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1934: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1935: return '';
1936: }
1937: }
1938: }
1939: }
1940: }
1941:
1942: #
1943: # Rest of the restrictions depend on selected course
1944: #
1945:
1946: unless ($ENV{'request.course.id'}) {
1947: return '1';
1948: }
1949:
1950: #
1951: # Now user is definitely in a course
1952: #
1953:
1954:
1955: # Course preferences
1956:
1957: if ($thisallowed=~/C/) {
1958: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1959: my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1960: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1961: =~/$rolecode/) {
1962: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1963: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1964: $ENV{'request.course.id'});
1965: return '';
1966: }
1967:
1968: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
1969: =~/$unamedom/) {
1970: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1971: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1972: $ENV{'request.course.id'});
1973: return '';
1974: }
1975: }
1976:
1977: # Resource preferences
1978:
1979: if ($thisallowed=~/R/) {
1980: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1981: my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
1982: if (-e $filename) {
1983: my @content;
1984: {
1985: my $fh=Apache::File->new($filename);
1986: @content=<$fh>;
1987: }
1988: if (join('',@content)=~
1989: /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1990: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1991: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1992: return '';
1993:
1994: }
1995: }
1996: }
1997:
1998: # Restricted by state or randomout?
1999:
2000: if ($thisallowed=~/X/) {
2001: if ($ENV{'acc.randomout'}) {
2002: my $symb=&symbread($uri,1);
2003: if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) {
2004: return '';
2005: }
2006: }
2007: if (&condval($statecond)) {
2008: return '2';
2009: } else {
2010: return '';
2011: }
2012: }
2013:
2014: return 'F';
2015: }
2016:
2017: # --------------------------------------------------- Is a resource on the map?
2018:
2019: sub is_on_map {
2020: my $uri=&declutter(shift);
2021: my @uriparts=split(/\//,$uri);
2022: my $filename=$uriparts[$#uriparts];
2023: my $pathname=$uri;
2024: $pathname=~s|/\Q$filename\E$||;
2025: #Trying to find the conditional for the file
2026: my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
2027: /\&\Q$filename\E\:([\d\|]+)\&/);
2028: if ($match) {
2029: return (1,$1);
2030: } else {
2031: return (0,0);
2032: }
2033: }
2034:
2035: # ----------------------------------------------------------------- Define Role
2036:
2037: sub definerole {
2038: if (allowed('mcr','/')) {
2039: my ($rolename,$sysrole,$domrole,$courole)=@_;
2040: foreach (split('/',$sysrole)) {
2041: my ($crole,$cqual)=split(/\&/,$_);
2042: if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
2043: if ($pr{'cr:s'}=~/$crole\&/) {
2044: if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) {
2045: return "refused:s:$crole&$cqual";
2046: }
2047: }
2048: }
2049: foreach (split('/',$domrole)) {
2050: my ($crole,$cqual)=split(/\&/,$_);
2051: if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
2052: if ($pr{'cr:d'}=~/$crole\&/) {
2053: if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) {
2054: return "refused:d:$crole&$cqual";
2055: }
2056: }
2057: }
2058: foreach (split('/',$courole)) {
2059: my ($crole,$cqual)=split(/\&/,$_);
2060: if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
2061: if ($pr{'cr:c'}=~/$crole\&/) {
2062: if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) {
2063: return "refused:c:$crole&$cqual";
2064: }
2065: }
2066: }
2067: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2068: "$ENV{'user.domain'}:$ENV{'user.name'}:".
2069: "rolesdef_$rolename=".
2070: escape($sysrole.'_'.$domrole.'_'.$courole);
2071: return reply($command,$ENV{'user.home'});
2072: } else {
2073: return 'refused';
2074: }
2075: }
2076:
2077: # ---------------- Make a metadata query against the network of library servers
2078:
2079: sub metadata_query {
2080: my ($query,$custom,$customshow,$server_array)=@_;
2081: my %rhash;
2082: my @server_list = (defined($server_array) ? @$server_array
2083: : keys(%libserv) );
2084: for my $server (@server_list) {
2085: unless ($custom or $customshow) {
2086: my $reply=&reply("querysend:".&escape($query),$server);
2087: $rhash{$server}=$reply;
2088: }
2089: else {
2090: my $reply=&reply("querysend:".&escape($query).':'.
2091: &escape($custom).':'.&escape($customshow),
2092: $server);
2093: $rhash{$server}=$reply;
2094: }
2095: }
2096: return \%rhash;
2097: }
2098:
2099: # ----------------------------------------- Send log queries and wait for reply
2100:
2101: sub log_query {
2102: my ($uname,$udom,$query,%filters)=@_;
2103: my $uhome=&homeserver($uname,$udom);
2104: if ($uhome eq 'no_host') { return 'error: no_host'; }
2105: my $uhost=$hostname{$uhome};
2106: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
2107: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
2108: $uhome);
2109: unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
2110: return get_query_reply($queryid);
2111: }
2112:
2113: sub get_query_reply {
2114: my $queryid=shift;
2115: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
2116: my $reply='';
2117: for (1..100) {
2118: sleep 2;
2119: if (-e $replyfile.'.end') {
2120: if (my $fh=Apache::File->new($replyfile)) {
2121: $reply.=<$fh>;
2122: $fh->close;
2123: } else { return 'error: reply_file_error'; }
2124: return &unescape($reply);
2125: }
2126: }
2127: return 'timeout:'.$queryid;
2128: }
2129:
2130: sub courselog_query {
2131: #
2132: # possible filters:
2133: # url: url or symb
2134: # username
2135: # domain
2136: # action: view, submit, grade
2137: # start: timestamp
2138: # end: timestamp
2139: #
2140: my (%filters)=@_;
2141: unless ($ENV{'request.course.id'}) { return 'no_course'; }
2142: if ($filters{'url'}) {
2143: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
2144: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
2145: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
2146: }
2147: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
2148: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
2149: return &log_query($cname,$cdom,'courselog',%filters);
2150: }
2151:
2152: sub userlog_query {
2153: my ($uname,$udom,%filters)=@_;
2154: return &log_query($uname,$udom,'userlog',%filters);
2155: }
2156:
2157: # ------------------------------------------------------------------ Plain Text
2158:
2159: sub plaintext {
2160: my $short=shift;
2161: return $prp{$short};
2162: }
2163:
2164: # ----------------------------------------------------------------- Assign Role
2165:
2166: sub assignrole {
2167: my ($udom,$uname,$url,$role,$end,$start)=@_;
2168: my $mrole;
2169: if ($role =~ /^cr\//) {
2170: unless (&allowed('ccr',$url)) {
2171: &logthis('Refused custom assignrole: '.
2172: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2173: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2174: return 'refused';
2175: }
2176: $mrole='cr';
2177: } else {
2178: my $cwosec=$url;
2179: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
2180: unless (&allowed('c'.$role,$cwosec)) {
2181: &logthis('Refused assignrole: '.
2182: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2183: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2184: return 'refused';
2185: }
2186: $mrole=$role;
2187: }
2188: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2189: "$udom:$uname:$url".'_'."$mrole=$role";
2190: if ($end) { $command.='_'.$end; }
2191: if ($start) {
2192: if ($end) {
2193: $command.='_'.$start;
2194: } else {
2195: $command.='_0_'.$start;
2196: }
2197: }
2198: return &reply($command,&homeserver($uname,$udom));
2199: }
2200:
2201: # -------------------------------------------------- Modify user authentication
2202: # Overrides without validation
2203:
2204: sub modifyuserauth {
2205: my ($udom,$uname,$umode,$upass)=@_;
2206: my $uhome=&homeserver($uname,$udom);
2207: unless (&allowed('mau',$udom)) { return 'refused'; }
2208: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
2209: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
2210: ' in domain '.$ENV{'request.role.domain'});
2211: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
2212: &escape($upass),$uhome);
2213: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
2214: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
2215: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
2216: &log($udom,,$uname,$uhome,
2217: 'Authentication changed by '.$ENV{'user.domain'}.', '.
2218: $ENV{'user.name'}.', '.$umode.
2219: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
2220: unless ($reply eq 'ok') {
2221: &logthis('Authentication mode error: '.$reply);
2222: return 'error: '.$reply;
2223: }
2224: return 'ok';
2225: }
2226:
2227: # --------------------------------------------------------------- Modify a user
2228:
2229: sub modifyuser {
2230: my ($udom, $uname, $uid,
2231: $umode, $upass, $first,
2232: $middle, $last, $gene,
2233: $forceid, $desiredhome)=@_;
2234: $udom=~s/\W//g;
2235: $uname=~s/\W//g;
2236: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
2237: $umode.', '.$first.', '.$middle.', '.
2238: $last.', '.$gene.'(forceid: '.$forceid.')'.
2239: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
2240: ' desiredhome not specified').
2241: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
2242: ' in domain '.$ENV{'request.role.domain'});
2243: my $uhome=&homeserver($uname,$udom,'true');
2244: # ----------------------------------------------------------------- Create User
2245: if (($uhome eq 'no_host') && ($umode) && ($upass)) {
2246: my $unhome='';
2247: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
2248: $unhome = $desiredhome;
2249: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
2250: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
2251: } else { # load balancing routine for determining $unhome
2252: my $tryserver;
2253: my $loadm=10000000;
2254: foreach $tryserver (keys %libserv) {
2255: if ($hostdom{$tryserver} eq $udom) {
2256: my $answer=reply('load',$tryserver);
2257: if (($answer=~/\d+/) && ($answer<$loadm)) {
2258: $loadm=$answer;
2259: $unhome=$tryserver;
2260: }
2261: }
2262: }
2263: }
2264: if (($unhome eq '') || ($unhome eq 'no_host')) {
2265: return 'error: unable to find a home server for '.$uname.
2266: ' in domain '.$udom;
2267: }
2268: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
2269: &escape($upass),$unhome);
2270: unless ($reply eq 'ok') {
2271: return 'error: '.$reply;
2272: }
2273: $uhome=&homeserver($uname,$udom,'true');
2274: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
2275: return 'error: verify home';
2276: }
2277: } # End of creation of new user
2278: # ---------------------------------------------------------------------- Add ID
2279: if ($uid) {
2280: $uid=~tr/A-Z/a-z/;
2281: my %uidhash=&idrget($udom,$uname);
2282: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
2283: && (!$forceid)) {
2284: unless ($uid eq $uidhash{$uname}) {
2285: return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
2286: }
2287: } else {
2288: &idput($udom,($uname => $uid));
2289: }
2290: }
2291: # -------------------------------------------------------------- Add names, etc
2292: my %names=&get('environment',
2293: ['firstname','middlename','lastname','generation'],
2294: $udom,$uname);
2295: if ($names{'firstname'} =~ m/^error:.*/) { %names=(); }
2296: if ($first) { $names{'firstname'} = $first; }
2297: if ($middle) { $names{'middlename'} = $middle; }
2298: if ($last) { $names{'lastname'} = $last; }
2299: if ($gene) { $names{'generation'} = $gene; }
2300: my $reply = &put('environment', \%names, $udom,$uname);
2301: if ($reply ne 'ok') { return 'error: '.$reply; }
2302: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
2303: $umode.', '.$first.', '.$middle.', '.
2304: $last.', '.$gene.' by '.
2305: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2306: return 'ok';
2307: }
2308:
2309: # -------------------------------------------------------------- Modify student
2310:
2311: sub modifystudent {
2312: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
2313: $end,$start,$forceid,$desiredhome)=@_;
2314: my $cid='';
2315: unless ($cid=$ENV{'request.course.id'}) {
2316: return 'not_in_class';
2317: }
2318: # --------------------------------------------------------------- Make the user
2319: my $reply=&modifyuser
2320: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
2321: $desiredhome);
2322: unless ($reply eq 'ok') { return $reply; }
2323: # This will cause &modify_student_enrollment to get the uid from the
2324: # students environment
2325: $uid = undef if (!$forceid);
2326: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
2327: $last,$gene,$usec,$end,$start);
2328: return $reply;
2329: }
2330:
2331: sub modify_student_enrollment {
2332: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
2333: # Get the course id from the environment
2334: my $cid='';
2335: unless ($cid=$ENV{'request.course.id'}) {
2336: return 'not_in_class';
2337: }
2338: # Make sure the user exists
2339: my $uhome=&homeserver($uname,$udom);
2340: if (($uhome eq '') || ($uhome eq 'no_host')) {
2341: return 'error: no such user';
2342: }
2343: #
2344: # Get student data if we were not given enough information
2345: if (!defined($first) || $first eq '' ||
2346: !defined($last) || $last eq '' ||
2347: !defined($uid) || $uid eq '' ||
2348: !defined($middle) || $middle eq '' ||
2349: !defined($gene) || $gene eq '') {
2350: # They did not supply us with enough data to enroll the student, so
2351: # we need to pick up more information.
2352: my %tmp = &get('environment',
2353: ['firstname','middlename','lastname', 'generation','id']
2354: ,$udom,$uname);
2355:
2356: foreach (keys(%tmp)) {
2357: &logthis("key $_ = ".$tmp{$_});
2358: }
2359: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
2360: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
2361: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
2362: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
2363: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
2364: }
2365: my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
2366: $first,$middle);
2367: my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
2368: $ENV{'course.'.$cid.'.num'}.':classlist:'.
2369: &escape($uname.':'.$udom).'='.
2370: &escape(join(':',$end,$start,$uid,$usec,$fullname)),
2371: $ENV{'course.'.$cid.'.home'});
2372: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
2373: return 'error: '.$reply;
2374: }
2375: # Add student role to user
2376: my $uurl='/'.$cid;
2377: $uurl=~s/\_/\//g;
2378: if ($usec) {
2379: $uurl.='/'.$usec;
2380: }
2381: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
2382: }
2383:
2384: # ------------------------------------------------- Write to course preferences
2385:
2386: sub writecoursepref {
2387: my ($courseid,%prefs)=@_;
2388: $courseid=~s/^\///;
2389: $courseid=~s/\_/\//g;
2390: my ($cdomain,$cnum)=split(/\//,$courseid);
2391: my $chome=homeserver($cnum,$cdomain);
2392: if (($chome eq '') || ($chome eq 'no_host')) {
2393: return 'error: no such course';
2394: }
2395: my $cstring='';
2396: foreach (keys %prefs) {
2397: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
2398: }
2399: $cstring=~s/\&$//;
2400: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
2401: }
2402:
2403: # ---------------------------------------------------------- Make/modify course
2404:
2405: sub createcourse {
2406: my ($udom,$description,$url,$course_server,$nonstandard)=@_;
2407: $url=&declutter($url);
2408: my $cid='';
2409: unless (&allowed('ccc',$udom)) {
2410: return 'refused';
2411: }
2412: # ------------------------------------------------------------------- Create ID
2413: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
2414: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
2415: # ----------------------------------------------- Make sure that does not exist
2416: my $uhome=&homeserver($uname,$udom,'true');
2417: unless (($uhome eq '') || ($uhome eq 'no_host')) {
2418: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
2419: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
2420: $uhome=&homeserver($uname,$udom,'true');
2421: unless (($uhome eq '') || ($uhome eq 'no_host')) {
2422: return 'error: unable to generate unique course-ID';
2423: }
2424: }
2425: # ------------------------------------------------ Check supplied server name
2426: $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
2427: if (! exists($libserv{$course_server})) {
2428: return 'error:bad server name '.$course_server;
2429: }
2430: # ------------------------------------------------------------- Make the course
2431: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
2432: $course_server);
2433: unless ($reply eq 'ok') { return 'error: '.$reply; }
2434: $uhome=&homeserver($uname,$udom,'true');
2435: if (($uhome eq '') || ($uhome eq 'no_host')) {
2436: return 'error: no such course';
2437: }
2438: # ----------------------------------------------------------------- Course made
2439: my $topurl=$url;
2440: unless ($nonstandard) {
2441: # ------------------------------------------ For standard courses, make top url
2442: my $mapurl=&clutter($url);
2443: if ($mapurl eq '/res/') { $mapurl=''; }
2444: $ENV{'form.initmap'}=(<<ENDINITMAP);
2445: <map>
2446: <resource id="1" type="start"></resource>
2447: <resource id="2" src="$mapurl"></resource>
2448: <resource id="3" type="finish"></resource>
2449: <link index="1" from="1" to="2"></link>
2450: <link index="2" from="2" to="3"></link>
2451: </map>
2452: ENDINITMAP
2453: $topurl=&declutter(
2454: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
2455: );
2456: }
2457: # ----------------------------------------------------------- Write preferences
2458: &writecoursepref($udom.'_'.$uname,
2459: ('description' => $description,
2460: 'url' => $topurl));
2461: return '/'.$udom.'/'.$uname;
2462: }
2463:
2464: # ---------------------------------------------------------- Assign Custom Role
2465:
2466: sub assigncustomrole {
2467: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
2468: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
2469: $end,$start);
2470: }
2471:
2472: # ----------------------------------------------------------------- Revoke Role
2473:
2474: sub revokerole {
2475: my ($udom,$uname,$url,$role)=@_;
2476: my $now=time;
2477: return &assignrole($udom,$uname,$url,$role,$now);
2478: }
2479:
2480: # ---------------------------------------------------------- Revoke Custom Role
2481:
2482: sub revokecustomrole {
2483: my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
2484: my $now=time;
2485: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
2486: }
2487:
2488: # ------------------------------------------------------------ Directory lister
2489:
2490: sub dirlist {
2491: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
2492:
2493: $uri=~s/^\///;
2494: $uri=~s/\/$//;
2495: my ($udom, $uname);
2496: (undef,$udom,$uname)=split(/\//,$uri);
2497: if(defined($userdomain)) {
2498: $udom = $userdomain;
2499: }
2500: if(defined($username)) {
2501: $uname = $username;
2502: }
2503:
2504: my $dirRoot = $perlvar{'lonDocRoot'};
2505: if(defined($alternateDirectoryRoot)) {
2506: $dirRoot = $alternateDirectoryRoot;
2507: $dirRoot =~ s/\/$//;
2508: }
2509:
2510: if($udom) {
2511: if($uname) {
2512: my $listing=reply('ls:'.$dirRoot.'/'.$uri,
2513: homeserver($uname,$udom));
2514: return split(/:/,$listing);
2515: } elsif(!defined($alternateDirectoryRoot)) {
2516: my $tryserver;
2517: my %allusers=();
2518: foreach $tryserver (keys %libserv) {
2519: if($hostdom{$tryserver} eq $udom) {
2520: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
2521: $udom, $tryserver);
2522: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
2523: && ($listing ne 'con_lost')) {
2524: foreach (split(/:/,$listing)) {
2525: my ($entry,@stat)=split(/&/,$_);
2526: $allusers{$entry}=1;
2527: }
2528: }
2529: }
2530: }
2531: my $alluserstr='';
2532: foreach (sort keys %allusers) {
2533: $alluserstr.=$_.'&user:';
2534: }
2535: $alluserstr=~s/:$//;
2536: return split(/:/,$alluserstr);
2537: } else {
2538: my @emptyResults = ();
2539: push(@emptyResults, 'missing user name');
2540: return split(':',@emptyResults);
2541: }
2542: } elsif(!defined($alternateDirectoryRoot)) {
2543: my $tryserver;
2544: my %alldom=();
2545: foreach $tryserver (keys %libserv) {
2546: $alldom{$hostdom{$tryserver}}=1;
2547: }
2548: my $alldomstr='';
2549: foreach (sort keys %alldom) {
2550: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
2551: }
2552: $alldomstr=~s/:$//;
2553: return split(/:/,$alldomstr);
2554: } else {
2555: my @emptyResults = ();
2556: push(@emptyResults, 'missing domain');
2557: return split(':',@emptyResults);
2558: }
2559: }
2560:
2561: # --------------------------------------------- GetFileTimestamp
2562: # This function utilizes dirlist and returns the date stamp for
2563: # when it was last modified. It will also return an error of -1
2564: # if an error occurs
2565:
2566: sub GetFileTimestamp {
2567: my ($studentDomain,$studentName,$filename,$root)=@_;
2568: $studentDomain=~s/\W//g;
2569: $studentName=~s/\W//g;
2570: my $subdir=$studentName.'__';
2571: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
2572: my $proname="$studentDomain/$subdir/$studentName";
2573: $proname .= '/'.$filename;
2574: my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
2575: $root);
2576: my $fileStat = $dir[0];
2577: my @stats = split('&', $fileStat);
2578: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
2579: return $stats[9];
2580: } else {
2581: return -1;
2582: }
2583: }
2584:
2585: # -------------------------------------------------------- Value of a Condition
2586:
2587: sub directcondval {
2588: my $number=shift;
2589: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
2590: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
2591: } else {
2592: return 2;
2593: }
2594: }
2595:
2596: sub condval {
2597: my $condidx=shift;
2598: my $result=0;
2599: my $allpathcond='';
2600: foreach (split(/\|/,$condidx)) {
2601: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
2602: $allpathcond.=
2603: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
2604: }
2605: }
2606: $allpathcond=~s/\|$//;
2607: if ($ENV{'request.course.id'}) {
2608: if ($allpathcond) {
2609: my $operand='|';
2610: my @stack;
2611: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
2612: if ($_ eq '(') {
2613: push @stack,($operand,$result)
2614: } elsif ($_ eq ')') {
2615: my $before=pop @stack;
2616: if (pop @stack eq '&') {
2617: $result=$result>$before?$before:$result;
2618: } else {
2619: $result=$result>$before?$result:$before;
2620: }
2621: } elsif (($_ eq '&') || ($_ eq '|')) {
2622: $operand=$_;
2623: } else {
2624: my $new=directcondval($_);
2625: if ($operand eq '&') {
2626: $result=$result>$new?$new:$result;
2627: } else {
2628: $result=$result>$new?$result:$new;
2629: }
2630: }
2631: }
2632: }
2633: }
2634: return $result;
2635: }
2636:
2637: # ---------------------------------------------------- Devalidate courseresdata
2638:
2639: sub devalidatecourseresdata {
2640: my ($coursenum,$coursedomain)=@_;
2641: my $hashid=$coursenum.':'.$coursedomain;
2642: delete $courseresdatacache{$hashid.'.time'};
2643: }
2644:
2645: # --------------------------------------------------- Course Resourcedata Query
2646:
2647: sub courseresdata {
2648: my ($coursenum,$coursedomain,@which)=@_;
2649: my $coursehom=&homeserver($coursenum,$coursedomain);
2650: my $hashid=$coursenum.':'.$coursedomain;
2651: my $dodump=0;
2652: if (!defined($courseresdatacache{$hashid.'.time'})) {
2653: $dodump=1;
2654: } else {
2655: if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
2656: }
2657: if ($dodump) {
2658: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
2659: my ($tmp) = keys(%dumpreply);
2660: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
2661: $courseresdatacache{$hashid.'.time'}=time;
2662: $courseresdatacache{$hashid}=\%dumpreply;
2663: }
2664: }
2665: foreach my $item (@which) {
2666: if (defined($courseresdatacache{$hashid}->{$item})) {
2667: return $courseresdatacache{$hashid}->{$item};
2668: }
2669: }
2670: return undef;
2671: }
2672:
2673: # --------------------------------------------------------- Value of a Variable
2674:
2675: sub EXT {
2676: my ($varname,$symbparm,$udom,$uname,)=@_;
2677:
2678: unless ($varname) { return ''; }
2679:
2680: #get real user name/domain, courseid and symb
2681: my $courseid;
2682: if (!($uname && $udom)) {
2683: (my $cursymb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
2684: if (!$symbparm) { $symbparm=$cursymb; }
2685: } else {
2686: $courseid=$ENV{'request.course.id'};
2687: }
2688:
2689: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
2690: my $rest;
2691: if ($therest[0]) {
2692: $rest=join('.',@therest);
2693: } else {
2694: $rest='';
2695: }
2696: my $qualifierrest=$qualifier;
2697: if ($rest) { $qualifierrest.='.'.$rest; }
2698: my $spacequalifierrest=$space;
2699: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
2700: if ($realm eq 'user') {
2701: # --------------------------------------------------------------- user.resource
2702: if ($space eq 'resource') {
2703: my %restored=&restore(undef,undef,$udom,$uname);
2704: return $restored{$qualifierrest};
2705: # ----------------------------------------------------------------- user.access
2706: } elsif ($space eq 'access') {
2707: # FIXME - not supporting calls for a specific user
2708: return &allowed($qualifier,$rest);
2709: # ------------------------------------------ user.preferences, user.environment
2710: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
2711: if (($uname eq $ENV{'user.name'}) &&
2712: ($udom eq $ENV{'user.domain'})) {
2713: return $ENV{join('.',('environment',$qualifierrest))};
2714: } else {
2715: my %returnhash=&userenvironment($udom,$uname,$qualifierrest);
2716: return $returnhash{$qualifierrest};
2717: }
2718: # ----------------------------------------------------------------- user.course
2719: } elsif ($space eq 'course') {
2720: # FIXME - not supporting calls for a specific user
2721: return $ENV{join('.',('request.course',$qualifier))};
2722: # ------------------------------------------------------------------- user.role
2723: } elsif ($space eq 'role') {
2724: # FIXME - not supporting calls for a specific user
2725: my ($role,$where)=split(/\./,$ENV{'request.role'});
2726: if ($qualifier eq 'value') {
2727: return $role;
2728: } elsif ($qualifier eq 'extent') {
2729: return $where;
2730: }
2731: # ----------------------------------------------------------------- user.domain
2732: } elsif ($space eq 'domain') {
2733: return $udom;
2734: # ------------------------------------------------------------------- user.name
2735: } elsif ($space eq 'name') {
2736: return $uname;
2737: # ---------------------------------------------------- Any other user namespace
2738: } else {
2739: my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
2740: my %reply=&get($space,[$item]);
2741: return $reply{$item};
2742: }
2743: } elsif ($realm eq 'query') {
2744: # ---------------------------------------------- pull stuff out of query string
2745: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
2746: return $ENV{'form.'.$space};
2747: } elsif ($realm eq 'request') {
2748: # ------------------------------------------------------------- request.browser
2749: if ($space eq 'browser') {
2750: return $ENV{'browser.'.$qualifier};
2751: # ------------------------------------------------------------ request.filename
2752: } else {
2753: return $ENV{'request.'.$spacequalifierrest};
2754: }
2755: } elsif ($realm eq 'course') {
2756: # ---------------------------------------------------------- course.description
2757: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
2758: } elsif ($realm eq 'resource') {
2759:
2760: if ($courseid eq $ENV{'request.course.id'}) {
2761:
2762: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
2763:
2764: # ----------------------------------------------------- Cascading lookup scheme
2765: if (!$symbparm) { $symbparm=&symbread(); }
2766: my $symbp=$symbparm;
2767: my $mapp=(split(/\_\_\_/,$symbp))[0];
2768:
2769: my $symbparm=$symbp.'.'.$spacequalifierrest;
2770: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
2771:
2772: my $section;
2773: if (($ENV{'user.name'} eq $uname) &&
2774: ($ENV{'user.domain'} eq $udom)) {
2775: $section=$ENV{'request.course.sec'};
2776: } else {
2777: $section=&usection($udom,$uname,$courseid);
2778: }
2779:
2780: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
2781: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
2782: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
2783:
2784: my $courselevel=$courseid.'.'.$spacequalifierrest;
2785: my $courselevelr=$courseid.'.'.$symbparm;
2786: my $courselevelm=$courseid.'.'.$mapparm;
2787:
2788: # ----------------------------------------------------------- first, check user
2789: my %resourcedata=&get('resourcedata',
2790: [$courselevelr,$courselevelm,$courselevel],
2791: $udom,$uname);
2792: if (($resourcedata{$courselevelr}!~/^error\:/) &&
2793: ($resourcedata{$courselevelr}!~/^con_lost/)) {
2794:
2795: if ($resourcedata{$courselevelr}) {
2796: return $resourcedata{$courselevelr}; }
2797: if ($resourcedata{$courselevelm}) {
2798: return $resourcedata{$courselevelm}; }
2799: if ($resourcedata{$courselevel}) {
2800: return $resourcedata{$courselevel}; }
2801: } else {
2802: if ($resourcedata{$courselevelr}!~/No such file/) {
2803: &logthis("<font color=blue>WARNING:".
2804: " Trying to get resource data for ".
2805: $uname." at ".$udom.": ".
2806: $resourcedata{$courselevelr}."</font>");
2807: }
2808: }
2809:
2810: # -------------------------------------------------------- second, check course
2811:
2812: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
2813: $ENV{'course.'.$courseid.'.domain'},
2814: ($seclevelr,$seclevelm,$seclevel,
2815: $courselevelr,$courselevelm,
2816: $courselevel));
2817: if (defined($coursereply)) { return $coursereply; }
2818:
2819: # ------------------------------------------------------ third, check map parms
2820: my %parmhash=();
2821: my $thisparm='';
2822: if (tie(%parmhash,'GDBM_File',
2823: $ENV{'request.course.fn'}.'_parms.db',
2824: &GDBM_READER(),0640)) {
2825: $thisparm=$parmhash{$symbparm};
2826: untie(%parmhash);
2827: }
2828: if ($thisparm) { return $thisparm; }
2829: }
2830: # --------------------------------------------- last, look in resource metadata
2831:
2832: $spacequalifierrest=~s/\./\_/;
2833: my $filename;
2834: if (!$symbparm) { $symbparm=&symbread(); }
2835: if ($symbparm) {
2836: $filename=(split(/\_\_\_/,$symbparm))[2];
2837: } else {
2838: $filename=$ENV{'request.filename'};
2839: }
2840: my $metadata=&metadata($filename,$spacequalifierrest);
2841: if (defined($metadata)) { return $metadata; }
2842: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
2843: if (defined($metadata)) { return $metadata; }
2844:
2845: # ------------------------------------------------------------------ Cascade up
2846: unless ($space eq '0') {
2847: my ($part,$id)=split(/\_/,$space);
2848: if ($id) {
2849: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
2850: $symbparm,$udom,$uname);
2851: if (defined($partgeneral)) { return $partgeneral; }
2852: } else {
2853: my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
2854: $symbparm,$udom,$uname);
2855: if (defined($resourcegeneral)) { return $resourcegeneral; }
2856: }
2857: }
2858:
2859: # ---------------------------------------------------- Any other user namespace
2860: } elsif ($realm eq 'environment') {
2861: # ----------------------------------------------------------------- environment
2862: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
2863: return $ENV{'environment.'.$spacequalifierrest};
2864: } else {
2865: my %returnhash=&userenvironment($udom,$uname,
2866: $spacequalifierrest);
2867: return $returnhash{$spacequalifierrest};
2868: }
2869: } elsif ($realm eq 'system') {
2870: # ----------------------------------------------------------------- system.time
2871: if ($space eq 'time') {
2872: return time;
2873: }
2874: }
2875: return '';
2876: }
2877:
2878: # ---------------------------------------------------------------- Get metadata
2879:
2880: sub metadata {
2881: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
2882:
2883: $uri=&declutter($uri);
2884: # if it is a non metadata possible uri return quickly
2885: if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
2886: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
2887: return '';
2888: }
2889: my $filename=$uri;
2890: $uri=~s/\.meta$//;
2891: #
2892: # Is the metadata already cached?
2893: # Look at timestamp of caching
2894: # Everything is cached by the main uri, libraries are never directly cached
2895: #
2896: unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
2897: #
2898: # Is this a recursive call for a library?
2899: #
2900: if ($liburi) {
2901: $liburi=&declutter($liburi);
2902: $filename=$liburi;
2903: }
2904: my %metathesekeys=();
2905: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
2906: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
2907: my $parser=HTML::LCParser->new(\$metastring);
2908: my $token;
2909: undef %metathesekeys;
2910: while ($token=$parser->get_token) {
2911: if ($token->[0] eq 'S') {
2912: if (defined($token->[2]->{'package'})) {
2913: #
2914: # This is a package - get package info
2915: #
2916: my $package=$token->[2]->{'package'};
2917: my $keyroot='';
2918: if ($prefix) {
2919: $keyroot.=$prefix;
2920: } else {
2921: if (defined($token->[2]->{'part'})) {
2922: $keyroot.='_'.$token->[2]->{'part'};
2923: }
2924: }
2925: if (defined($token->[2]->{'id'})) {
2926: $keyroot.='_'.$token->[2]->{'id'};
2927: }
2928: if ($metacache{$uri.':packages'}) {
2929: $metacache{$uri.':packages'}.=','.$package.$keyroot;
2930: } else {
2931: $metacache{$uri.':packages'}=$package.$keyroot;
2932: }
2933: foreach (keys %packagetab) {
2934: if ($_=~/^$package\&/) {
2935: my ($pack,$name,$subp)=split(/\&/,$_);
2936: my $value=$packagetab{$_};
2937: my $part=$keyroot;
2938: $part=~s/^\_//;
2939: if ($subp eq 'display') {
2940: $value.=' [Part: '.$part.']';
2941: }
2942: my $unikey='parameter'.$keyroot.'_'.$name;
2943: $metathesekeys{$unikey}=1;
2944: $metacache{$uri.':'.$unikey.'.part'}=$part;
2945: unless
2946: (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
2947: $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
2948: }
2949: }
2950: }
2951: } else {
2952: #
2953: # This is not a package - some other kind of start tag
2954: #
2955: my $entry=$token->[1];
2956: my $unikey;
2957: if ($entry eq 'import') {
2958: $unikey='';
2959: } else {
2960: $unikey=$entry;
2961: }
2962: if ($prefix) {
2963: $unikey.=$prefix;
2964: } else {
2965: if (defined($token->[2]->{'part'})) {
2966: $unikey.='_'.$token->[2]->{'part'};
2967: }
2968: }
2969: if (defined($token->[2]->{'id'})) {
2970: $unikey.='_'.$token->[2]->{'id'};
2971: }
2972:
2973: if ($entry eq 'import') {
2974: #
2975: # Importing a library here
2976: #
2977: if ($depthcount<20) {
2978: my $location=$parser->get_text('/import');
2979: my $dir=$filename;
2980: $dir=~s|[^/]*$||;
2981: $location=&filelocation($dir,$location);
2982: foreach (sort(split(/\,/,&metadata($uri,'keys',
2983: $location,$unikey,
2984: $depthcount+1)))) {
2985: $metathesekeys{$_}=1;
2986: }
2987: }
2988: } else {
2989:
2990: if (defined($token->[2]->{'name'})) {
2991: $unikey.='_'.$token->[2]->{'name'};
2992: }
2993: $metathesekeys{$unikey}=1;
2994: foreach (@{$token->[3]}) {
2995: $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
2996: }
2997: unless (
2998: $metacache{$uri.':'.$unikey}=&HTML::Entities::decode($parser->get_text('/'.$entry))
2999: ) { $metacache{$uri.':'.$unikey}=
3000: $metacache{$uri.':'.$unikey.'.default'};
3001: }
3002: # end of not-a-package not-a-library import
3003: }
3004: # end of not-a-package start tag
3005: }
3006: # the next is the end of "start tag"
3007: }
3008: }
3009: $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
3010: &metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
3011: $metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
3012: $metacache{$uri.':cachedtimestamp'}=time;
3013: # this is the end of "was not already recently cached
3014: }
3015: return $metacache{$uri.':'.$what};
3016: }
3017:
3018: sub metadata_generate_part0 {
3019: my ($metadata,$metacache,$uri) = @_;
3020: my %allnames;
3021: foreach my $metakey (sort keys %$metadata) {
3022: if ($metakey=~/^parameter\_(.*)/) {
3023: my $part=$$metacache{$uri.':'.$metakey.'.part'};
3024: my $name=$$metacache{$uri.':'.$metakey.'.name'};
3025: if (! exists($$metadata{'parameter_0_'.$name})) {
3026: $allnames{$name}=$part;
3027: }
3028: }
3029: }
3030: foreach my $name (keys(%allnames)) {
3031: $$metadata{"parameter_0_$name"}=1;
3032: my $key="$uri:parameter_0_$name";
3033: $$metacache{"$key.part"}='0';
3034: $$metacache{"$key.name"}=$name;
3035: $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
3036: $allnames{$name}.'_'.$name.
3037: '.type'};
3038: my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
3039: '.display'};
3040: my $expr='\\[Part: '.$allnames{$name}.'\\]';
3041: $olddis=~s/$expr/\[Part: 0\]/;
3042: $$metacache{"$key.display"}=$olddis;
3043: }
3044: }
3045:
3046: # ------------------------------------------------- Update symbolic store links
3047:
3048: sub symblist {
3049: my ($mapname,%newhash)=@_;
3050: $mapname=declutter($mapname);
3051: my %hash;
3052: if (($ENV{'request.course.fn'}) && (%newhash)) {
3053: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
3054: &GDBM_WRCREAT(),0640)) {
3055: foreach (keys %newhash) {
3056: $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
3057: }
3058: if (untie(%hash)) {
3059: return 'ok';
3060: }
3061: }
3062: }
3063: return 'error';
3064: }
3065:
3066: # --------------------------------------------------------------- Verify a symb
3067:
3068: sub symbverify {
3069: my ($symb,$thisfn)=@_;
3070: $thisfn=&declutter($thisfn);
3071: # direct jump to resource in page or to a sequence - will construct own symbs
3072: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
3073: # check URL part
3074: my ($map,$resid,$url)=split(/\_\_\_/,$symb);
3075: unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
3076:
3077: $symb=&symbclean($symb);
3078:
3079: my %bighash;
3080: my $okay=0;
3081: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3082: &GDBM_READER(),0640)) {
3083: my $ids=$bighash{'ids_'.&clutter($thisfn)};
3084: unless ($ids) {
3085: $ids=$bighash{'ids_/'.$thisfn};
3086: }
3087: if ($ids) {
3088: # ------------------------------------------------------------------- Has ID(s)
3089: foreach (split(/\,/,$ids)) {
3090: my ($mapid,$resid)=split(/\./,$_);
3091: if (
3092: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
3093: eq $symb) {
3094: $okay=1;
3095: }
3096: }
3097: }
3098: untie(%bighash);
3099: }
3100: return $okay;
3101: }
3102:
3103: # --------------------------------------------------------------- Clean-up symb
3104:
3105: sub symbclean {
3106: my $symb=shift;
3107:
3108: # remove version from map
3109: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
3110:
3111: # remove version from URL
3112: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
3113:
3114: return $symb;
3115: }
3116:
3117: # ------------------------------------------------------ Return symb list entry
3118:
3119: sub symbread {
3120: my ($thisfn,$donotrecurse)=@_;
3121: # no filename provided? try from environment
3122: unless ($thisfn) {
3123: if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
3124: $thisfn=$ENV{'request.filename'};
3125: }
3126: # is that filename actually a symb? Verify, clean, and return
3127: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
3128: if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
3129: }
3130: $thisfn=declutter($thisfn);
3131: my %hash;
3132: my %bighash;
3133: my $syval='';
3134: if (($ENV{'request.course.fn'}) && ($thisfn)) {
3135: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
3136: &GDBM_READER(),0640)) {
3137: $syval=$hash{$thisfn};
3138: untie(%hash);
3139: }
3140: # ---------------------------------------------------------- There was an entry
3141: if ($syval) {
3142: unless ($syval=~/\_\d+$/) {
3143: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
3144: &appenv('request.ambiguous' => $thisfn);
3145: return '';
3146: }
3147: $syval.=$1;
3148: }
3149: } else {
3150: # ------------------------------------------------------- Was not in symb table
3151: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3152: &GDBM_READER(),0640)) {
3153: # ---------------------------------------------- Get ID(s) for current resource
3154: my $ids=$bighash{'ids_'.&clutter($thisfn)};
3155: unless ($ids) {
3156: $ids=$bighash{'ids_/'.$thisfn};
3157: }
3158: unless ($ids) {
3159: # alias?
3160: $ids=$bighash{'mapalias_'.$thisfn};
3161: }
3162: if ($ids) {
3163: # ------------------------------------------------------------------- Has ID(s)
3164: my @possibilities=split(/\,/,$ids);
3165: if ($#possibilities==0) {
3166: # ----------------------------------------------- There is only one possibility
3167: my ($mapid,$resid)=split(/\./,$ids);
3168: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
3169: } elsif (!$donotrecurse) {
3170: # ------------------------------------------ There is more than one possibility
3171: my $realpossible=0;
3172: foreach (@possibilities) {
3173: my $file=$bighash{'src_'.$_};
3174: if (&allowed('bre',$file)) {
3175: my ($mapid,$resid)=split(/\./,$_);
3176: if ($bighash{'map_type_'.$mapid} ne 'page') {
3177: $realpossible++;
3178: $syval=declutter($bighash{'map_id_'.$mapid}).
3179: '___'.$resid;
3180: }
3181: }
3182: }
3183: if ($realpossible!=1) { $syval=''; }
3184: } else {
3185: $syval='';
3186: }
3187: }
3188: untie(%bighash)
3189: }
3190: }
3191: if ($syval) {
3192: return &symbclean($syval.'___'.$thisfn);
3193: }
3194: }
3195: &appenv('request.ambiguous' => $thisfn);
3196: return '';
3197: }
3198:
3199: # ---------------------------------------------------------- Return random seed
3200:
3201: sub numval {
3202: my $txt=shift;
3203: $txt=~tr/A-J/0-9/;
3204: $txt=~tr/a-j/0-9/;
3205: $txt=~tr/K-T/0-9/;
3206: $txt=~tr/k-t/0-9/;
3207: $txt=~tr/U-Z/0-5/;
3208: $txt=~tr/u-z/0-5/;
3209: $txt=~s/\D//g;
3210: return int($txt);
3211: }
3212:
3213: sub rndseed {
3214: my ($symb,$courseid,$domain,$username)=@_;
3215: if (!$symb) {
3216: unless ($symb=&symbread()) { return time; }
3217: }
3218: if (!$courseid) { $courseid=$ENV{'request.course.id'};}
3219: if (!$domain) {$domain=$ENV{'user.domain'};}
3220: if (!$username) {$username=$ENV{'user.name'};}
3221: {
3222: use integer;
3223: my $symbchck=unpack("%32C*",$symb) << 27;
3224: my $symbseed=numval($symb) << 22;
3225: my $namechck=unpack("%32C*",$username) << 17;
3226: my $nameseed=numval($username) << 12;
3227: my $domainseed=unpack("%32C*",$domain) << 7;
3228: my $courseseed=unpack("%32C*",$courseid);
3229: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
3230: #uncommenting these lines can break things!
3231: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
3232: #&Apache::lonxml::debug("rndseed :$num:$symb");
3233: return $num;
3234: }
3235: }
3236:
3237: sub ireceipt {
3238: my ($funame,$fudom,$fucourseid,$fusymb)=@_;
3239: my $cuname=unpack("%32C*",$funame);
3240: my $cudom=unpack("%32C*",$fudom);
3241: my $cucourseid=unpack("%32C*",$fucourseid);
3242: my $cusymb=unpack("%32C*",$fusymb);
3243: my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
3244: return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
3245: ($cunique%$cuname+
3246: $cunique%$cudom+
3247: $cusymb%$cuname+
3248: $cusymb%$cudom+
3249: $cucourseid%$cuname+
3250: $cucourseid%$cudom);
3251: }
3252:
3253: sub receipt {
3254: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
3255: return &ireceipt($name,$domain,$courseid,$symb);
3256: }
3257:
3258: # ------------------------------------------------------------ Serves up a file
3259: # returns either the contents of the file or a -1
3260: sub getfile {
3261: my $file=shift;
3262: if ($file=~/^\/*uploaded\//) { # user file
3263: my $ua=new LWP::UserAgent;
3264: my $request=new HTTP::Request('GET',&tokenwrapper($file));
3265: my $response=$ua->request($request);
3266: if ($response->is_success()) {
3267: return $response->content;
3268: } else {
3269: return -1;
3270: }
3271: } else { # normal file from res space
3272: &repcopy($file);
3273: if (! -e $file ) { return -1; };
3274: my $fh=Apache::File->new($file);
3275: my $a='';
3276: while (<$fh>) { $a .=$_; }
3277: return $a;
3278: }
3279: }
3280:
3281: sub filelocation {
3282: my ($dir,$file) = @_;
3283: my $location;
3284: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
3285: if ($file=~m:^/~:) { # is a contruction space reference
3286: $location = $file;
3287: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
3288: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
3289: $location=$file;
3290: } else {
3291: $file=~s/^$perlvar{'lonDocRoot'}//;
3292: $file=~s:^/*res::;
3293: if ( !( $file =~ m:^/:) ) {
3294: $location = $dir. '/'.$file;
3295: } else {
3296: $location = '/home/httpd/html/res'.$file;
3297: }
3298: }
3299: $location=~s://+:/:g; # remove duplicate /
3300: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
3301: return $location;
3302: }
3303:
3304: sub hreflocation {
3305: my ($dir,$file)=@_;
3306: unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
3307: my $finalpath=filelocation($dir,$file);
3308: $finalpath=~s/^\/home\/httpd\/html//;
3309: $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
3310: return $finalpath;
3311: } else {
3312: return $file;
3313: }
3314: }
3315:
3316: # ------------------------------------------------------------- Declutters URLs
3317:
3318: sub declutter {
3319: my $thisfn=shift;
3320: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
3321: $thisfn=~s/^\///;
3322: $thisfn=~s/^res\///;
3323: $thisfn=~s/\?.+$//;
3324: return $thisfn;
3325: }
3326:
3327: # ------------------------------------------------------------- Clutter up URLs
3328:
3329: sub clutter {
3330: my $thisfn='/'.&declutter(shift);
3331: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) {
3332: $thisfn='/res'.$thisfn;
3333: }
3334: return $thisfn;
3335: }
3336:
3337: # -------------------------------------------------------- Escape Special Chars
3338:
3339: sub escape {
3340: my $str=shift;
3341: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
3342: return $str;
3343: }
3344:
3345: # ----------------------------------------------------- Un-Escape Special Chars
3346:
3347: sub unescape {
3348: my $str=shift;
3349: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3350: return $str;
3351: }
3352:
3353: # ================================================================ Main Program
3354:
3355: sub goodbye {
3356: &logthis("Starting Shut down");
3357: &flushcourselogs();
3358: &logthis("Shutting down");
3359: }
3360:
3361: BEGIN {
3362: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
3363: unless ($readit) {
3364: {
3365: my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
3366:
3367: while (my $configline=<$config>) {
3368: if ($configline =~ /^[^\#]*PerlSetVar/) {
3369: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
3370: chomp($varvalue);
3371: $perlvar{$varname}=$varvalue;
3372: }
3373: }
3374: }
3375: {
3376: my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
3377:
3378: while (my $configline=<$config>) {
3379: if ($configline =~ /^[^\#]*PerlSetVar/) {
3380: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
3381: chomp($varvalue);
3382: $perlvar{$varname}=$varvalue;
3383: }
3384: }
3385: }
3386:
3387: # ------------------------------------------------------------- Read hosts file
3388: {
3389: my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
3390:
3391: while (my $configline=<$config>) {
3392: chomp($configline);
3393: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
3394: if ($id && $domain && $role && $name && $ip) {
3395: $hostname{$id}=$name;
3396: $hostdom{$id}=$domain;
3397: $hostip{$id}=$ip;
3398: if ($domdescr) { $domaindescription{$domain}=$domdescr; }
3399: if ($role eq 'library') { $libserv{$id}=$name; }
3400: } else {
3401: if ($configline) {
3402: &logthis("Skipping hosts.tab line -$configline-");
3403: }
3404: }
3405: }
3406: }
3407:
3408: # ------------------------------------------------------ Read spare server file
3409: {
3410: my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
3411:
3412: while (my $configline=<$config>) {
3413: chomp($configline);
3414: if ($configline) {
3415: $spareid{$configline}=1;
3416: }
3417: }
3418: }
3419: # ------------------------------------------------------------ Read permissions
3420: {
3421: my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
3422:
3423: while (my $configline=<$config>) {
3424: chomp($configline);
3425: if ($configline) {
3426: my ($role,$perm)=split(/ /,$configline);
3427: if ($perm ne '') { $pr{$role}=$perm; }
3428: }
3429: }
3430: }
3431:
3432: # -------------------------------------------- Read plain texts for permissions
3433: {
3434: my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
3435:
3436: while (my $configline=<$config>) {
3437: chomp($configline);
3438: if ($configline) {
3439: my ($short,$plain)=split(/:/,$configline);
3440: if ($plain ne '') { $prp{$short}=$plain; }
3441: }
3442: }
3443: }
3444:
3445: # ---------------------------------------------------------- Read package table
3446: {
3447: my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
3448:
3449: while (my $configline=<$config>) {
3450: chomp($configline);
3451: my ($short,$plain)=split(/:/,$configline);
3452: my ($pack,$name)=split(/\&/,$short);
3453: if ($plain ne '') {
3454: $packagetab{$pack.'&'.$name.'&name'}=$name;
3455: $packagetab{$short}=$plain;
3456: }
3457: }
3458: }
3459:
3460: %metacache=();
3461:
3462: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
3463: $dumpcount=0;
3464:
3465: &logtouch();
3466: &logthis('<font color=yellow>INFO: Read configuration</font>');
3467: $readit=1;
3468: }
3469: }
3470:
3471: 1;
3472: __END__
3473:
3474: =pod
3475:
3476: =head1 NAME
3477:
3478: Apache::lonnet - Subroutines to ask questions about things in the network.
3479:
3480: =head1 SYNOPSIS
3481:
3482: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
3483:
3484: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
3485:
3486: Common parameters:
3487:
3488: =over 4
3489:
3490: =item *
3491:
3492: $uname : an internal username (if $cname expecting a course Id specifically)
3493:
3494: =item *
3495:
3496: $udom : a domain (if $cdom expecting a course's domain specifically)
3497:
3498: =item *
3499:
3500: $symb : a resource instance identifier
3501:
3502: =item *
3503:
3504: $namespace : the name of a .db file that contains the data needed or
3505: being set.
3506:
3507: =back
3508:
3509: =head1 INTRODUCTION
3510:
3511: This module provides subroutines which interact with the
3512: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about
3513: - classes
3514: - users
3515: - resources
3516:
3517: For many of these objects you can also use this to store data about
3518: them or modify them in various ways.
3519:
3520: This is part of the LearningOnline Network with CAPA project
3521: described at http://www.lon-capa.org.
3522:
3523: =head1 RETURN MESSAGES
3524:
3525: =over 4
3526:
3527: =item *
3528:
3529: con_lost : unable to contact remote host
3530:
3531: =item *
3532:
3533: con_delayed : unable to contact remote host, message will be delivered
3534: when the connection is brought back up
3535:
3536: =item *
3537:
3538: con_failed : unable to contact remote host and unable to save message
3539: for later delivery
3540:
3541: =item *
3542:
3543: error: : an error a occured, a description of the error follows the :
3544:
3545: =item *
3546:
3547: no_such_host : unable to fund a host associated with the user/domain
3548: that was requested
3549:
3550: =back
3551:
3552: =head1 PUBLIC SUBROUTINES
3553:
3554: =head2 Session Environment Functions
3555:
3556: =over 4
3557:
3558: =item *
3559:
3560: appenv(%hash) : the value of %hash is written to the user envirnoment
3561: file, and will be restored for each access this user makes during this
3562: session, also modifies the %ENV for the current process
3563:
3564: =item *
3565:
3566: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
3567:
3568: =back
3569:
3570: =head2 User Information
3571:
3572: =over 4
3573:
3574: =item *
3575:
3576: queryauthenticate($uname,$udom) : try to determine user's current
3577: authentication scheme
3578:
3579: =item *
3580:
3581: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
3582: servers (first use the current one), $upass should be the users password
3583:
3584: =item *
3585:
3586: homeserver($uname,$udom) : find the server which has the user's
3587: directory and files (there must be only one), this caches the answer,
3588: and also caches if there is a borken connection.
3589:
3590: =item *
3591:
3592: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
3593: unique resource in a domain, there must be only 1 ID per username, and
3594: only 1 username per ID in a specific domain) (returns hash:
3595: id=>name,id=>name)
3596:
3597: =item *
3598:
3599: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
3600: name=>id,name=>id)
3601:
3602: =item *
3603:
3604: idput($udom,%ids) : store away a list of names and associated IDs
3605:
3606: =item *
3607:
3608: rolesinit($udom,$username,$authhost) : get user privileges
3609:
3610: =item *
3611:
3612: usection($udom,$uname,$cname) : finds the section of student in the
3613: course $cname, return section name/number or '' for "not in course"
3614: and '-1' for "no section"
3615:
3616: =item *
3617:
3618: userenvironment($udom,$uname,@what) : gets the values of the keys
3619: passed in @what from the requested user's environment, returns a hash
3620:
3621: =back
3622:
3623: =head2 User Roles
3624:
3625: =over 4
3626:
3627: =item *
3628:
3629: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
3630: actions
3631: F: full access
3632: U,I,K: authentication modes (cxx only)
3633: '': forbidden
3634: 1: user needs to choose course
3635: 2: browse allowed
3636:
3637: =item *
3638:
3639: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
3640: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
3641: and course level
3642:
3643: =item *
3644:
3645: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
3646: explanation of a user role term
3647:
3648: =back
3649:
3650: =head2 User Modification
3651:
3652: =over 4
3653:
3654: =item *
3655:
3656: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
3657: user for the level given by URL. Optional start and end dates (leave empty
3658: string or zero for "no date")
3659:
3660: =item *
3661:
3662: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
3663: change a users, password, possible return values are: ok,
3664: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
3665: refused
3666:
3667: =item *
3668:
3669: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
3670:
3671: =item *
3672:
3673: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
3674: modify user
3675:
3676: =item *
3677:
3678: modifystudent
3679:
3680: modify a students enrollment and identification information.
3681: The course id is resolved based on the current users environment.
3682: This means the envoking user must be a course coordinator or otherwise
3683: associated with a course.
3684:
3685: This call is essentially a wrapper for lonnet::modifyuser and
3686: lonnet::modify_student_enrollment
3687:
3688: Inputs:
3689:
3690: =over 4
3691:
3692: =item B<$udom> Students loncapa domain
3693:
3694: =item B<$uname> Students loncapa login name
3695:
3696: =item B<$uid> Students id/student number
3697:
3698: =item B<$umode> Students authentication mode
3699:
3700: =item B<$upass> Students password
3701:
3702: =item B<$first> Students first name
3703:
3704: =item B<$middle> Students middle name
3705:
3706: =item B<$last> Students last name
3707:
3708: =item B<$gene> Students generation
3709:
3710: =item B<$usec> Students section in course
3711:
3712: =item B<$end> Unix time of the roles expiration
3713:
3714: =item B<$start> Unix time of the roles start date
3715:
3716: =item B<$forceid> If defined, allow $uid to be changed
3717:
3718: =item B<$desiredhome> server to use as home server for student
3719:
3720: =back
3721:
3722: =item *
3723:
3724: modify_student_enrollment
3725:
3726: Change a students enrollment status in a class. The environment variable
3727: 'role.request.course' must be defined for this function to proceed.
3728:
3729: Inputs:
3730:
3731: =over 4
3732:
3733: =item $udom, students domain
3734:
3735: =item $uname, students name
3736:
3737: =item $uid, students user id
3738:
3739: =item $first, students first name
3740:
3741: =item $middle
3742:
3743: =item $last
3744:
3745: =item $gene
3746:
3747: =item $usec
3748:
3749: =item $end
3750:
3751: =item $start
3752:
3753: =back
3754:
3755:
3756: =item *
3757:
3758: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
3759: custom role; give a custom role to a user for the level given by URL. Specify
3760: name and domain of role author, and role name
3761:
3762: =item *
3763:
3764: revokerole($udom,$uname,$url,$role) : revoke a role for url
3765:
3766: =item *
3767:
3768: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
3769:
3770: =back
3771:
3772: =head2 Course Infomation
3773:
3774: =over 4
3775:
3776: =item *
3777:
3778: coursedescription($courseid) : course description
3779:
3780: =item *
3781:
3782: courseresdata($coursenum,$coursedomain,@which) : request for current
3783: parameter setting for a specific course, @what should be a list of
3784: parameters to ask about. This routine caches answers for 5 minutes.
3785:
3786: =back
3787:
3788: =head2 Course Modification
3789:
3790: =over 4
3791:
3792: =item *
3793:
3794: writecoursepref($courseid,%prefs) : write preferences (environment
3795: database) for a course
3796:
3797: =item *
3798:
3799: createcourse($udom,$description,$url) : make/modify course
3800:
3801: =back
3802:
3803: =head2 Resource Subroutines
3804:
3805: =over 4
3806:
3807: =item *
3808:
3809: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
3810:
3811: =item *
3812:
3813: repcopy($filename) : subscribes to the requested file, and attempts to
3814: replicate from the owning library server, Might return
3815: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
3816: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
3817: resource. Expects the local filesystem pathname
3818: (/home/httpd/html/res/....)
3819:
3820: =back
3821:
3822: =head2 Resource Information
3823:
3824: =over 4
3825:
3826: =item *
3827:
3828: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
3829: a vairety of different possible values, $varname should be a request
3830: string, and the other parameters can be used to specify who and what
3831: one is asking about.
3832:
3833: Possible values for $varname are environment.lastname (or other item
3834: from the envirnment hash), user.name (or someother aspect about the
3835: user), resource.0.maxtries (or some other part and parameter of a
3836: resource)
3837:
3838: =item *
3839:
3840: directcondval($number) : get current value of a condition; reads from a state
3841: string
3842:
3843: =item *
3844:
3845: condval($condidx) : value of condition index based on state
3846:
3847: =item *
3848:
3849: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
3850: resource's metadata, $what should be either a specific key, or either
3851: 'keys' (to get a list of possible keys) or 'packages' to get a list of
3852: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
3853:
3854: this function automatically caches all requests
3855:
3856: =item *
3857:
3858: metadata_query($query,$custom,$customshow) : make a metadata query against the
3859: network of library servers; returns file handle of where SQL and regex results
3860: will be stored for query
3861:
3862: =item *
3863:
3864: symbread($filename) : return symbolic list entry (filename argument optional);
3865: returns the data handle
3866:
3867: =item *
3868:
3869: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
3870: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
3871: failure, user must be in a course, as it assumes the existance of the
3872: course initi hash, and uses $ENV('request.course.id'}
3873:
3874:
3875: =item *
3876:
3877: symbclean($symb) : removes versions numbers from a symb, returns the
3878: cleaned symb
3879:
3880: =item *
3881:
3882: is_on_map($uri) : checks if the $uri is somewhere on the current
3883: course map, user must be in a course for it to work.
3884:
3885: =item *
3886:
3887: numval($salt) : return random seed value (addend for rndseed)
3888:
3889: =item *
3890:
3891: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
3892: a random seed, all arguments are optional, if they aren't sent it uses the
3893: environment to derive them. Note: if symb isn't sent and it can't get one
3894: from &symbread it will use the current time as its return value
3895:
3896: =item *
3897:
3898: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
3899: unfakeable, receipt
3900:
3901: =item *
3902:
3903: receipt() : API to ireceipt working off of ENV values; given out to users
3904:
3905: =item *
3906:
3907: countacc($url) : count the number of accesses to a given URL
3908:
3909: =item *
3910:
3911: 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
3912:
3913: =item *
3914:
3915: 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)
3916:
3917: =item *
3918:
3919: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
3920:
3921: =item *
3922:
3923: devalidate($symb) : devalidate temporary spreadsheet calculations,
3924: forcing spreadsheet to reevaluate the resource scores next time.
3925:
3926: =back
3927:
3928: =head2 Storing/Retreiving Data
3929:
3930: =over 4
3931:
3932: =item *
3933:
3934: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
3935: for this url; hashref needs to be given and should be a \%hashname; the
3936: remaining args aren't required and if they aren't passed or are '' they will
3937: be derived from the ENV
3938:
3939: =item *
3940:
3941: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
3942: uses critical subroutine
3943:
3944: =item *
3945:
3946: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
3947: all args are optional
3948:
3949: =item *
3950:
3951: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
3952: works very similar to store/cstore, but all data is stored in a
3953: temporary location and can be reset using tmpreset, $storehash should
3954: be a hash reference, returns nothing on success
3955:
3956: =item *
3957:
3958: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
3959: similar to restore, but all data is stored in a temporary location and
3960: can be reset using tmpreset. Returns a hash of values on success,
3961: error string otherwise.
3962:
3963: =item *
3964:
3965: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
3966: deltes all keys for $symb form the temporary storage hash.
3967:
3968: =item *
3969:
3970: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
3971: reference filled in from namesp ($udom and $uname are optional)
3972:
3973: =item *
3974:
3975: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
3976: namesp ($udom and $uname are optional)
3977:
3978: =item *
3979:
3980: dump($namespace,$udom,$uname,$regexp) :
3981: dumps the complete (or key matching regexp) namespace into a hash
3982: ($udom, $uname and $regexp are optional)
3983:
3984: =item *
3985:
3986: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
3987: ($udom and $uname are optional)
3988:
3989: =item *
3990:
3991: cput($namespace,$storehash,$udom,$uname) : critical put
3992: ($udom and $uname are optional)
3993:
3994: =item *
3995:
3996: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
3997: reference filled in from namesp (encrypts the return communication)
3998: ($udom and $uname are optional)
3999:
4000: =item *
4001:
4002: log($udom,$name,$home,$message) : write to permanent log for user; use
4003: critical subroutine
4004:
4005: =back
4006:
4007: =head2 Network Status Functions
4008:
4009: =over 4
4010:
4011: =item *
4012:
4013: dirlist($uri) : return directory list based on URI
4014:
4015: =item *
4016:
4017: spareserver() : find server with least workload from spare.tab
4018:
4019: =back
4020:
4021: =head2 Apache Request
4022:
4023: =over 4
4024:
4025: =item *
4026:
4027: ssi($url,%hash) : server side include, does a complete request cycle on url to
4028: localhost, posts hash
4029:
4030: =back
4031:
4032: =head2 Data to String to Data
4033:
4034: =over 4
4035:
4036: =item *
4037:
4038: hash2str(%hash) : convert a hash into a string complete with escaping and '='
4039: and '&' separators, supports elements that are arrayrefs and hashrefs
4040:
4041: =item *
4042:
4043: hashref2str($hashref) : convert a hashref into a string complete with
4044: escaping and '=' and '&' separators, supports elements that are
4045: arrayrefs and hashrefs
4046:
4047: =item *
4048:
4049: arrayref2str($arrayref) : convert an arrayref into a string complete
4050: with escaping and '&' separators, supports elements that are arrayrefs
4051: and hashrefs
4052:
4053: =item *
4054:
4055: str2hash($string) : convert string to hash using unescaping and
4056: splitting on '=' and '&', supports elements that are arrayrefs and
4057: hashrefs
4058:
4059: =item *
4060:
4061: str2array($string) : convert string to hash using unescaping and
4062: splitting on '&', supports elements that are arrayrefs and hashrefs
4063:
4064: =back
4065:
4066: =head2 Logging Routines
4067:
4068: =over 4
4069:
4070: These routines allow one to make log messages in the lonnet.log and
4071: lonnet.perm logfiles.
4072:
4073: =item *
4074:
4075: logtouch() : make sure the logfile, lonnet.log, exists
4076:
4077: =item *
4078:
4079: logthis() : append message to the normal lonnet.log file, it gets
4080: preiodically rolled over and deleted.
4081:
4082: =item *
4083:
4084: logperm() : append a permanent message to lonnet.perm.log, this log
4085: file never gets deleted by any automated portion of the system, only
4086: messages of critical importance should go in here.
4087:
4088: =back
4089:
4090: =head2 General File Helper Routines
4091:
4092: =over 4
4093:
4094: =item *
4095:
4096: getfile($file) : returns the entire contents of a file or -1; it
4097: properly subscribes to and replicates the file if neccessary.
4098:
4099: =item *
4100:
4101: filelocation($dir,$file) : returns file system location of a file
4102: based on URI; meant to be "fairly clean" absolute reference, $dir is a
4103: directory that relative $file lookups are to looked in ($dir of /a/dir
4104: and a file of ../bob will become /a/bob)
4105:
4106: =item *
4107:
4108: hreflocation($dir,$file) : returns file system location or a URL; same as
4109: filelocation except for hrefs
4110:
4111: =item *
4112:
4113: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
4114:
4115: =back
4116:
4117: =head2 HTTP Helper Routines
4118:
4119: =over 4
4120:
4121: =item *
4122:
4123: escape() : unpack non-word characters into CGI-compatible hex codes
4124:
4125: =item *
4126:
4127: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
4128:
4129: =back
4130:
4131: =head1 PRIVATE SUBROUTINES
4132:
4133: =head2 Underlying communication routines (Shouldn't call)
4134:
4135: =over 4
4136:
4137: =item *
4138:
4139: subreply() : tries to pass a message to lonc, returns con_lost if incapable
4140:
4141: =item *
4142:
4143: reply() : uses subreply to send a message to remote machine, logs all failures
4144:
4145: =item *
4146:
4147: critical() : passes a critical message to another server; if cannot
4148: get through then place message in connection buffer directory and
4149: returns con_delayed, if incapable of saving message, returns
4150: con_failed
4151:
4152: =item *
4153:
4154: reconlonc() : tries to reconnect lonc client processes.
4155:
4156: =back
4157:
4158: =head2 Resource Access Logging
4159:
4160: =over 4
4161:
4162: =item *
4163:
4164: flushcourselogs() : flush (save) buffer logs and access logs
4165:
4166: =item *
4167:
4168: courselog($what) : save message for course in hash
4169:
4170: =item *
4171:
4172: courseacclog($what) : save message for course using &courselog(). Perform
4173: special processing for specific resource types (problems, exams, quizzes, etc).
4174:
4175: =item *
4176:
4177: goodbye() : flush course logs and log shutting down; it is called in srm.conf
4178: as a PerlChildExitHandler
4179:
4180: =back
4181:
4182: =head2 Other
4183:
4184: =over 4
4185:
4186: =item *
4187:
4188: symblist($mapname,%newhash) : update symbolic storage links
4189:
4190: =back
4191:
4192: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>