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