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