1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.201 2002/02/14 20:44:26 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: # 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 %hostip %spareid %hostdom
81: %libserv %pr %prp %metacache %packagetab
82: %courselogs %accesshash $processmarker $dumpcount
83: %coursedombuf %coursehombuf %courseresdatacache);
84: use IO::Socket;
85: use GDBM_File;
86: use Apache::Constants qw(:common :http);
87: use HTML::TokeParser;
88: use Fcntl qw(:flock);
89: my $readit;
90:
91: # --------------------------------------------------------------------- Logging
92:
93: sub logtouch {
94: my $execdir=$perlvar{'lonDaemons'};
95: unless (-e "$execdir/logs/lonnet.log") {
96: my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
97: close $fh;
98: }
99: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
100: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
101: }
102:
103: sub logthis {
104: my $message=shift;
105: my $execdir=$perlvar{'lonDaemons'};
106: my $now=time;
107: my $local=localtime($now);
108: my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
109: print $fh "$local ($$): $message\n";
110: return 1;
111: }
112:
113: sub logperm {
114: my $message=shift;
115: my $execdir=$perlvar{'lonDaemons'};
116: my $now=time;
117: my $local=localtime($now);
118: my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
119: print $fh "$now:$message:$local\n";
120: return 1;
121: }
122:
123: # -------------------------------------------------- Non-critical communication
124: sub subreply {
125: my ($cmd,$server)=@_;
126: my $peerfile="$perlvar{'lonSockDir'}/$server";
127: my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
128: Type => SOCK_STREAM,
129: Timeout => 10)
130: or return "con_lost";
131: print $client "$cmd\n";
132: my $answer=<$client>;
133: if (!$answer) { $answer="con_lost"; }
134: chomp($answer);
135: return $answer;
136: }
137:
138: sub reply {
139: my ($cmd,$server)=@_;
140: my $answer=subreply($cmd,$server);
141: if ($answer eq 'con_lost') { $answer=subreply($cmd,$server); }
142: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
143: &logthis("<font color=blue>WARNING:".
144: " $cmd to $server returned $answer</font>");
145: }
146: return $answer;
147: }
148:
149: # ----------------------------------------------------------- Send USR1 to lonc
150:
151: sub reconlonc {
152: my $peerfile=shift;
153: &logthis("Trying to reconnect for $peerfile");
154: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
155: if (my $fh=Apache::File->new("$loncfile")) {
156: my $loncpid=<$fh>;
157: chomp($loncpid);
158: if (kill 0 => $loncpid) {
159: &logthis("lonc at pid $loncpid responding, sending USR1");
160: kill USR1 => $loncpid;
161: sleep 1;
162: if (-e "$peerfile") { return; }
163: &logthis("$peerfile still not there, give it another try");
164: sleep 5;
165: if (-e "$peerfile") { return; }
166: &logthis(
167: "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
168: } else {
169: &logthis(
170: "<font color=blue>WARNING:".
171: " lonc at pid $loncpid not responding, giving up</font>");
172: }
173: } else {
174: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
175: }
176: }
177:
178: # ------------------------------------------------------ Critical communication
179:
180: sub critical {
181: my ($cmd,$server)=@_;
182: unless ($hostname{$server}) {
183: &logthis("<font color=blue>WARNING:".
184: " Critical message to unknown server ($server)</font>");
185: return 'no_such_host';
186: }
187: my $answer=reply($cmd,$server);
188: if ($answer eq 'con_lost') {
189: my $pingreply=reply('ping',$server);
190: &reconlonc("$perlvar{'lonSockDir'}/$server");
191: my $pongreply=reply('pong',$server);
192: &logthis("Ping/Pong for $server: $pingreply/$pongreply");
193: $answer=reply($cmd,$server);
194: if ($answer eq 'con_lost') {
195: my $now=time;
196: my $middlename=$cmd;
197: $middlename=substr($middlename,0,16);
198: $middlename=~s/\W//g;
199: my $dfilename=
200: "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
201: {
202: my $dfh;
203: if ($dfh=Apache::File->new(">$dfilename")) {
204: print $dfh "$cmd\n";
205: }
206: }
207: sleep 2;
208: my $wcmd='';
209: {
210: my $dfh;
211: if ($dfh=Apache::File->new("$dfilename")) {
212: $wcmd=<$dfh>;
213: }
214: }
215: chomp($wcmd);
216: if ($wcmd eq $cmd) {
217: &logthis("<font color=blue>WARNING: ".
218: "Connection buffer $dfilename: $cmd</font>");
219: &logperm("D:$server:$cmd");
220: return 'con_delayed';
221: } else {
222: &logthis("<font color=red>CRITICAL:"
223: ." Critical connection failed: $server $cmd</font>");
224: &logperm("F:$server:$cmd");
225: return 'con_failed';
226: }
227: }
228: }
229: return $answer;
230: }
231:
232: # ---------------------------------------------------------- Append Environment
233:
234: sub appenv {
235: my %newenv=@_;
236: foreach (keys %newenv) {
237: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
238: &logthis("<font color=blue>WARNING: ".
239: "Attempt to modify environment ".$_." to ".$newenv{$_}
240: .'</font>');
241: delete($newenv{$_});
242: } else {
243: $ENV{$_}=$newenv{$_};
244: }
245: }
246:
247: my $lockfh;
248: unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
249: return 'error: '.$!;
250: }
251: unless (flock($lockfh,LOCK_EX)) {
252: &logthis("<font color=blue>WARNING: ".
253: 'Could not obtain exclusive lock in appenv: '.$!);
254: $lockfh->close();
255: return 'error: '.$!;
256: }
257:
258: my @oldenv;
259: {
260: my $fh;
261: unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
262: return 'error: '.$!;
263: }
264: @oldenv=<$fh>;
265: $fh->close();
266: }
267: for (my $i=0; $i<=$#oldenv; $i++) {
268: chomp($oldenv[$i]);
269: if ($oldenv[$i] ne '') {
270: my ($name,$value)=split(/=/,$oldenv[$i]);
271: unless (defined($newenv{$name})) {
272: $newenv{$name}=$value;
273: }
274: }
275: }
276: {
277: my $fh;
278: unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
279: return 'error';
280: }
281: my $newname;
282: foreach $newname (keys %newenv) {
283: print $fh "$newname=$newenv{$newname}\n";
284: }
285: $fh->close();
286: }
287:
288: $lockfh->close();
289: return 'ok';
290: }
291: # ----------------------------------------------------- Delete from Environment
292:
293: sub delenv {
294: my $delthis=shift;
295: my %newenv=();
296: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
297: &logthis("<font color=blue>WARNING: ".
298: "Attempt to delete from environment ".$delthis);
299: return 'error';
300: }
301: my @oldenv;
302: {
303: my $fh;
304: unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
305: return 'error';
306: }
307: unless (flock($fh,LOCK_SH)) {
308: &logthis("<font color=blue>WARNING: ".
309: 'Could not obtain shared lock in delenv: '.$!);
310: $fh->close();
311: return 'error: '.$!;
312: }
313: @oldenv=<$fh>;
314: $fh->close();
315: }
316: {
317: my $fh;
318: unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
319: return 'error';
320: }
321: unless (flock($fh,LOCK_EX)) {
322: &logthis("<font color=blue>WARNING: ".
323: 'Could not obtain exclusive lock in delenv: '.$!);
324: $fh->close();
325: return 'error: '.$!;
326: }
327: foreach (@oldenv) {
328: unless ($_=~/^$delthis/) { print $fh $_; }
329: }
330: $fh->close();
331: }
332: return 'ok';
333: }
334:
335: # ------------------------------ Find server with least workload from spare.tab
336:
337: sub spareserver {
338: my $tryserver;
339: my $spareserver='';
340: my $lowestserver=100;
341: foreach $tryserver (keys %spareid) {
342: my $answer=reply('load',$tryserver);
343: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
344: $spareserver="http://$hostname{$tryserver}";
345: $lowestserver=$answer;
346: }
347: }
348: return $spareserver;
349: }
350:
351: # ----------------------- Try to determine user's current authentication scheme
352:
353: sub queryauthenticate {
354: my ($uname,$udom)=@_;
355: if (($perlvar{'lonRole'} eq 'library') &&
356: ($udom eq $perlvar{'lonDefDomain'})) {
357: my $answer=reply("encrypt:currentauth:$udom:$uname",
358: $perlvar{'lonHostID'});
359: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
360: if (length($answer)) {
361: return $answer;
362: }
363: else {
364: &logthis("User $uname at $udom lacks an authentication mechanism");
365: return 'no_host';
366: }
367: }
368: }
369:
370: my $tryserver;
371: foreach $tryserver (keys %libserv) {
372: if ($hostdom{$tryserver} eq $udom) {
373: my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
374: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
375: if (length($answer)) {
376: return $answer;
377: }
378: else {
379: &logthis("User $uname at $udom lacks an authentication mechanism");
380: return 'no_host';
381: }
382: }
383: }
384: }
385: &logthis("User $uname at $udom lacks an authentication mechanism");
386: return 'no_host';
387: }
388:
389: # --------- Try to authenticate user from domain's lib servers (first this one)
390:
391: sub authenticate {
392: my ($uname,$upass,$udom)=@_;
393: $upass=escape($upass);
394: $uname=~s/\W//g;
395: if (($perlvar{'lonRole'} eq 'library') &&
396: ($udom eq $perlvar{'lonDefDomain'})) {
397: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
398: if ($answer =~ /authorized/) {
399: if ($answer eq 'authorized') {
400: &logthis("User $uname at $udom authorized by local server");
401: return $perlvar{'lonHostID'};
402: }
403: if ($answer eq 'non_authorized') {
404: &logthis("User $uname at $udom rejected by local server");
405: return 'no_host';
406: }
407: }
408: }
409:
410: my $tryserver;
411: foreach $tryserver (keys %libserv) {
412: if ($hostdom{$tryserver} eq $udom) {
413: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
414: if ($answer =~ /authorized/) {
415: if ($answer eq 'authorized') {
416: &logthis("User $uname at $udom authorized by $tryserver");
417: return $tryserver;
418: }
419: if ($answer eq 'non_authorized') {
420: &logthis("User $uname at $udom rejected by $tryserver");
421: return 'no_host';
422: }
423: }
424: }
425: }
426: &logthis("User $uname at $udom could not be authenticated");
427: return 'no_host';
428: }
429:
430: # ---------------------- Find the homebase for a user from domain's lib servers
431:
432: sub homeserver {
433: my ($uname,$udom)=@_;
434:
435: my $index="$uname:$udom";
436: if ($homecache{$index}) { return "$homecache{$index}"; }
437:
438: my $tryserver;
439: foreach $tryserver (keys %libserv) {
440: if ($hostdom{$tryserver} eq $udom) {
441: my $answer=reply("home:$udom:$uname",$tryserver);
442: if ($answer eq 'found') {
443: $homecache{$index}=$tryserver;
444: return $tryserver;
445: }
446: }
447: }
448: return 'no_host';
449: }
450:
451: # ------------------------------------- Find the usernames behind a list of IDs
452:
453: sub idget {
454: my ($udom,@ids)=@_;
455: my %returnhash=();
456:
457: my $tryserver;
458: foreach $tryserver (keys %libserv) {
459: if ($hostdom{$tryserver} eq $udom) {
460: my $idlist=join('&',@ids);
461: $idlist=~tr/A-Z/a-z/;
462: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
463: my @answer=();
464: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
465: @answer=split(/\&/,$reply);
466: } ;
467: my $i;
468: for ($i=0;$i<=$#ids;$i++) {
469: if ($answer[$i]) {
470: $returnhash{$ids[$i]}=$answer[$i];
471: }
472: }
473: }
474: }
475: return %returnhash;
476: }
477:
478: # ------------------------------------- Find the IDs behind a list of usernames
479:
480: sub idrget {
481: my ($udom,@unames)=@_;
482: my %returnhash=();
483: foreach (@unames) {
484: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
485: }
486: return %returnhash;
487: }
488:
489: # ------------------------------- Store away a list of names and associated IDs
490:
491: sub idput {
492: my ($udom,%ids)=@_;
493: my %servers=();
494: foreach (keys %ids) {
495: my $uhom=&homeserver($_,$udom);
496: if ($uhom ne 'no_host') {
497: my $id=&escape($ids{$_});
498: $id=~tr/A-Z/a-z/;
499: my $unam=&escape($_);
500: if ($servers{$uhom}) {
501: $servers{$uhom}.='&'.$id.'='.$unam;
502: } else {
503: $servers{$uhom}=$id.'='.$unam;
504: }
505: &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
506: }
507: }
508: foreach (keys %servers) {
509: &critical('idput:'.$udom.':'.$servers{$_},$_);
510: }
511: }
512:
513: # ------------------------------------- Find the section of student in a course
514:
515: sub usection {
516: my ($udom,$unam,$courseid)=@_;
517: $courseid=~s/\_/\//g;
518: $courseid=~s/^(\w)/\/$1/;
519: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
520: &homeserver($unam,$udom)))) {
521: my ($key,$value)=split(/\=/,$_);
522: $key=&unescape($key);
523: if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
524: my $section=$1;
525: if ($key eq $courseid.'_st') { $section=''; }
526: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
527: my $now=time;
528: my $notactive=0;
529: if ($start) {
530: if ($now<$start) { $notactive=1; }
531: }
532: if ($end) {
533: if ($now>$end) { $notactive=1; }
534: }
535: unless ($notactive) { return $section; }
536: }
537: }
538: return '-1';
539: }
540:
541: # ------------------------------------- Read an entry from a user's environment
542:
543: sub userenvironment {
544: my ($udom,$unam,@what)=@_;
545: my %returnhash=();
546: my @answer=split(/\&/,
547: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
548: &homeserver($unam,$udom)));
549: my $i;
550: for ($i=0;$i<=$#what;$i++) {
551: $returnhash{$what[$i]}=&unescape($answer[$i]);
552: }
553: return %returnhash;
554: }
555:
556: # ----------------------------- Subscribe to a resource, return URL if possible
557:
558: sub subscribe {
559: my $fname=shift;
560: my $author=$fname;
561: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
562: my ($udom,$uname)=split(/\//,$author);
563: my $home=homeserver($uname,$udom);
564: if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) {
565: return 'not_found';
566: }
567: my $answer=reply("sub:$fname",$home);
568: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
569: $answer.=' by '.$home;
570: }
571: return $answer;
572: }
573:
574: # -------------------------------------------------------------- Replicate file
575:
576: sub repcopy {
577: my $filename=shift;
578: $filename=~s/\/+/\//g;
579: my $transname="$filename.in.transfer";
580: if ((-e $filename) || (-e $transname)) { return OK; }
581: my $remoteurl=subscribe($filename);
582: if ($remoteurl =~ /^con_lost by/) {
583: &logthis("Subscribe returned $remoteurl: $filename");
584: return HTTP_SERVICE_UNAVAILABLE;
585: } elsif ($remoteurl eq 'not_found') {
586: &logthis("Subscribe returned not_found: $filename");
587: return HTTP_NOT_FOUND;
588: } elsif ($remoteurl =~ /^rejected by/) {
589: &logthis("Subscribe returned $remoteurl: $filename");
590: return FORBIDDEN;
591: } elsif ($remoteurl eq 'directory') {
592: return OK;
593: } else {
594: my @parts=split(/\//,$filename);
595: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
596: if ($path ne "$perlvar{'lonDocRoot'}/res") {
597: &logthis("Malconfiguration for replication: $filename");
598: return HTTP_BAD_REQUEST;
599: }
600: my $count;
601: for ($count=5;$count<$#parts;$count++) {
602: $path.="/$parts[$count]";
603: if ((-e $path)!=1) {
604: mkdir($path,0777);
605: }
606: }
607: my $ua=new LWP::UserAgent;
608: my $request=new HTTP::Request('GET',"$remoteurl");
609: my $response=$ua->request($request,$transname);
610: if ($response->is_error()) {
611: unlink($transname);
612: my $message=$response->status_line;
613: &logthis("<font color=blue>WARNING:"
614: ." LWP get: $message: $filename</font>");
615: return HTTP_SERVICE_UNAVAILABLE;
616: } else {
617: if ($remoteurl!~/\.meta$/) {
618: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
619: my $mresponse=$ua->request($mrequest,$filename.'.meta');
620: if ($mresponse->is_error()) {
621: unlink($filename.'.meta');
622: &logthis(
623: "<font color=yellow>INFO: No metadata: $filename</font>");
624: }
625: }
626: rename($transname,$filename);
627: return OK;
628: }
629: }
630: }
631:
632: # --------------------------------------------------------- Server Side Include
633:
634: sub ssi {
635:
636: my ($fn,%form)=@_;
637:
638: my $ua=new LWP::UserAgent;
639:
640: my $request;
641:
642: if (%form) {
643: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
644: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
645: } else {
646: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
647: }
648:
649: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
650: my $response=$ua->request($request);
651:
652: return $response->content;
653: }
654:
655: # ------------------------------------------------------------------------- Log
656:
657: sub log {
658: my ($dom,$nam,$hom,$what)=@_;
659: return critical("log:$dom:$nam:$what",$hom);
660: }
661:
662: # ------------------------------------------------------------------ Course Log
663:
664: sub flushcourselogs {
665: &logthis('Flushing course log buffers');
666: foreach (keys %courselogs) {
667: my $crsid=$_;
668: if (&reply('log:'.$coursedombuf{$crsid}.':'.
669: &escape($courselogs{$crsid}),
670: $coursehombuf{$crsid}) eq 'ok') {
671: delete $courselogs{$crsid};
672: } else {
673: &logthis('Failed to flush log buffer for '.$crsid);
674: if (length($courselogs{$crsid})>40000) {
675: &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
676: " exceeded maximum size, deleting.</font>");
677: delete $courselogs{$crsid};
678: }
679: }
680: }
681: &logthis('Flushing access logs');
682: foreach (keys %accesshash) {
683: my $entry=$_;
684: $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
685: my %temphash=($entry => $accesshash{$entry});
686: if (&Apache::lonnet::put('resevaldata',\%temphash,$1,$2) eq 'ok') {
687: delete $accesshash{$entry};
688: }
689: }
690: $dumpcount++;
691: }
692:
693: sub courselog {
694: my $what=shift;
695: $what=time.':'.$what;
696: unless ($ENV{'request.course.id'}) { return ''; }
697: $coursedombuf{$ENV{'request.course.id'}}=
698: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
699: $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
700: $coursehombuf{$ENV{'request.course.id'}}=
701: $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
702: if (defined $courselogs{$ENV{'request.course.id'}}) {
703: $courselogs{$ENV{'request.course.id'}}.='&'.$what;
704: } else {
705: $courselogs{$ENV{'request.course.id'}}.=$what;
706: }
707: if (length($courselogs{$ENV{'request.course.id'}})>4048) {
708: &flushcourselogs();
709: }
710: }
711:
712: sub courseacclog {
713: my $fnsymb=shift;
714: unless ($ENV{'request.course.id'}) { return ''; }
715: my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
716: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
717: $what.=':POST';
718: foreach (keys %ENV) {
719: if ($_=~/^form\.(.*)/) {
720: $what.=':'.$1.'='.$ENV{$_};
721: }
722: }
723: }
724: &courselog($what);
725: }
726:
727: sub countacc {
728: my $url=&declutter(shift);
729: unless ($ENV{'request.course.id'}) { return ''; }
730: $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
731: my $key=$processmarker.'_'.$dumpcount.'___'.$url.'___count';
732: if (defined($accesshash{$key})) {
733: $accesshash{$key}++;
734: } else {
735: $accesshash{$key}=1;
736: }
737: }
738:
739: # ----------------------------------------------------------- Check out an item
740:
741: sub checkout {
742: my ($symb,$tuname,$tudom,$tcrsid)=@_;
743: my $now=time;
744: my $lonhost=$perlvar{'lonHostID'};
745: my $infostr=&escape(
746: $tuname.'&'.
747: $tudom.'&'.
748: $tcrsid.'&'.
749: $symb.'&'.
750: $now.'&'.$ENV{'REMOTE_ADDR'});
751: my $token=&reply('tmpput:'.$infostr,$lonhost);
752: if ($token=~/^error\:/) {
753: &logthis("<font color=blue>WARNING: ".
754: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
755: "</font>");
756: return '';
757: }
758:
759: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
760: $token=~tr/a-z/A-Z/;
761:
762: my %infohash=('resource.0.outtoken' => $token,
763: 'resource.0.checkouttime' => $now,
764: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
765:
766: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
767: return '';
768: } else {
769: &logthis("<font color=blue>WARNING: ".
770: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
771: "</font>");
772: }
773:
774: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
775: &escape('Checkout '.$infostr.' - '.
776: $token)) ne 'ok') {
777: return '';
778: } else {
779: &logthis("<font color=blue>WARNING: ".
780: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
781: "</font>");
782: }
783: return $token;
784: }
785:
786: # ------------------------------------------------------------ Check in an item
787:
788: sub checkin {
789: my $token=shift;
790: my $now=time;
791: my ($ta,$tb,$lonhost)=split(/\*/,$token);
792: $lonhost=~tr/A-Z/a-z/;
793: my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
794: $dtoken=~s/\W/\_/g;
795: my ($tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
796: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
797:
798: unless (($tuname) && ($tudom)) {
799: &logthis('Check in '.$token.' ('.$dtoken.') failed');
800: return '';
801: }
802:
803: unless (&allowed('mgr',$tcrsid)) {
804: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
805: $ENV{'user.name'}.' - '.$ENV{'user.domain'});
806: return '';
807: }
808:
809: my %infohash=('resource.0.intoken' => $token,
810: 'resource.0.checkintime' => $now,
811: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
812:
813: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
814: return '';
815: }
816:
817: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
818: &escape('Checkin - '.$token)) ne 'ok') {
819: return '';
820: }
821:
822: return ($symb,$tuname,$tudom,$tcrsid);
823: }
824:
825: # --------------------------------------------- Set Expire Date for Spreadsheet
826:
827: sub expirespread {
828: my ($uname,$udom,$stype,$usymb)=@_;
829: my $cid=$ENV{'request.course.id'};
830: if ($cid) {
831: my $now=time;
832: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
833: return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
834: $ENV{'course.'.$cid.'.num'}.
835: ':nohist_expirationdates:'.
836: &escape($key).'='.$now,
837: $ENV{'course.'.$cid.'.home'})
838: }
839: return 'ok';
840: }
841:
842: # ----------------------------------------------------- Devalidate Spreadsheets
843:
844: sub devalidate {
845: my $symb=shift;
846: my $cid=$ENV{'request.course.id'};
847: if ($cid) {
848: my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
849: my $status=
850: &del('nohist_calculatedsheet',
851: [$key.'studentcalc'],
852: $ENV{'course.'.$cid.'.domain'},
853: $ENV{'course.'.$cid.'.num'})
854: .' '.
855: &del('nohist_calculatedsheets_'.$cid,
856: [$key.'assesscalc:'.$symb]);
857: unless ($status eq 'ok ok') {
858: &logthis('Could not devalidate spreadsheet '.
859: $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
860: $symb.': '.$status);
861: }
862: }
863: }
864:
865: sub hash2str {
866: my (%hash)=@_;
867: my $result='';
868: foreach (keys %hash) { $result.=escape($_).'='.escape($hash{$_}).'&'; }
869: $result=~s/\&$//;
870: return $result;
871: }
872:
873: sub str2hash {
874: my ($string) = @_;
875: my %returnhash;
876: foreach (split(/\&/,$string)) {
877: my ($name,$value)=split(/\=/,$_);
878: $returnhash{&unescape($name)}=&unescape($value);
879: }
880: return %returnhash;
881: }
882:
883: # -------------------------------------------------------------------Temp Store
884:
885: sub tmpreset {
886: my ($symb,$namespace,$domain,$stuname) = @_;
887: if (!$symb) {
888: $symb=&symbread();
889: if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
890: }
891: $symb=escape($symb);
892:
893: if (!$namespace) { $namespace=$ENV{'request.state'}; }
894: $namespace=~s/\//\_/g;
895: $namespace=~s/\W//g;
896:
897: #FIXME needs to do something for /pub resources
898: if (!$domain) { $domain=$ENV{'user.domain'}; }
899: if (!$stuname) { $stuname=$ENV{'user.name'}; }
900: my $path=$perlvar{'lonDaemons'}.'/tmp';
901: my %hash;
902: if (tie(%hash,'GDBM_File',
903: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
904: &GDBM_WRCREAT,0640)) {
905: foreach my $key (keys %hash) {
906: if ($key=~ /:$symb/) {
907: delete($hash{$key});
908: }
909: }
910: }
911: }
912:
913: sub tmpstore {
914: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
915:
916: if (!$symb) {
917: $symb=&symbread();
918: if (!$symb) { $symb= $ENV{'request.url'}; }
919: }
920: $symb=escape($symb);
921:
922: if (!$namespace) {
923: # I don't think we would ever want to store this for a course.
924: # it seems this will only be used if we don't have a course.
925: #$namespace=$ENV{'request.course.id'};
926: #if (!$namespace) {
927: $namespace=$ENV{'request.state'};
928: #}
929: }
930: $namespace=~s/\//\_/g;
931: $namespace=~s/\W//g;
932: #FIXME needs to do something for /pub resources
933: if (!$domain) { $domain=$ENV{'user.domain'}; }
934: if (!$stuname) { $stuname=$ENV{'user.name'}; }
935: my $now=time;
936: my %hash;
937: my $path=$perlvar{'lonDaemons'}.'/tmp';
938: if (tie(%hash,'GDBM_File',
939: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
940: &GDBM_WRCREAT,0640)) {
941: $hash{"version:$symb"}++;
942: my $version=$hash{"version:$symb"};
943: my $allkeys='';
944: foreach my $key (keys(%$storehash)) {
945: $allkeys.=$key.':';
946: $hash{"$version:$symb:$key"}=$$storehash{$key};
947: }
948: $hash{"$version:$symb:timestamp"}=$now;
949: $allkeys.='timestamp';
950: $hash{"$version:keys:$symb"}=$allkeys;
951: if (untie(%hash)) {
952: return 'ok';
953: } else {
954: return "error:$!";
955: }
956: } else {
957: return "error:$!";
958: }
959: }
960:
961: # -----------------------------------------------------------------Temp Restore
962:
963: sub tmprestore {
964: my ($symb,$namespace,$domain,$stuname) = @_;
965:
966: if (!$symb) {
967: $symb=&symbread();
968: if (!$symb) { $symb= $ENV{'request.url'}; }
969: }
970: $symb=escape($symb);
971:
972: if (!$namespace) { $namespace=$ENV{'request.state'}; }
973: #FIXME needs to do something for /pub resources
974: if (!$domain) { $domain=$ENV{'user.domain'}; }
975: if (!$stuname) { $stuname=$ENV{'user.name'}; }
976:
977: my %returnhash;
978: $namespace=~s/\//\_/g;
979: $namespace=~s/\W//g;
980: my %hash;
981: my $path=$perlvar{'lonDaemons'}.'/tmp';
982: if (tie(%hash,'GDBM_File',
983: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
984: &GDBM_READER,0640)) {
985: my $version=$hash{"version:$symb"};
986: $returnhash{'version'}=$version;
987: my $scope;
988: for ($scope=1;$scope<=$version;$scope++) {
989: my $vkeys=$hash{"$scope:keys:$symb"};
990: my @keys=split(/:/,$vkeys);
991: my $key;
992: $returnhash{"$scope:keys"}=$vkeys;
993: foreach $key (@keys) {
994: $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
995: $returnhash{"$key"}=$hash{"$scope:$symb:$key"};
996: }
997: }
998: if (!(untie(%hash))) {
999: return "error:$!";
1000: }
1001: } else {
1002: return "error:$!";
1003: }
1004: return %returnhash;
1005: }
1006:
1007: # ----------------------------------------------------------------------- Store
1008:
1009: sub store {
1010: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1011: my $home='';
1012:
1013: if ($stuname) { $home=&homeserver($stuname,$domain); }
1014:
1015: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1016:
1017: &devalidate($symb);
1018:
1019: $symb=escape($symb);
1020: if (!$namespace) {
1021: unless ($namespace=$ENV{'request.course.id'}) {
1022: return '';
1023: }
1024: }
1025: if (!$domain) { $domain=$ENV{'user.domain'}; }
1026: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1027: if (!$home) { $home=$ENV{'user.home'}; }
1028: my $namevalue='';
1029: foreach (keys %$storehash) {
1030: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1031: }
1032: $namevalue=~s/\&$//;
1033: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1034: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1035: }
1036:
1037: # -------------------------------------------------------------- Critical Store
1038:
1039: sub cstore {
1040: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1041: my $home='';
1042:
1043: if ($stuname) { $home=&homeserver($stuname,$domain); }
1044:
1045: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1046:
1047: &devalidate($symb);
1048:
1049: $symb=escape($symb);
1050: if (!$namespace) {
1051: unless ($namespace=$ENV{'request.course.id'}) {
1052: return '';
1053: }
1054: }
1055: if (!$domain) { $domain=$ENV{'user.domain'}; }
1056: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1057: if (!$home) { $home=$ENV{'user.home'}; }
1058:
1059: my $namevalue='';
1060: foreach (keys %$storehash) {
1061: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1062: }
1063: $namevalue=~s/\&$//;
1064: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1065: return critical
1066: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1067: }
1068:
1069: # --------------------------------------------------------------------- Restore
1070:
1071: sub restore {
1072: my ($symb,$namespace,$domain,$stuname) = @_;
1073: my $home='';
1074:
1075: if ($stuname) { $home=&homeserver($stuname,$domain); }
1076:
1077: if (!$symb) {
1078: unless ($symb=escape(&symbread())) { return ''; }
1079: } else {
1080: $symb=&escape($symb);
1081: }
1082: if (!$namespace) {
1083: unless ($namespace=$ENV{'request.course.id'}) {
1084: return '';
1085: }
1086: }
1087: if (!$domain) { $domain=$ENV{'user.domain'}; }
1088: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1089: if (!$home) { $home=$ENV{'user.home'}; }
1090: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
1091:
1092: my %returnhash=();
1093: foreach (split(/\&/,$answer)) {
1094: my ($name,$value)=split(/\=/,$_);
1095: $returnhash{&unescape($name)}=&unescape($value);
1096: }
1097: my $version;
1098: for ($version=1;$version<=$returnhash{'version'};$version++) {
1099: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1100: $returnhash{$_}=$returnhash{$version.':'.$_};
1101: }
1102: }
1103: return %returnhash;
1104: }
1105:
1106: # ---------------------------------------------------------- Course Description
1107:
1108: sub coursedescription {
1109: my $courseid=shift;
1110: $courseid=~s/^\///;
1111: $courseid=~s/\_/\//g;
1112: my ($cdomain,$cnum)=split(/\//,$courseid);
1113: my $chome=&homeserver($cnum,$cdomain);
1114: if ($chome ne 'no_host') {
1115: my %returnhash=&dump('environment',$cdomain,$cnum);
1116: if (!exists($returnhash{'con_lost'})) {
1117: my $normalid=$cdomain.'_'.$cnum;
1118: my %envhash=();
1119: $returnhash{'home'}= $chome;
1120: $returnhash{'domain'} = $cdomain;
1121: $returnhash{'num'} = $cnum;
1122: while (my ($name,$value) = each %returnhash) {
1123: $envhash{'course.'.$normalid.'.'.$name}=$value;
1124: }
1125: $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
1126: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1127: $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1128: $envhash{'course.'.$normalid.'.last_cache'}=time;
1129: $envhash{'course.'.$normalid.'.home'}=$chome;
1130: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
1131: $envhash{'course.'.$normalid.'.num'}=$cnum;
1132: &appenv(%envhash);
1133: return %returnhash;
1134: }
1135: }
1136: return ();
1137: }
1138:
1139: # -------------------------------------------------------- Get user privileges
1140:
1141: sub rolesinit {
1142: my ($domain,$username,$authhost)=@_;
1143: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1144: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1145: my %allroles=();
1146: my %thesepriv=();
1147: my $now=time;
1148: my $userroles="user.login.time=$now\n";
1149: my $thesestr;
1150:
1151: if ($rolesdump ne '') {
1152: foreach (split(/&/,$rolesdump)) {
1153: if ($_!~/^rolesdef\&/) {
1154: my ($area,$role)=split(/=/,$_);
1155: $area=~s/\_\w\w$//;
1156: my ($trole,$tend,$tstart)=split(/_/,$role);
1157: $userroles.='user.role.'.$trole.'.'.$area.'='.
1158: $tstart.'.'.$tend."\n";
1159: if ($tend!=0) {
1160: if ($tend<$now) {
1161: $trole='';
1162: }
1163: }
1164: if ($tstart!=0) {
1165: if ($tstart>$now) {
1166: $trole='';
1167: }
1168: }
1169: if (($area ne '') && ($trole ne '')) {
1170: my $spec=$trole.'.'.$area;
1171: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
1172: if ($trole =~ /^cr\//) {
1173: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1174: my $homsvr=homeserver($rauthor,$rdomain);
1175: if ($hostname{$homsvr} ne '') {
1176: my $roledef=
1177: reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
1178: $homsvr);
1179: if (($roledef ne 'con_lost') && ($roledef ne '')) {
1180: my ($syspriv,$dompriv,$coursepriv)=
1181: split(/\_/,unescape($roledef));
1182: $allroles{'cm./'}.=':'.$syspriv;
1183: $allroles{$spec.'./'}.=':'.$syspriv;
1184: if ($tdomain ne '') {
1185: $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
1186: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
1187: if ($trest ne '') {
1188: $allroles{'cm.'.$area}.=':'.$coursepriv;
1189: $allroles{$spec.'.'.$area}.=':'.$coursepriv;
1190: }
1191: }
1192: }
1193: }
1194: } else {
1195: $allroles{'cm./'}.=':'.$pr{$trole.':s'};
1196: $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
1197: if ($tdomain ne '') {
1198: $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1199: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1200: if ($trest ne '') {
1201: $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
1202: $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
1203: }
1204: }
1205: }
1206: }
1207: }
1208: }
1209: my $adv=0;
1210: my $author=0;
1211: foreach (keys %allroles) {
1212: %thesepriv=();
1213: if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1214: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1215: foreach (split(/:/,$allroles{$_})) {
1216: if ($_ ne '') {
1217: my ($privilege,$restrictions)=split(/&/,$_);
1218: if ($restrictions eq '') {
1219: $thesepriv{$privilege}='F';
1220: } else {
1221: if ($thesepriv{$privilege} ne 'F') {
1222: $thesepriv{$privilege}.=$restrictions;
1223: }
1224: }
1225: }
1226: }
1227: $thesestr='';
1228: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1229: $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1230: }
1231: $userroles.='user.adv='.$adv."\n".
1232: 'user.author='.$author."\n";
1233: $ENV{'user.adv'}=$adv;
1234: }
1235: return $userroles;
1236: }
1237:
1238: # --------------------------------------------------------------- get interface
1239:
1240: sub get {
1241: my ($namespace,$storearr,$udomain,$uname)=@_;
1242: my $items='';
1243: foreach (@$storearr) {
1244: $items.=escape($_).'&';
1245: }
1246: $items=~s/\&$//;
1247: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1248: if (!$uname) { $uname=$ENV{'user.name'}; }
1249: my $uhome=&homeserver($uname,$udomain);
1250:
1251: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1252: my @pairs=split(/\&/,$rep);
1253: my %returnhash=();
1254: my $i=0;
1255: foreach (@$storearr) {
1256: $returnhash{$_}=unescape($pairs[$i]);
1257: $i++;
1258: }
1259: return %returnhash;
1260: }
1261:
1262: # --------------------------------------------------------------- del interface
1263:
1264: sub del {
1265: my ($namespace,$storearr,$udomain,$uname)=@_;
1266: my $items='';
1267: foreach (@$storearr) {
1268: $items.=escape($_).'&';
1269: }
1270: $items=~s/\&$//;
1271: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1272: if (!$uname) { $uname=$ENV{'user.name'}; }
1273: my $uhome=&homeserver($uname,$udomain);
1274:
1275: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1276: }
1277:
1278: # -------------------------------------------------------------- dump interface
1279:
1280: sub dump {
1281: my ($namespace,$udomain,$uname,$regexp)=@_;
1282: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1283: if (!$uname) { $uname=$ENV{'user.name'}; }
1284: my $uhome=&homeserver($uname,$udomain);
1285: if ($regexp) {
1286: $regexp=&escape($regexp);
1287: } else {
1288: $regexp='.';
1289: }
1290: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1291: my @pairs=split(/\&/,$rep);
1292: my %returnhash=();
1293: foreach (@pairs) {
1294: my ($key,$value)=split(/=/,$_);
1295: $returnhash{unescape($key)}=unescape($value);
1296: }
1297: return %returnhash;
1298: }
1299:
1300: # --------------------------------------------------------------- put interface
1301:
1302: sub put {
1303: my ($namespace,$storehash,$udomain,$uname)=@_;
1304: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1305: if (!$uname) { $uname=$ENV{'user.name'}; }
1306: my $uhome=&homeserver($uname,$udomain);
1307: my $items='';
1308: foreach (keys %$storehash) {
1309: $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1310: }
1311: $items=~s/\&$//;
1312: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1313: }
1314:
1315: # ------------------------------------------------------ critical put interface
1316:
1317: sub cput {
1318: my ($namespace,$storehash,$udomain,$uname)=@_;
1319: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1320: if (!$uname) { $uname=$ENV{'user.name'}; }
1321: my $uhome=&homeserver($uname,$udomain);
1322: my $items='';
1323: foreach (keys %$storehash) {
1324: $items.=escape($_).'='.escape($$storehash{$_}).'&';
1325: }
1326: $items=~s/\&$//;
1327: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1328: }
1329:
1330: # -------------------------------------------------------------- eget interface
1331:
1332: sub eget {
1333: my ($namespace,$storearr,$udomain,$uname)=@_;
1334: my $items='';
1335: foreach (@$storearr) {
1336: $items.=escape($_).'&';
1337: }
1338: $items=~s/\&$//;
1339: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
1340: if (!$uname) { $uname=$ENV{'user.name'}; }
1341: my $uhome=&homeserver($uname,$udomain);
1342: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1343: my @pairs=split(/\&/,$rep);
1344: my %returnhash=();
1345: my $i=0;
1346: foreach (@$storearr) {
1347: $returnhash{$_}=unescape($pairs[$i]);
1348: $i++;
1349: }
1350: return %returnhash;
1351: }
1352:
1353: # ------------------------------------------------- Check for a user privilege
1354:
1355: sub allowed {
1356: my ($priv,$uri)=@_;
1357:
1358: my $orguri=$uri;
1359: $uri=&declutter($uri);
1360:
1361: # Free bre access to adm and meta resources
1362:
1363: if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1364: return 'F';
1365: }
1366:
1367: # Free bre to public access
1368:
1369: if ($priv eq 'bre') {
1370: if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
1371: }
1372:
1373: my $thisallowed='';
1374: my $statecond=0;
1375: my $courseprivid='';
1376:
1377: # Course
1378:
1379: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
1380: $thisallowed.=$1;
1381: }
1382:
1383: # Domain
1384:
1385: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1386: =~/$priv\&([^\:]*)/) {
1387: $thisallowed.=$1;
1388: }
1389:
1390: # Course: uri itself is a course
1391: my $courseuri=$uri;
1392: $courseuri=~s/\_(\d)/\/$1/;
1393: $courseuri=~s/^([^\/])/\/$1/;
1394:
1395: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1396: =~/$priv\&([^\:]*)/) {
1397: $thisallowed.=$1;
1398: }
1399:
1400: # Full access at system, domain or course-wide level? Exit.
1401:
1402: if ($thisallowed=~/F/) {
1403: return 'F';
1404: }
1405:
1406: # If this is generating or modifying users, exit with special codes
1407:
1408: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1409: return $thisallowed;
1410: }
1411: #
1412: # Gathered so far: system, domain and course wide privileges
1413: #
1414: # Course: See if uri or referer is an individual resource that is part of
1415: # the course
1416:
1417: if ($ENV{'request.course.id'}) {
1418: $courseprivid=$ENV{'request.course.id'};
1419: if ($ENV{'request.course.sec'}) {
1420: $courseprivid.='/'.$ENV{'request.course.sec'};
1421: }
1422: $courseprivid=~s/\_/\//;
1423: my $checkreferer=1;
1424: my @uriparts=split(/\//,$uri);
1425: my $filename=$uriparts[$#uriparts];
1426: my $pathname=$uri;
1427: $pathname=~s/\/$filename$//;
1428: if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1429: /\&$filename\:([\d\|]+)\&/) {
1430: $statecond=$1;
1431: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1432: =~/$priv\&([^\:]*)/) {
1433: $thisallowed.=$1;
1434: $checkreferer=0;
1435: }
1436: }
1437:
1438: if ($checkreferer) {
1439: my $refuri=$ENV{'httpref.'.$orguri};
1440:
1441: unless ($refuri) {
1442: foreach (keys %ENV) {
1443: if ($_=~/^httpref\..*\*/) {
1444: my $pattern=$_;
1445: $pattern=~s/^httpref\.\/res\///;
1446: $pattern=~s/\*/\[\^\/\]\+/g;
1447: $pattern=~s/\//\\\//g;
1448: if ($orguri=~/$pattern/) {
1449: $refuri=$ENV{$_};
1450: }
1451: }
1452: }
1453: }
1454: if ($refuri) {
1455: $refuri=&declutter($refuri);
1456: my @uriparts=split(/\//,$refuri);
1457: my $filename=$uriparts[$#uriparts];
1458: my $pathname=$refuri;
1459: $pathname=~s/\/$filename$//;
1460: if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1461: /\&$filename\:([\d\|]+)\&/) {
1462: my $refstatecond=$1;
1463: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1464: =~/$priv\&([^\:]*)/) {
1465: $thisallowed.=$1;
1466: $uri=$refuri;
1467: $statecond=$refstatecond;
1468: }
1469: }
1470: }
1471: }
1472: }
1473:
1474: #
1475: # Gathered now: all privileges that could apply, and condition number
1476: #
1477: #
1478: # Full or no access?
1479: #
1480:
1481: if ($thisallowed=~/F/) {
1482: return 'F';
1483: }
1484:
1485: unless ($thisallowed) {
1486: return '';
1487: }
1488:
1489: # Restrictions exist, deal with them
1490: #
1491: # C:according to course preferences
1492: # R:according to resource settings
1493: # L:unless locked
1494: # X:according to user session state
1495: #
1496:
1497: # Possibly locked functionality, check all courses
1498: # Locks might take effect only after 10 minutes cache expiration for other
1499: # courses, and 2 minutes for current course
1500:
1501: my $envkey;
1502: if ($thisallowed=~/L/) {
1503: foreach $envkey (keys %ENV) {
1504: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
1505: my $courseid=$2;
1506: my $roleid=$1.'.'.$2;
1507: $courseid=~s/^\///;
1508: my $expiretime=600;
1509: if ($ENV{'request.role'} eq $roleid) {
1510: $expiretime=120;
1511: }
1512: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
1513: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1514: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
1515: &coursedescription($courseid);
1516: }
1517: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
1518: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
1519: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1520: &log($ENV{'user.domain'},$ENV{'user.name'},
1521: $ENV{'user.host'},
1522: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1523: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1524: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1525: return '';
1526: }
1527: }
1528: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
1529: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1530: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1531: &log($ENV{'user.domain'},$ENV{'user.name'},
1532: $ENV{'user.host'},
1533: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1534: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1535: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1536: return '';
1537: }
1538: }
1539: }
1540: }
1541: }
1542:
1543: #
1544: # Rest of the restrictions depend on selected course
1545: #
1546:
1547: unless ($ENV{'request.course.id'}) {
1548: return '1';
1549: }
1550:
1551: #
1552: # Now user is definitely in a course
1553: #
1554:
1555:
1556: # Course preferences
1557:
1558: if ($thisallowed=~/C/) {
1559: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1560: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1561: =~/$rolecode/) {
1562: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1563: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1564: $ENV{'request.course.id'});
1565: return '';
1566: }
1567: }
1568:
1569: # Resource preferences
1570:
1571: if ($thisallowed=~/R/) {
1572: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1573: my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
1574: if (-e $filename) {
1575: my @content;
1576: {
1577: my $fh=Apache::File->new($filename);
1578: @content=<$fh>;
1579: }
1580: if (join('',@content)=~
1581: /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1582: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1583: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1584: return '';
1585:
1586: }
1587: }
1588: }
1589:
1590: # Restricted by state?
1591:
1592: if ($thisallowed=~/X/) {
1593: if (&condval($statecond)) {
1594: return '2';
1595: } else {
1596: return '';
1597: }
1598: }
1599:
1600: return 'F';
1601: }
1602:
1603: # ----------------------------------------------------------------- Define Role
1604:
1605: sub definerole {
1606: if (allowed('mcr','/')) {
1607: my ($rolename,$sysrole,$domrole,$courole)=@_;
1608: foreach (split('/',$sysrole)) {
1609: my ($crole,$cqual)=split(/\&/,$_);
1610: if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
1611: if ($pr{'cr:s'}=~/$crole\&/) {
1612: if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) {
1613: return "refused:s:$crole&$cqual";
1614: }
1615: }
1616: }
1617: foreach (split('/',$domrole)) {
1618: my ($crole,$cqual)=split(/\&/,$_);
1619: if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
1620: if ($pr{'cr:d'}=~/$crole\&/) {
1621: if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) {
1622: return "refused:d:$crole&$cqual";
1623: }
1624: }
1625: }
1626: foreach (split('/',$courole)) {
1627: my ($crole,$cqual)=split(/\&/,$_);
1628: if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
1629: if ($pr{'cr:c'}=~/$crole\&/) {
1630: if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) {
1631: return "refused:c:$crole&$cqual";
1632: }
1633: }
1634: }
1635: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
1636: "$ENV{'user.domain'}:$ENV{'user.name'}:".
1637: "rolesdef_$rolename=".
1638: escape($sysrole.'_'.$domrole.'_'.$courole);
1639: return reply($command,$ENV{'user.home'});
1640: } else {
1641: return 'refused';
1642: }
1643: }
1644:
1645: # ---------------- Make a metadata query against the network of library servers
1646:
1647: sub metadata_query {
1648: my ($query,$custom,$customshow)=@_;
1649: my %rhash;
1650: for my $server (keys %libserv) {
1651: unless ($custom or $customshow) {
1652: my $reply=&reply("querysend:".&escape($query),$server);
1653: $rhash{$server}=$reply;
1654: }
1655: else {
1656: my $reply=&reply("querysend:".&escape($query).':'.
1657: &escape($custom).':'.&escape($customshow),
1658: $server);
1659: $rhash{$server}=$reply;
1660: }
1661: }
1662: return \%rhash;
1663: }
1664:
1665: # ------------------------------------------------------------------ Plain Text
1666:
1667: sub plaintext {
1668: my $short=shift;
1669: return $prp{$short};
1670: }
1671:
1672: # ----------------------------------------------------------------- Assign Role
1673:
1674: sub assignrole {
1675: my ($udom,$uname,$url,$role,$end,$start)=@_;
1676: my $mrole;
1677: if ($role =~ /^cr\//) {
1678: unless (&allowed('ccr',$url)) {
1679: &logthis('Refused custom assignrole: '.
1680: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1681: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1682: return 'refused';
1683: }
1684: $mrole='cr';
1685: } else {
1686: my $cwosec=$url;
1687: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1688: unless (&allowed('c'.$role,$cwosec)) {
1689: &logthis('Refused assignrole: '.
1690: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1691: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1692: return 'refused';
1693: }
1694: $mrole=$role;
1695: }
1696: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
1697: "$udom:$uname:$url".'_'."$mrole=$role";
1698: if ($end) { $command.='_'.$end; }
1699: if ($start) {
1700: if ($end) {
1701: $command.='_'.$start;
1702: } else {
1703: $command.='_0_'.$start;
1704: }
1705: }
1706: return &reply($command,&homeserver($uname,$udom));
1707: }
1708:
1709: # -------------------------------------------------- Modify user authentication
1710: # Overrides without validation
1711:
1712: sub modifyuserauth {
1713: my ($udom,$uname,$umode,$upass)=@_;
1714: my $uhome=&homeserver($uname,$udom);
1715: unless (&allowed('mau',$udom)) { return 'refused'; }
1716: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1717: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});
1718: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
1719: &escape($upass),$uhome);
1720: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
1721: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1722: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1723: &log($udom,,$uname,$uhome,
1724: 'Authentication changed by '.$ENV{'user.domain'}.', '.
1725: $ENV{'user.name'}.', '.$umode.
1726: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1727: unless ($reply eq 'ok') {
1728: &logthis('Authentication mode error: '.$reply);
1729: return 'error: '.$reply;
1730: }
1731: return 'ok';
1732: }
1733:
1734: # --------------------------------------------------------------- Modify a user
1735:
1736:
1737: sub modifyuser {
1738: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
1739: $forceid)=@_;
1740: $udom=~s/\W//g;
1741: $uname=~s/\W//g;
1742: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1743: $umode.', '.$first.', '.$middle.', '.
1744: $last.', '.$gene.'(forceid: '.$forceid.') by '.
1745: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1746: my $uhome=&homeserver($uname,$udom);
1747: # ----------------------------------------------------------------- Create User
1748: if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1749: my $unhome='';
1750: if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1751: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1752: } else {
1753: my $tryserver;
1754: my $loadm=10000000;
1755: foreach $tryserver (keys %libserv) {
1756: if ($hostdom{$tryserver} eq $udom) {
1757: my $answer=reply('load',$tryserver);
1758: if (($answer=~/\d+/) && ($answer<$loadm)) {
1759: $loadm=$answer;
1760: $unhome=$tryserver;
1761: }
1762: }
1763: }
1764: }
1765: if (($unhome eq '') || ($unhome eq 'no_host')) {
1766: return 'error: find home';
1767: }
1768: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
1769: &escape($upass),$unhome);
1770: unless ($reply eq 'ok') {
1771: return 'error: '.$reply;
1772: }
1773: $uhome=&homeserver($uname,$udom);
1774: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1775: return 'error: verify home';
1776: }
1777: }
1778: # ---------------------------------------------------------------------- Add ID
1779: if ($uid) {
1780: $uid=~tr/A-Z/a-z/;
1781: my %uidhash=&idrget($udom,$uname);
1782: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
1783: && (!$forceid)) {
1784: unless ($uid eq $uidhash{$uname}) {
1785: return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
1786: }
1787: } else {
1788: &idput($udom,($uname => $uid));
1789: }
1790: }
1791: # -------------------------------------------------------------- Add names, etc
1792: my %names=&get('environment',
1793: ['firstname','middlename','lastname','generation'],
1794: $udom,$uname);
1795: if ($first) { $names{'firstname'} = $first; }
1796: if ($middle) { $names{'middlename'} = $middle; }
1797: if ($last) { $names{'lastname'} = $last; }
1798: if ($gene) { $names{'generation'} = $gene; }
1799: my $reply = &put('environment', \%names, $udom,$uname);
1800: if ($reply ne 'ok') { return 'error: '.$reply; }
1801: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1802: $umode.', '.$first.', '.$middle.', '.
1803: $last.', '.$gene.' by '.
1804: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1805: return 'ok';
1806: }
1807:
1808: # -------------------------------------------------------------- Modify student
1809:
1810: sub modifystudent {
1811: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1812: $end,$start,$forceid)=@_;
1813: my $cid='';
1814: unless ($cid=$ENV{'request.course.id'}) {
1815: return 'not_in_class';
1816: }
1817: # --------------------------------------------------------------- Make the user
1818: my $reply=&modifyuser
1819: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid);
1820: unless ($reply eq 'ok') { return $reply; }
1821: my $uhome=&homeserver($uname,$udom);
1822: if (($uhome eq '') || ($uhome eq 'no_host')) {
1823: return 'error: no such user';
1824: }
1825: # -------------------------------------------------- Add student to course list
1826: $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1827: $ENV{'course.'.$cid.'.num'}.':classlist:'.
1828: &escape($uname.':'.$udom).'='.
1829: &escape($end.':'.$start),
1830: $ENV{'course.'.$cid.'.home'});
1831: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
1832: return 'error: '.$reply;
1833: }
1834: # ---------------------------------------------------- Add student role to user
1835: my $uurl='/'.$cid;
1836: $uurl=~s/\_/\//g;
1837: if ($usec) {
1838: $uurl.='/'.$usec;
1839: }
1840: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1841: }
1842:
1843: # ------------------------------------------------- Write to course preferences
1844:
1845: sub writecoursepref {
1846: my ($courseid,%prefs)=@_;
1847: $courseid=~s/^\///;
1848: $courseid=~s/\_/\//g;
1849: my ($cdomain,$cnum)=split(/\//,$courseid);
1850: my $chome=homeserver($cnum,$cdomain);
1851: if (($chome eq '') || ($chome eq 'no_host')) {
1852: return 'error: no such course';
1853: }
1854: my $cstring='';
1855: foreach (keys %prefs) {
1856: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1857: }
1858: $cstring=~s/\&$//;
1859: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
1860: }
1861:
1862: # ---------------------------------------------------------- Make/modify course
1863:
1864: sub createcourse {
1865: my ($udom,$description,$url)=@_;
1866: $url=&declutter($url);
1867: my $cid='';
1868: unless (&allowed('ccc',$ENV{'user.domain'})) {
1869: return 'refused';
1870: }
1871: unless ($udom eq $ENV{'user.domain'}) {
1872: return 'refused';
1873: }
1874: # ------------------------------------------------------------------- Create ID
1875: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
1876: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1877: # ----------------------------------------------- Make sure that does not exist
1878: my $uhome=&homeserver($uname,$udom);
1879: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1880: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
1881: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1882: $uhome=&homeserver($uname,$udom);
1883: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1884: return 'error: unable to generate unique course-ID';
1885: }
1886: }
1887: # ------------------------------------------------------------- Make the course
1888: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1889: $ENV{'user.home'});
1890: unless ($reply eq 'ok') { return 'error: '.$reply; }
1891: $uhome=&homeserver($uname,$udom);
1892: if (($uhome eq '') || ($uhome eq 'no_host')) {
1893: return 'error: no such course';
1894: }
1895: &writecoursepref($udom.'_'.$uname,
1896: ('description' => $description,
1897: 'url' => $url));
1898: return '/'.$udom.'/'.$uname;
1899: }
1900:
1901: # ---------------------------------------------------------- Assign Custom Role
1902:
1903: sub assigncustomrole {
1904: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
1905: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1906: $end,$start);
1907: }
1908:
1909: # ----------------------------------------------------------------- Revoke Role
1910:
1911: sub revokerole {
1912: my ($udom,$uname,$url,$role)=@_;
1913: my $now=time;
1914: return &assignrole($udom,$uname,$url,$role,$now);
1915: }
1916:
1917: # ---------------------------------------------------------- Revoke Custom Role
1918:
1919: sub revokecustomrole {
1920: my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
1921: my $now=time;
1922: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
1923: }
1924:
1925: # ------------------------------------------------------------ Directory lister
1926:
1927: sub dirlist {
1928: my $uri=shift;
1929: $uri=~s/^\///;
1930: $uri=~s/\/$//;
1931: my ($res,$udom,$uname,@rest)=split(/\//,$uri);
1932: if ($udom) {
1933: if ($uname) {
1934: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
1935: homeserver($uname,$udom));
1936: return split(/:/,$listing);
1937: } else {
1938: my $tryserver;
1939: my %allusers=();
1940: foreach $tryserver (keys %libserv) {
1941: if ($hostdom{$tryserver} eq $udom) {
1942: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
1943: $tryserver);
1944: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
1945: && ($listing ne 'con_lost')) {
1946: foreach (split(/:/,$listing)) {
1947: my ($entry,@stat)=split(/&/,$_);
1948: $allusers{$entry}=1;
1949: }
1950: }
1951: }
1952: }
1953: my $alluserstr='';
1954: foreach (sort keys %allusers) {
1955: $alluserstr.=$_.'&user:';
1956: }
1957: $alluserstr=~s/:$//;
1958: return split(/:/,$alluserstr);
1959: }
1960: } else {
1961: my $tryserver;
1962: my %alldom=();
1963: foreach $tryserver (keys %libserv) {
1964: $alldom{$hostdom{$tryserver}}=1;
1965: }
1966: my $alldomstr='';
1967: foreach (sort keys %alldom) {
1968: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
1969: }
1970: $alldomstr=~s/:$//;
1971: return split(/:/,$alldomstr);
1972: }
1973: }
1974:
1975: # -------------------------------------------------------- Value of a Condition
1976:
1977: sub directcondval {
1978: my $number=shift;
1979: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
1980: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
1981: } else {
1982: return 2;
1983: }
1984: }
1985:
1986: sub condval {
1987: my $condidx=shift;
1988: my $result=0;
1989: my $allpathcond='';
1990: foreach (split(/\|/,$condidx)) {
1991: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
1992: $allpathcond.=
1993: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
1994: }
1995: }
1996: $allpathcond=~s/\|$//;
1997: if ($ENV{'request.course.id'}) {
1998: if ($allpathcond) {
1999: my $operand='|';
2000: my @stack;
2001: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
2002: if ($_ eq '(') {
2003: push @stack,($operand,$result)
2004: } elsif ($_ eq ')') {
2005: my $before=pop @stack;
2006: if (pop @stack eq '&') {
2007: $result=$result>$before?$before:$result;
2008: } else {
2009: $result=$result>$before?$result:$before;
2010: }
2011: } elsif (($_ eq '&') || ($_ eq '|')) {
2012: $operand=$_;
2013: } else {
2014: my $new=directcondval($_);
2015: if ($operand eq '&') {
2016: $result=$result>$new?$new:$result;
2017: } else {
2018: $result=$result>$new?$result:$new;
2019: }
2020: }
2021: }
2022: }
2023: }
2024: return $result;
2025: }
2026:
2027: # --------------------------------------------------- Course Resourcedata Query
2028:
2029: sub courseresdata {
2030: my ($coursenum,$coursedomain,@which)=@_;
2031: my $coursehom=&homeserver($coursenum,$coursedomain);
2032: my $hashid=$coursenum.':'.$coursedomain;
2033: unless (defined($courseresdatacache{$hashid.'.time'})) {
2034: unless (time-$courseresdatacache{$hashid.'.time'}<300) {
2035: my $coursehom=&homeserver($coursenum,$coursedomain);
2036: if ($coursehom) {
2037: my $dumpreply=&reply('dump:'.$coursedomain.':'.$coursenum.
2038: ':resourcedata:.',$coursehom);
2039: unless ($dumpreply=~/^error\:/) {
2040: $courseresdatacache{$hashid.'.time'}=time;
2041: $courseresdatacache{$hashid}=$dumpreply;
2042: }
2043: }
2044: }
2045: }
2046: my @pairs=split(/\&/,$courseresdatacache{$hashid});
2047: my %returnhash=();
2048: foreach (@pairs) {
2049: my ($key,$value)=split(/=/,$_);
2050: $returnhash{unescape($key)}=unescape($value);
2051: }
2052: my $item;
2053: foreach $item (@which) {
2054: if ($returnhash{$item}) { return $returnhash{$item}; }
2055: }
2056: return '';
2057: }
2058:
2059: # --------------------------------------------------------- Value of a Variable
2060:
2061: sub EXT {
2062: my ($varname,$symbparm)=@_;
2063: unless ($varname) { return ''; }
2064: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
2065: my $rest;
2066: if ($therest[0]) {
2067: $rest=join('.',@therest);
2068: } else {
2069: $rest='';
2070: }
2071: my $qualifierrest=$qualifier;
2072: if ($rest) { $qualifierrest.='.'.$rest; }
2073: my $spacequalifierrest=$space;
2074: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
2075: if ($realm eq 'user') {
2076: # --------------------------------------------------------------- user.resource
2077: if ($space eq 'resource') {
2078: my %restored=&restore();
2079: return $restored{$qualifierrest};
2080: # ----------------------------------------------------------------- user.access
2081: } elsif ($space eq 'access') {
2082: return &allowed($qualifier,$rest);
2083: # ------------------------------------------ user.preferences, user.environment
2084: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
2085: return $ENV{join('.',('environment',$qualifierrest))};
2086: # ----------------------------------------------------------------- user.course
2087: } elsif ($space eq 'course') {
2088: return $ENV{join('.',('request.course',$qualifier))};
2089: # ------------------------------------------------------------------- user.role
2090: } elsif ($space eq 'role') {
2091: my ($role,$where)=split(/\./,$ENV{'request.role'});
2092: if ($qualifier eq 'value') {
2093: return $role;
2094: } elsif ($qualifier eq 'extent') {
2095: return $where;
2096: }
2097: # ----------------------------------------------------------------- user.domain
2098: } elsif ($space eq 'domain') {
2099: return $ENV{'user.domain'};
2100: # ------------------------------------------------------------------- user.name
2101: } elsif ($space eq 'name') {
2102: return $ENV{'user.name'};
2103: # ---------------------------------------------------- Any other user namespace
2104: } else {
2105: my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
2106: my %reply=&get($space,[$item]);
2107: return $reply{$item};
2108: }
2109: } elsif ($realm eq 'request') {
2110: # ------------------------------------------------------------- request.browser
2111: if ($space eq 'browser') {
2112: return $ENV{'browser.'.$qualifier};
2113: # ------------------------------------------------------------ request.filename
2114: } else {
2115: return $ENV{'request.'.$spacequalifierrest};
2116: }
2117: } elsif ($realm eq 'course') {
2118: # ---------------------------------------------------------- course.description
2119: return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
2120: $spacequalifierrest};
2121: } elsif ($realm eq 'resource') {
2122: if ($ENV{'request.course.id'}) {
2123:
2124: # print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
2125:
2126:
2127: # ----------------------------------------------------- Cascading lookup scheme
2128: my $symbp;
2129: if ($symbparm) {
2130: $symbp=$symbparm;
2131: } else {
2132: $symbp=&symbread();
2133: }
2134: my $mapp=(split(/\_\_\_/,$symbp))[0];
2135:
2136: my $symbparm=$symbp.'.'.$spacequalifierrest;
2137: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
2138:
2139: my $seclevel=
2140: $ENV{'request.course.id'}.'.['.
2141: $ENV{'request.course.sec'}.'].'.$spacequalifierrest;
2142: my $seclevelr=
2143: $ENV{'request.course.id'}.'.['.
2144: $ENV{'request.course.sec'}.'].'.$symbparm;
2145: my $seclevelm=
2146: $ENV{'request.course.id'}.'.['.
2147: $ENV{'request.course.sec'}.'].'.$mapparm;
2148:
2149: my $courselevel=
2150: $ENV{'request.course.id'}.'.'.$spacequalifierrest;
2151: my $courselevelr=
2152: $ENV{'request.course.id'}.'.'.$symbparm;
2153: my $courselevelm=
2154: $ENV{'request.course.id'}.'.'.$mapparm;
2155:
2156: # ----------------------------------------------------------- first, check user
2157: my %resourcedata=get('resourcedata',
2158: [$courselevelr,$courselevelm,$courselevel]);
2159: if (($resourcedata{$courselevelr}!~/^error\:/) &&
2160: ($resourcedata{$courselevelr}!~/^con_lost/)) {
2161:
2162: if ($resourcedata{$courselevelr}) {
2163: return $resourcedata{$courselevelr}; }
2164: if ($resourcedata{$courselevelm}) {
2165: return $resourcedata{$courselevelm}; }
2166: if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
2167:
2168: } else {
2169: if ($resourcedata{$courselevelr}!~/No such file/) {
2170: &logthis("<font color=blue>WARNING:".
2171: " Trying to get resource data for ".$ENV{'user.name'}." at "
2172: .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
2173: "</font>");
2174: }
2175: }
2176:
2177: # -------------------------------------------------------- second, check course
2178:
2179: my $coursereply=&courseresdata(
2180: $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
2181: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
2182: ($seclevelr,$seclevelm,$seclevel,
2183: $courselevelr,$courselevelm,$courselevel));
2184: if ($coursereply) { return $coursereply; }
2185:
2186: # ------------------------------------------------------ third, check map parms
2187: my %parmhash=();
2188: my $thisparm='';
2189: if (tie(%parmhash,'GDBM_File',
2190: $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
2191: $thisparm=$parmhash{$symbparm};
2192: untie(%parmhash);
2193: }
2194: if ($thisparm) { return $thisparm; }
2195: }
2196:
2197: # --------------------------------------------- last, look in resource metadata
2198:
2199: $spacequalifierrest=~s/\./\_/;
2200: my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
2201: if ($metadata) { return $metadata; }
2202: $metadata=&metadata($ENV{'request.filename'},
2203: 'parameter_'.$spacequalifierrest);
2204: if ($metadata) { return $metadata; }
2205:
2206: # ------------------------------------------------------------------ Cascade up
2207:
2208: unless ($space eq '0') {
2209: my ($part,$id)=split(/\_/,$space);
2210: if ($id) {
2211: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
2212: $symbparm);
2213: if ($partgeneral) { return $partgeneral; }
2214: } else {
2215: my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
2216: $symbparm);
2217: if ($resourcegeneral) { return $resourcegeneral; }
2218: }
2219: }
2220:
2221: # ---------------------------------------------------- Any other user namespace
2222: } elsif ($realm eq 'environment') {
2223: # ----------------------------------------------------------------- environment
2224: return $ENV{'environment.'.$spacequalifierrest};
2225: } elsif ($realm eq 'system') {
2226: # ----------------------------------------------------------------- system.time
2227: if ($space eq 'time') {
2228: return time;
2229: }
2230: }
2231: return '';
2232: }
2233:
2234: # ---------------------------------------------------------------- Get metadata
2235:
2236: sub metadata {
2237: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
2238:
2239: $uri=&declutter($uri);
2240: my $filename=$uri;
2241: $uri=~s/\.meta$//;
2242: #
2243: # Is the metadata already cached?
2244: # Look at timestamp of caching
2245: # Everything is cached by the main uri, libraries are never directly cached
2246: #
2247: unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
2248: #
2249: # Is this a recursive call for a library?
2250: #
2251: if ($liburi) {
2252: $liburi=&declutter($liburi);
2253: $filename=$liburi;
2254: }
2255: my %metathesekeys=();
2256: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
2257: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
2258: my $parser=HTML::TokeParser->new(\$metastring);
2259: my $token;
2260: undef %metathesekeys;
2261: while ($token=$parser->get_token) {
2262: if ($token->[0] eq 'S') {
2263: if (defined($token->[2]->{'package'})) {
2264: #
2265: # This is a package - get package info
2266: #
2267: my $package=$token->[2]->{'package'};
2268: my $keyroot='';
2269: if ($prefix) {
2270: $keyroot.='_'.$prefix;
2271: } else {
2272: if (defined($token->[2]->{'part'})) {
2273: $keyroot.='_'.$token->[2]->{'part'};
2274: }
2275: }
2276: if (defined($token->[2]->{'id'})) {
2277: $keyroot.='_'.$token->[2]->{'id'};
2278: }
2279: if ($metacache{$uri.':packages'}) {
2280: $metacache{$uri.':packages'}.=','.$package.$keyroot;
2281: } else {
2282: $metacache{$uri.':packages'}=$package.$keyroot;
2283: }
2284: foreach (keys %packagetab) {
2285: if ($_=~/^$package\&/) {
2286: my ($pack,$name,$subp)=split(/\&/,$_);
2287: my $value=$packagetab{$_};
2288: my $part=$keyroot;
2289: $part=~s/^\_//;
2290: if ($subp eq 'display') {
2291: $value.=' [Part: '.$part.']';
2292: }
2293: my $unikey='parameter'.$keyroot.'_'.$name;
2294: $metathesekeys{$unikey}=1;
2295: $metacache{$uri.':'.$unikey.'.part'}=$part;
2296: unless
2297: (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
2298: $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
2299: }
2300: }
2301: }
2302: } else {
2303: #
2304: # This is not a package - some other kind of start tag
2305: #
2306: my $entry=$token->[1];
2307: my $unikey;
2308: if ($entry eq 'import') {
2309: $unikey='';
2310: } else {
2311: $unikey=$entry;
2312: }
2313: if ($prefix) {
2314: $unikey.=$prefix;
2315: } else {
2316: if (defined($token->[2]->{'part'})) {
2317: $unikey.='_'.$token->[2]->{'part'};
2318: }
2319: }
2320: if (defined($token->[2]->{'id'})) {
2321: $unikey.='_'.$token->[2]->{'id'};
2322: }
2323:
2324: if ($entry eq 'import') {
2325: #
2326: # Importing a library here
2327: #
2328: if (defined($depthcount)) { $depthcount++; } else
2329: { $depthcount=0; }
2330: if ($depthcount<20) {
2331: foreach (split(/\,/,&metadata($uri,'keys',
2332: $parser->get_text('/import'),$unikey,
2333: $depthcount))) {
2334: $metathesekeys{$_}=1;
2335: }
2336: }
2337: } else {
2338:
2339: if (defined($token->[2]->{'name'})) {
2340: $unikey.='_'.$token->[2]->{'name'};
2341: }
2342: $metathesekeys{$unikey}=1;
2343: foreach (@{$token->[3]}) {
2344: $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
2345: }
2346: unless (
2347: $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
2348: ) { $metacache{$uri.':'.$unikey}=
2349: $metacache{$uri.':'.$unikey.'.default'};
2350: }
2351: # end of not-a-package not-a-library import
2352: }
2353: # end of not-a-package start tag
2354: }
2355: # the next is the end of "start tag"
2356: }
2357: }
2358: $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
2359: $metacache{$uri.':cachedtimestamp'}=time;
2360: # this is the end of "was not already recently cached
2361: }
2362: return $metacache{$uri.':'.$what};
2363: }
2364:
2365: # ------------------------------------------------- Update symbolic store links
2366:
2367: sub symblist {
2368: my ($mapname,%newhash)=@_;
2369: $mapname=declutter($mapname);
2370: my %hash;
2371: if (($ENV{'request.course.fn'}) && (%newhash)) {
2372: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
2373: &GDBM_WRCREAT,0640)) {
2374: foreach (keys %newhash) {
2375: $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
2376: }
2377: if (untie(%hash)) {
2378: return 'ok';
2379: }
2380: }
2381: }
2382: return 'error';
2383: }
2384:
2385: # ------------------------------------------------------ Return symb list entry
2386:
2387: sub symbread {
2388: my $thisfn=shift;
2389: unless ($thisfn) {
2390: if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
2391: $thisfn=$ENV{'request.filename'};
2392: }
2393: $thisfn=declutter($thisfn);
2394: my %hash;
2395: my %bighash;
2396: my $syval='';
2397: if (($ENV{'request.course.fn'}) && ($thisfn)) {
2398: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
2399: &GDBM_READER,0640)) {
2400: $syval=$hash{$thisfn};
2401: untie(%hash);
2402: }
2403: # ---------------------------------------------------------- There was an entry
2404: if ($syval) {
2405: unless ($syval=~/\_\d+$/) {
2406: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
2407: &appenv('request.ambiguous' => $thisfn);
2408: return '';
2409: }
2410: $syval.=$1;
2411: }
2412: } else {
2413: # ------------------------------------------------------- Was not in symb table
2414: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
2415: &GDBM_READER,0640)) {
2416: # ---------------------------------------------- Get ID(s) for current resource
2417: my $ids=$bighash{'ids_/res/'.$thisfn};
2418: unless ($ids) {
2419: $ids=$bighash{'ids_/'.$thisfn};
2420: }
2421: if ($ids) {
2422: # ------------------------------------------------------------------- Has ID(s)
2423: my @possibilities=split(/\,/,$ids);
2424: if ($#possibilities==0) {
2425: # ----------------------------------------------- There is only one possibility
2426: my ($mapid,$resid)=split(/\./,$ids);
2427: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
2428: } else {
2429: # ------------------------------------------ There is more than one possibility
2430: my $realpossible=0;
2431: foreach (@possibilities) {
2432: my $file=$bighash{'src_'.$_};
2433: if (&allowed('bre',$file)) {
2434: my ($mapid,$resid)=split(/\./,$_);
2435: if ($bighash{'map_type_'.$mapid} ne 'page') {
2436: $realpossible++;
2437: $syval=declutter($bighash{'map_id_'.$mapid}).
2438: '___'.$resid;
2439: }
2440: }
2441: }
2442: if ($realpossible!=1) { $syval=''; }
2443: }
2444: }
2445: untie(%bighash)
2446: }
2447: }
2448: if ($syval) {
2449: return $syval.'___'.$thisfn;
2450: }
2451: }
2452: &appenv('request.ambiguous' => $thisfn);
2453: return '';
2454: }
2455:
2456: # ---------------------------------------------------------- Return random seed
2457:
2458: sub numval {
2459: my $txt=shift;
2460: $txt=~tr/A-J/0-9/;
2461: $txt=~tr/a-j/0-9/;
2462: $txt=~tr/K-T/0-9/;
2463: $txt=~tr/k-t/0-9/;
2464: $txt=~tr/U-Z/0-5/;
2465: $txt=~tr/u-z/0-5/;
2466: $txt=~s/\D//g;
2467: return int($txt);
2468: }
2469:
2470: sub rndseed {
2471: my ($symb,$courseid,$domain,$username)=@_;
2472: if (!$symb) {
2473: unless ($symb=&symbread()) { return time; }
2474: }
2475: if (!$courseid) { $courseid=$ENV{'request.course.id'};}
2476: if (!$domain) {$domain=$ENV{'user.domain'};}
2477: if (!$username) {$username=$ENV{'user.name'};}
2478: {
2479: use integer;
2480: my $symbchck=unpack("%32C*",$symb) << 27;
2481: my $symbseed=numval($symb) << 22;
2482: my $namechck=unpack("%32C*",$username) << 17;
2483: my $nameseed=numval($username) << 12;
2484: my $domainseed=unpack("%32C*",$domain) << 7;
2485: my $courseseed=unpack("%32C*",$courseid);
2486: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
2487: #uncommenting these lines can break things!
2488: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
2489: #&Apache::lonxml::debug("rndseed :$num:$symb");
2490: return $num;
2491: }
2492: }
2493:
2494: sub ireceipt {
2495: my ($funame,$fudom,$fucourseid,$fusymb)=@_;
2496: my $cuname=unpack("%32C*",$funame);
2497: my $cudom=unpack("%32C*",$fudom);
2498: my $cucourseid=unpack("%32C*",$fucourseid);
2499: my $cusymb=unpack("%32C*",$fusymb);
2500: my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
2501: return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
2502: ($cunique%$cuname+
2503: $cunique%$cudom+
2504: $cusymb%$cuname+
2505: $cusymb%$cudom+
2506: $cucourseid%$cuname+
2507: $cucourseid%$cudom);
2508: }
2509:
2510: sub receipt {
2511: return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
2512: $ENV{'request.course.id'},&symbread());
2513: }
2514:
2515: # ------------------------------------------------------------ Serves up a file
2516: # returns either the contents of the file or a -1
2517: sub getfile {
2518: my $file=shift;
2519: &repcopy($file);
2520: if (! -e $file ) { return -1; };
2521: my $fh=Apache::File->new($file);
2522: my $a='';
2523: while (<$fh>) { $a .=$_; }
2524: return $a
2525: }
2526:
2527: sub filelocation {
2528: my ($dir,$file) = @_;
2529: my $location;
2530: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
2531: if ($file=~m:^/~:) { # is a contruction space reference
2532: $location = $file;
2533: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
2534: } else {
2535: $file=~s/^$perlvar{'lonDocRoot'}//;
2536: $file=~s:^/*res::;
2537: if ( !( $file =~ m:^/:) ) {
2538: $location = $dir. '/'.$file;
2539: } else {
2540: $location = '/home/httpd/html/res'.$file;
2541: }
2542: }
2543: $location=~s://+:/:g; # remove duplicate /
2544: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
2545: return $location;
2546: }
2547:
2548: sub hreflocation {
2549: my ($dir,$file)=@_;
2550: unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
2551: my $finalpath=filelocation($dir,$file);
2552: $finalpath=~s/^\/home\/httpd\/html//;
2553: return $finalpath;
2554: } else {
2555: return $file;
2556: }
2557: }
2558:
2559: # ------------------------------------------------------------- Declutters URLs
2560:
2561: sub declutter {
2562: my $thisfn=shift;
2563: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
2564: $thisfn=~s/^\///;
2565: $thisfn=~s/^res\///;
2566: return $thisfn;
2567: }
2568:
2569: # -------------------------------------------------------- Escape Special Chars
2570:
2571: sub escape {
2572: my $str=shift;
2573: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
2574: return $str;
2575: }
2576:
2577: # ----------------------------------------------------- Un-Escape Special Chars
2578:
2579: sub unescape {
2580: my $str=shift;
2581: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2582: return $str;
2583: }
2584:
2585: # ================================================================ Main Program
2586:
2587: sub goodbye {
2588: &flushcourselogs();
2589: &logthis("Shutting down");
2590: }
2591:
2592: BEGIN {
2593: # ------------------------------------------------------------ Read access.conf
2594: unless ($readit) {
2595: {
2596: my $config=Apache::File->new("/etc/httpd/conf/access.conf");
2597:
2598: while (my $configline=<$config>) {
2599: if ($configline =~ /PerlSetVar/) {
2600: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
2601: chomp($varvalue);
2602: $perlvar{$varname}=$varvalue;
2603: }
2604: }
2605: }
2606:
2607: # ------------------------------------------------------------- Read hosts file
2608: {
2609: my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
2610:
2611: while (my $configline=<$config>) {
2612: chomp($configline);
2613: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
2614: $hostname{$id}=$name;
2615: $hostdom{$id}=$domain;
2616: $hostip{$id}=$ip;
2617: if ($role eq 'library') { $libserv{$id}=$name; }
2618: }
2619: }
2620:
2621: # ------------------------------------------------------ Read spare server file
2622: {
2623: my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
2624:
2625: while (my $configline=<$config>) {
2626: chomp($configline);
2627: if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
2628: $spareid{$configline}=1;
2629: }
2630: }
2631: }
2632: # ------------------------------------------------------------ Read permissions
2633: {
2634: my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
2635:
2636: while (my $configline=<$config>) {
2637: chomp($configline);
2638: if ($configline) {
2639: my ($role,$perm)=split(/ /,$configline);
2640: if ($perm ne '') { $pr{$role}=$perm; }
2641: }
2642: }
2643: }
2644:
2645: # -------------------------------------------- Read plain texts for permissions
2646: {
2647: my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
2648:
2649: while (my $configline=<$config>) {
2650: chomp($configline);
2651: if ($configline) {
2652: my ($short,$plain)=split(/:/,$configline);
2653: if ($plain ne '') { $prp{$short}=$plain; }
2654: }
2655: }
2656: }
2657:
2658: # ---------------------------------------------------------- Read package table
2659: {
2660: my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
2661:
2662: while (my $configline=<$config>) {
2663: chomp($configline);
2664: my ($short,$plain)=split(/:/,$configline);
2665: my ($pack,$name)=split(/\&/,$short);
2666: if ($plain ne '') {
2667: $packagetab{$pack.'&'.$name.'&name'}=$name;
2668: $packagetab{$short}=$plain;
2669: }
2670: }
2671: }
2672:
2673: %metacache=();
2674:
2675: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
2676: $dumpcount=0;
2677:
2678: &logtouch();
2679: &logthis('<font color=yellow>INFO: Read configuration</font>');
2680: $readit=1;
2681: }
2682: }
2683:
2684: 1;
2685: __END__
2686:
2687: =head1 NAME
2688:
2689: Apache::lonnet - TCP networking package
2690:
2691: =head1 SYNOPSIS
2692:
2693: Invoked by other LON-CAPA modules.
2694:
2695: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
2696:
2697: =head1 INTRODUCTION
2698:
2699: This module provides subroutines which interact with the
2700: lonc/lond (TCP) network layer of LON-CAPA.
2701:
2702: This is part of the LearningOnline Network with CAPA project
2703: described at http://www.lon-capa.org.
2704:
2705: =head1 HANDLER SUBROUTINE
2706:
2707: There is no handler routine for this module.
2708:
2709: =head1 OTHER SUBROUTINES
2710:
2711: =over 4
2712:
2713: =item *
2714:
2715: logtouch() : make sure the logfile, lonnet.log, exists
2716:
2717: =item *
2718:
2719: logthis() : append message to lonnet.log
2720:
2721: =item *
2722:
2723: logperm() : append a permanent message to lonnet.perm.log
2724:
2725: =item *
2726:
2727: subreply() : non-critical communication, called by &reply
2728:
2729: =item *
2730:
2731: reply() : makes two attempts to pass message; logs refusals and rejections
2732:
2733: =item *
2734:
2735: reconlonc() : tries to reconnect lonc client processes.
2736:
2737: =item *
2738:
2739: critical() : passes a critical message to another server; if cannot get
2740: through then place message in connection buffer
2741:
2742: =item *
2743:
2744: appenv(%hash) : read in current user environment, append new environment
2745: values to make new user environment
2746:
2747: =item *
2748:
2749: delenv($varname) : read in current user environment, remove all values
2750: beginning with $varname, write new user environment (note: flock is used
2751: to prevent conflicting shared read/writes with file)
2752:
2753: =item *
2754:
2755: spareserver() : find server with least workload from spare.tab
2756:
2757: =item *
2758:
2759: queryauthenticate($uname,$udom) : try to determine user's current
2760: authentication scheme
2761:
2762: =item *
2763:
2764: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
2765: servers (first use the current one)
2766:
2767: =item *
2768:
2769: homeserver($uname,$udom) : find the homebase for a user from domain's lib
2770: servers
2771:
2772: =item *
2773:
2774: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
2775: id=>name,id=>name)
2776:
2777: =item *
2778:
2779: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
2780: name=>id,name=>id)
2781:
2782: =item *
2783:
2784: idput($udom,%ids) : store away a list of names and associated IDs
2785:
2786: =item *
2787:
2788: usection($domain,$user,$courseid) : output of section name/number or '' for
2789: "not in course" and '-1' for "no section"
2790:
2791: =item *
2792:
2793: userenvironment($domain,$user,$what) : puts out any environment parameter
2794: for a user
2795:
2796: =item *
2797:
2798: subscribe($fname) : subscribe to a resource, return URL if possible
2799:
2800: =item *
2801:
2802: repcopy($filename) : replicate file
2803:
2804: =item *
2805:
2806: ssi($url,%hash) : server side include, does a complete request cycle on url to
2807: localhost, posts hash
2808:
2809: =item *
2810:
2811: log($domain,$name,$home,$message) : write to permanent log for user; use
2812: critical subroutine
2813:
2814: =item *
2815:
2816: flushcourselogs() : flush (save) buffer logs and access logs
2817:
2818: =item *
2819:
2820: courselog($what) : save message for course in hash
2821:
2822: =item *
2823:
2824: courseacclog($what) : save message for course using &courselog(). Perform
2825: special processing for specific resource types (problems, exams, quizzes, etc).
2826:
2827: =item *
2828:
2829: countacc($url) : count the number of accesses to a given URL
2830:
2831: =item *
2832:
2833: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
2834:
2835: =item *
2836:
2837: sub checkin($token) : check in an item
2838:
2839: =item *
2840:
2841: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
2842:
2843: =item *
2844:
2845: devalidate($symb) : devalidate spreadsheets
2846:
2847: =item *
2848:
2849: hash2str(%hash) : convert a hash into a string complete with escaping and '='
2850: and '&' separators
2851:
2852: =item *
2853:
2854: str2hash($string) : convert string to hash using unescaping and splitting on
2855: '=' and '&'
2856:
2857: =item *
2858:
2859: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
2860:
2861: =item *
2862:
2863: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
2864:
2865: =item *
2866:
2867: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
2868: for this url; hashref needs to be given and should be a \%hashname; the
2869: remaining args aren't required and if they aren't passed or are '' they will
2870: be derived from the ENV
2871:
2872: =item *
2873:
2874: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
2875: uses critical subroutine
2876:
2877: =item *
2878:
2879: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
2880: all args are optional
2881:
2882: =item *
2883:
2884: coursedescription($courseid) : course description
2885:
2886: =item *
2887:
2888: rolesinit($domain,$username,$authhost) : get user privileges
2889:
2890: =item *
2891:
2892: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
2893: reference filled in from namesp ($udomain and $uname are optional)
2894:
2895: =item *
2896:
2897: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
2898: namesp ($udomain and $uname are optional)
2899:
2900: =item *
2901:
2902: dump($namespace,$udomain,$uname,$regexp) :
2903: dumps the complete (or key matching regexp) namespace into a hash
2904: ($udomain, $uname and $regexp are optional)
2905:
2906: =item *
2907:
2908: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
2909: ($udomain and $uname are optional)
2910:
2911: =item *
2912:
2913: cput($namespace,$storehash,$udomain,$uname) : critical put
2914: ($udomain and $uname are optional)
2915:
2916: =item *
2917:
2918: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
2919: reference filled in from namesp (encrypts the return communication)
2920: ($udomain and $uname are optional)
2921:
2922: =item *
2923:
2924: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
2925: actions
2926: F: full access
2927: U,I,K: authentication modes (cxx only)
2928: '': forbidden
2929: 1: user needs to choose course
2930: 2: browse allowed
2931:
2932: =item *
2933:
2934: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
2935: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
2936: and course level
2937:
2938: =item *
2939:
2940: metadata_query($query,$custom,$customshow) : make a metadata query against the
2941: network of library servers; returns file handle of where SQL and regex results
2942: will be stored for query
2943:
2944: =item *
2945:
2946: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
2947: explanation of a user role term
2948:
2949: =item *
2950:
2951: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
2952: user for the level given by URL. Optional start and end dates (leave empty
2953: string or zero for "no date")
2954:
2955: =item *
2956:
2957: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
2958:
2959: =item *
2960:
2961: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
2962: modify user
2963:
2964: =item *
2965:
2966: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
2967: $end,$start) : modify student
2968:
2969: =item *
2970:
2971: writecoursepref($courseid,%prefs) : write preferences for a course
2972:
2973: =item *
2974:
2975: createcourse($udom,$description,$url) : make/modify course
2976:
2977: =item *
2978:
2979: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
2980: custom role; give a custom role to a user for the level given by URL. Specify
2981: name and domain of role author, and role name
2982:
2983: =item *
2984:
2985: revokerole($udom,$uname,$url,$role) : revoke a role for url
2986:
2987: =item *
2988:
2989: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
2990:
2991: =item *
2992:
2993: dirlist($uri) : return directory list based on URI
2994:
2995: =item *
2996:
2997: directcondval($number) : get current value of a condition; reads from a state
2998: string
2999:
3000: =item *
3001:
3002: condval($condidx) : value of condition index based on state
3003:
3004: =item *
3005:
3006: EXT($varname,$symbparm) : value of a variable
3007:
3008: =item *
3009:
3010: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
3011: metadata entry for a file; entry='keys', returns a comma separated list of keys
3012:
3013: =item *
3014:
3015: symblist($mapname,%newhash) : update symbolic storage links
3016:
3017: =item *
3018:
3019: symbread($filename) : return symbolic list entry (filename argument optional);
3020: returns the data handle
3021:
3022: =item *
3023:
3024: numval($salt) : return random seed value (addend for rndseed)
3025:
3026: =item *
3027:
3028: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
3029: a random seed, all arguments are optional, if they aren't sent it uses the
3030: environment to derive them. Note: if symb isn't sent and it can't get one
3031: from &symbread it will use the current time as its return value
3032:
3033: =item *
3034:
3035: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
3036: unfakeable, receipt
3037:
3038: =item *
3039:
3040: receipt() : API to ireceipt working off of ENV values; given out to users
3041:
3042: =item *
3043:
3044: getfile($file) : serves up a file, returns the contents of a file or -1;
3045: replicates and subscribes to the file
3046:
3047: =item *
3048:
3049: filelocation($dir,$file) : returns file system location of a file based on URI;
3050: meant to be "fairly clean" absolute reference
3051:
3052: =item *
3053:
3054: hreflocation($dir,$file) : returns file system location or a URL; same as
3055: filelocation except for hrefs
3056:
3057: =item *
3058:
3059: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
3060:
3061: =item *
3062:
3063: escape() : unpack non-word characters into CGI-compatible hex codes
3064:
3065: =item *
3066:
3067: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
3068:
3069: =item *
3070:
3071: goodbye() : flush course logs and log shutting down; it is called in srm.conf
3072: as a PerlChildExitHandler
3073:
3074: =back
3075:
3076: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>