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