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