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