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