1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.413 2003/09/16 17:54:50 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: my ($name,$ext)=($filename=~/^(.+)\.(\w+)$/);
2610: $ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
2611: /\&(\Q$name\E\.\d+\.$ext)\:([\d\|]+)\&/;
2612: return (0,$2,$pathname.'/'.$1);
2613: }
2614: }
2615:
2616: # ----------------------------------------------------------------- Define Role
2617:
2618: sub definerole {
2619: if (allowed('mcr','/')) {
2620: my ($rolename,$sysrole,$domrole,$courole)=@_;
2621: foreach (split(':',$sysrole)) {
2622: my ($crole,$cqual)=split(/\&/,$_);
2623: if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
2624: if ($pr{'cr:s'}=~/$crole\&/) {
2625: if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) {
2626: return "refused:s:$crole&$cqual";
2627: }
2628: }
2629: }
2630: foreach (split(':',$domrole)) {
2631: my ($crole,$cqual)=split(/\&/,$_);
2632: if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
2633: if ($pr{'cr:d'}=~/$crole\&/) {
2634: if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) {
2635: return "refused:d:$crole&$cqual";
2636: }
2637: }
2638: }
2639: foreach (split(':',$courole)) {
2640: my ($crole,$cqual)=split(/\&/,$_);
2641: if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
2642: if ($pr{'cr:c'}=~/$crole\&/) {
2643: if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) {
2644: return "refused:c:$crole&$cqual";
2645: }
2646: }
2647: }
2648: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2649: "$ENV{'user.domain'}:$ENV{'user.name'}:".
2650: "rolesdef_$rolename=".
2651: escape($sysrole.'_'.$domrole.'_'.$courole);
2652: return reply($command,$ENV{'user.home'});
2653: } else {
2654: return 'refused';
2655: }
2656: }
2657:
2658: # ---------------- Make a metadata query against the network of library servers
2659:
2660: sub metadata_query {
2661: my ($query,$custom,$customshow,$server_array)=@_;
2662: my %rhash;
2663: my @server_list = (defined($server_array) ? @$server_array
2664: : keys(%libserv) );
2665: for my $server (@server_list) {
2666: unless ($custom or $customshow) {
2667: my $reply=&reply("querysend:".&escape($query),$server);
2668: $rhash{$server}=$reply;
2669: }
2670: else {
2671: my $reply=&reply("querysend:".&escape($query).':'.
2672: &escape($custom).':'.&escape($customshow),
2673: $server);
2674: $rhash{$server}=$reply;
2675: }
2676: }
2677: return \%rhash;
2678: }
2679:
2680: # ----------------------------------------- Send log queries and wait for reply
2681:
2682: sub log_query {
2683: my ($uname,$udom,$query,%filters)=@_;
2684: my $uhome=&homeserver($uname,$udom);
2685: if ($uhome eq 'no_host') { return 'error: no_host'; }
2686: my $uhost=$hostname{$uhome};
2687: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
2688: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
2689: $uhome);
2690: unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
2691: return get_query_reply($queryid);
2692: }
2693:
2694: sub get_query_reply {
2695: my $queryid=shift;
2696: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
2697: my $reply='';
2698: for (1..100) {
2699: sleep 2;
2700: if (-e $replyfile.'.end') {
2701: if (my $fh=Apache::File->new($replyfile)) {
2702: $reply.=<$fh>;
2703: $fh->close;
2704: } else { return 'error: reply_file_error'; }
2705: return &unescape($reply);
2706: }
2707: }
2708: return 'timeout:'.$queryid;
2709: }
2710:
2711: sub courselog_query {
2712: #
2713: # possible filters:
2714: # url: url or symb
2715: # username
2716: # domain
2717: # action: view, submit, grade
2718: # start: timestamp
2719: # end: timestamp
2720: #
2721: my (%filters)=@_;
2722: unless ($ENV{'request.course.id'}) { return 'no_course'; }
2723: if ($filters{'url'}) {
2724: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
2725: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
2726: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
2727: }
2728: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
2729: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
2730: return &log_query($cname,$cdom,'courselog',%filters);
2731: }
2732:
2733: sub userlog_query {
2734: my ($uname,$udom,%filters)=@_;
2735: return &log_query($uname,$udom,'userlog',%filters);
2736: }
2737:
2738: # ------------------------------------------------------------------ Plain Text
2739:
2740: sub plaintext {
2741: my $short=shift;
2742: return $prp{$short};
2743: }
2744:
2745: # ----------------------------------------------------------------- Assign Role
2746:
2747: sub assignrole {
2748: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
2749: my $mrole;
2750: if ($role =~ /^cr\//) {
2751: my $cwosec=$url;
2752: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
2753: unless (&allowed('ccr',$cwosec)) {
2754: &logthis('Refused custom assignrole: '.
2755: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2756: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2757: return 'refused';
2758: }
2759: $mrole='cr';
2760: } else {
2761: my $cwosec=$url;
2762: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
2763: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
2764: &logthis('Refused assignrole: '.
2765: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2766: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2767: return 'refused';
2768: }
2769: $mrole=$role;
2770: }
2771: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2772: "$udom:$uname:$url".'_'."$mrole=$role";
2773: if ($end) { $command.='_'.$end; }
2774: if ($start) {
2775: if ($end) {
2776: $command.='_'.$start;
2777: } else {
2778: $command.='_0_'.$start;
2779: }
2780: }
2781: # actually delete
2782: if ($deleteflag) {
2783: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
2784: # modify command to delete the role
2785: $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
2786: "$udom:$uname:$url".'_'."$mrole";
2787: &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom");
2788: # set start and finish to negative values for userrolelog
2789: $start=-1;
2790: $end=-1;
2791: }
2792: }
2793: # send command
2794: my $answer=&reply($command,&homeserver($uname,$udom));
2795: # log new user role if status is ok
2796: if ($answer eq 'ok') {
2797: &userrolelog($mrole,$uname,$udom,$url,$start,$end);
2798: }
2799: return $answer;
2800: }
2801:
2802: # -------------------------------------------------- Modify user authentication
2803: # Overrides without validation
2804:
2805: sub modifyuserauth {
2806: my ($udom,$uname,$umode,$upass)=@_;
2807: my $uhome=&homeserver($uname,$udom);
2808: unless (&allowed('mau',$udom)) { return 'refused'; }
2809: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
2810: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
2811: ' in domain '.$ENV{'request.role.domain'});
2812: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
2813: &escape($upass),$uhome);
2814: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
2815: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
2816: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
2817: &log($udom,,$uname,$uhome,
2818: 'Authentication changed by '.$ENV{'user.domain'}.', '.
2819: $ENV{'user.name'}.', '.$umode.
2820: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
2821: unless ($reply eq 'ok') {
2822: &logthis('Authentication mode error: '.$reply);
2823: return 'error: '.$reply;
2824: }
2825: return 'ok';
2826: }
2827:
2828: # --------------------------------------------------------------- Modify a user
2829:
2830: sub modifyuser {
2831: my ($udom, $uname, $uid,
2832: $umode, $upass, $first,
2833: $middle, $last, $gene,
2834: $forceid, $desiredhome, $email)=@_;
2835: $udom=~s/\W//g;
2836: $uname=~s/\W//g;
2837: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
2838: $umode.', '.$first.', '.$middle.', '.
2839: $last.', '.$gene.'(forceid: '.$forceid.')'.
2840: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
2841: ' desiredhome not specified').
2842: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
2843: ' in domain '.$ENV{'request.role.domain'});
2844: my $uhome=&homeserver($uname,$udom,'true');
2845: # ----------------------------------------------------------------- Create User
2846: if (($uhome eq 'no_host') &&
2847: (($umode && $upass) || ($umode eq 'localauth'))) {
2848: my $unhome='';
2849: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
2850: $unhome = $desiredhome;
2851: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
2852: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
2853: } else { # load balancing routine for determining $unhome
2854: my $tryserver;
2855: my $loadm=10000000;
2856: foreach $tryserver (keys %libserv) {
2857: if ($hostdom{$tryserver} eq $udom) {
2858: my $answer=reply('load',$tryserver);
2859: if (($answer=~/\d+/) && ($answer<$loadm)) {
2860: $loadm=$answer;
2861: $unhome=$tryserver;
2862: }
2863: }
2864: }
2865: }
2866: if (($unhome eq '') || ($unhome eq 'no_host')) {
2867: return 'error: unable to find a home server for '.$uname.
2868: ' in domain '.$udom;
2869: }
2870: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
2871: &escape($upass),$unhome);
2872: unless ($reply eq 'ok') {
2873: return 'error: '.$reply;
2874: }
2875: $uhome=&homeserver($uname,$udom,'true');
2876: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
2877: return 'error: unable verify users home machine.';
2878: }
2879: } # End of creation of new user
2880: # ---------------------------------------------------------------------- Add ID
2881: if ($uid) {
2882: $uid=~tr/A-Z/a-z/;
2883: my %uidhash=&idrget($udom,$uname);
2884: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
2885: && (!$forceid)) {
2886: unless ($uid eq $uidhash{$uname}) {
2887: return 'error: user id "'.$uid.'" does not match '.
2888: 'current user id "'.$uidhash{$uname}.'".';
2889: }
2890: } else {
2891: &idput($udom,($uname => $uid));
2892: }
2893: }
2894: # -------------------------------------------------------------- Add names, etc
2895: my @tmp=&get('environment',
2896: ['firstname','middlename','lastname','generation'],
2897: $udom,$uname);
2898: my %names;
2899: if ($tmp[0] =~ m/^error:.*/) {
2900: %names=();
2901: } else {
2902: %names = @tmp;
2903: }
2904: #
2905: # Make sure to not trash student environment if instructor does not bother
2906: # to supply name and email information
2907: #
2908: if ($first) { $names{'firstname'} = $first; }
2909: if (defined($middle)) { $names{'middlename'} = $middle; }
2910: if ($last) { $names{'lastname'} = $last; }
2911: if (defined($gene)) { $names{'generation'} = $gene; }
2912: if ($email) { $names{'notification'} = $email;
2913: $names{'critnotification'} = $email; }
2914:
2915: my $reply = &put('environment', \%names, $udom,$uname);
2916: if ($reply ne 'ok') { return 'error: '.$reply; }
2917: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
2918: $umode.', '.$first.', '.$middle.', '.
2919: $last.', '.$gene.' by '.
2920: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2921: return 'ok';
2922: }
2923:
2924: # -------------------------------------------------------------- Modify student
2925:
2926: sub modifystudent {
2927: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
2928: $end,$start,$forceid,$desiredhome,$email)=@_;
2929: my $cid='';
2930: unless ($cid=$ENV{'request.course.id'}) {
2931: return 'not_in_class';
2932: }
2933: # --------------------------------------------------------------- Make the user
2934: my $reply=&modifyuser
2935: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
2936: $desiredhome,$email);
2937: unless ($reply eq 'ok') { return $reply; }
2938: # This will cause &modify_student_enrollment to get the uid from the
2939: # students environment
2940: $uid = undef if (!$forceid);
2941: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
2942: $last,$gene,$usec,$end,$start);
2943: return $reply;
2944: }
2945:
2946: sub modify_student_enrollment {
2947: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
2948: # Get the course id from the environment
2949: my $cid='';
2950: unless ($cid=$ENV{'request.course.id'}) {
2951: return 'not_in_class';
2952: }
2953: # Make sure the user exists
2954: my $uhome=&homeserver($uname,$udom);
2955: if (($uhome eq '') || ($uhome eq 'no_host')) {
2956: return 'error: no such user';
2957: }
2958: #
2959: # Get student data if we were not given enough information
2960: if (!defined($first) || $first eq '' ||
2961: !defined($last) || $last eq '' ||
2962: !defined($uid) || $uid eq '' ||
2963: !defined($middle) || $middle eq '' ||
2964: !defined($gene) || $gene eq '') {
2965: # They did not supply us with enough data to enroll the student, so
2966: # we need to pick up more information.
2967: my %tmp = &get('environment',
2968: ['firstname','middlename','lastname', 'generation','id']
2969: ,$udom,$uname);
2970:
2971: foreach (keys(%tmp)) {
2972: &logthis("key $_ = ".$tmp{$_});
2973: }
2974: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
2975: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
2976: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
2977: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
2978: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
2979: }
2980: my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
2981: $first,$middle);
2982: my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
2983: $ENV{'course.'.$cid.'.num'}.':classlist:'.
2984: &escape($uname.':'.$udom).'='.
2985: &escape(join(':',$end,$start,$uid,$usec,$fullname)),
2986: $ENV{'course.'.$cid.'.home'});
2987: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
2988: return 'error: '.$reply;
2989: }
2990: # Add student role to user
2991: my $uurl='/'.$cid;
2992: $uurl=~s/\_/\//g;
2993: if ($usec) {
2994: $uurl.='/'.$usec;
2995: }
2996: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
2997: }
2998:
2999: # ------------------------------------------------- Write to course preferences
3000:
3001: sub writecoursepref {
3002: my ($courseid,%prefs)=@_;
3003: $courseid=~s/^\///;
3004: $courseid=~s/\_/\//g;
3005: my ($cdomain,$cnum)=split(/\//,$courseid);
3006: my $chome=homeserver($cnum,$cdomain);
3007: if (($chome eq '') || ($chome eq 'no_host')) {
3008: return 'error: no such course';
3009: }
3010: my $cstring='';
3011: foreach (keys %prefs) {
3012: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
3013: }
3014: $cstring=~s/\&$//;
3015: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3016: }
3017:
3018: # ---------------------------------------------------------- Make/modify course
3019:
3020: sub createcourse {
3021: my ($udom,$description,$url,$course_server,$nonstandard)=@_;
3022: $url=&declutter($url);
3023: my $cid='';
3024: unless (&allowed('ccc',$udom)) {
3025: return 'refused';
3026: }
3027: # ------------------------------------------------------------------- Create ID
3028: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3029: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3030: # ----------------------------------------------- Make sure that does not exist
3031: my $uhome=&homeserver($uname,$udom,'true');
3032: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3033: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3034: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3035: $uhome=&homeserver($uname,$udom,'true');
3036: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3037: return 'error: unable to generate unique course-ID';
3038: }
3039: }
3040: # ------------------------------------------------ Check supplied server name
3041: $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
3042: if (! exists($libserv{$course_server})) {
3043: return 'error:bad server name '.$course_server;
3044: }
3045: # ------------------------------------------------------------- Make the course
3046: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
3047: $course_server);
3048: unless ($reply eq 'ok') { return 'error: '.$reply; }
3049: $uhome=&homeserver($uname,$udom,'true');
3050: if (($uhome eq '') || ($uhome eq 'no_host')) {
3051: return 'error: no such course';
3052: }
3053: # ----------------------------------------------------------------- Course made
3054: # log existance
3055: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
3056: $uhome);
3057: &flushcourselogs();
3058: # set toplevel url
3059: my $topurl=$url;
3060: unless ($nonstandard) {
3061: # ------------------------------------------ For standard courses, make top url
3062: my $mapurl=&clutter($url);
3063: if ($mapurl eq '/res/') { $mapurl=''; }
3064: $ENV{'form.initmap'}=(<<ENDINITMAP);
3065: <map>
3066: <resource id="1" type="start"></resource>
3067: <resource id="2" src="$mapurl"></resource>
3068: <resource id="3" type="finish"></resource>
3069: <link index="1" from="1" to="2"></link>
3070: <link index="2" from="2" to="3"></link>
3071: </map>
3072: ENDINITMAP
3073: $topurl=&declutter(
3074: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
3075: );
3076: }
3077: # ----------------------------------------------------------- Write preferences
3078: &writecoursepref($udom.'_'.$uname,
3079: ('description' => $description,
3080: 'url' => $topurl));
3081: return '/'.$udom.'/'.$uname;
3082: }
3083:
3084: # ---------------------------------------------------------- Assign Custom Role
3085:
3086: sub assigncustomrole {
3087: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
3088: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
3089: $end,$start,$deleteflag);
3090: }
3091:
3092: # ----------------------------------------------------------------- Revoke Role
3093:
3094: sub revokerole {
3095: my ($udom,$uname,$url,$role,$deleteflag)=@_;
3096: my $now=time;
3097: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
3098: }
3099:
3100: # ---------------------------------------------------------- Revoke Custom Role
3101:
3102: sub revokecustomrole {
3103: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
3104: my $now=time;
3105: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
3106: $deleteflag);
3107: }
3108:
3109: # ------------------------------------------------------------ Directory lister
3110:
3111: sub dirlist {
3112: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
3113:
3114: $uri=~s/^\///;
3115: $uri=~s/\/$//;
3116: my ($udom, $uname);
3117: (undef,$udom,$uname)=split(/\//,$uri);
3118: if(defined($userdomain)) {
3119: $udom = $userdomain;
3120: }
3121: if(defined($username)) {
3122: $uname = $username;
3123: }
3124:
3125: my $dirRoot = $perlvar{'lonDocRoot'};
3126: if(defined($alternateDirectoryRoot)) {
3127: $dirRoot = $alternateDirectoryRoot;
3128: $dirRoot =~ s/\/$//;
3129: }
3130:
3131: if($udom) {
3132: if($uname) {
3133: my $listing=reply('ls:'.$dirRoot.'/'.$uri,
3134: homeserver($uname,$udom));
3135: return split(/:/,$listing);
3136: } elsif(!defined($alternateDirectoryRoot)) {
3137: my $tryserver;
3138: my %allusers=();
3139: foreach $tryserver (keys %libserv) {
3140: if($hostdom{$tryserver} eq $udom) {
3141: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
3142: $udom, $tryserver);
3143: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
3144: && ($listing ne 'con_lost')) {
3145: foreach (split(/:/,$listing)) {
3146: my ($entry,@stat)=split(/&/,$_);
3147: $allusers{$entry}=1;
3148: }
3149: }
3150: }
3151: }
3152: my $alluserstr='';
3153: foreach (sort keys %allusers) {
3154: $alluserstr.=$_.'&user:';
3155: }
3156: $alluserstr=~s/:$//;
3157: return split(/:/,$alluserstr);
3158: } else {
3159: my @emptyResults = ();
3160: push(@emptyResults, 'missing user name');
3161: return split(':',@emptyResults);
3162: }
3163: } elsif(!defined($alternateDirectoryRoot)) {
3164: my $tryserver;
3165: my %alldom=();
3166: foreach $tryserver (keys %libserv) {
3167: $alldom{$hostdom{$tryserver}}=1;
3168: }
3169: my $alldomstr='';
3170: foreach (sort keys %alldom) {
3171: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
3172: }
3173: $alldomstr=~s/:$//;
3174: return split(/:/,$alldomstr);
3175: } else {
3176: my @emptyResults = ();
3177: push(@emptyResults, 'missing domain');
3178: return split(':',@emptyResults);
3179: }
3180: }
3181:
3182: # --------------------------------------------- GetFileTimestamp
3183: # This function utilizes dirlist and returns the date stamp for
3184: # when it was last modified. It will also return an error of -1
3185: # if an error occurs
3186:
3187: ##
3188: ## FIXME: This subroutine assumes its caller knows something about the
3189: ## directory structure of the home server for the student ($root).
3190: ## Not a good assumption to make. Since this is for looking up files
3191: ## in user directories, the full path should be constructed by lond, not
3192: ## whatever machine we request data from.
3193: ##
3194: sub GetFileTimestamp {
3195: my ($studentDomain,$studentName,$filename,$root)=@_;
3196: $studentDomain=~s/\W//g;
3197: $studentName=~s/\W//g;
3198: my $subdir=$studentName.'__';
3199: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3200: my $proname="$studentDomain/$subdir/$studentName";
3201: $proname .= '/'.$filename;
3202: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
3203: $studentName, $root);
3204: my @stats = split('&', $fileStat);
3205: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
3206: # @stats contains first the filename, then the stat output
3207: return $stats[10]; # so this is 10 instead of 9.
3208: } else {
3209: return -1;
3210: }
3211: }
3212:
3213: # -------------------------------------------------------- Value of a Condition
3214:
3215: sub directcondval {
3216: my $number=shift;
3217: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
3218: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
3219: } else {
3220: return 2;
3221: }
3222: }
3223:
3224: sub condval {
3225: my $condidx=shift;
3226: my $result=0;
3227: my $allpathcond='';
3228: foreach (split(/\|/,$condidx)) {
3229: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
3230: $allpathcond.=
3231: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
3232: }
3233: }
3234: $allpathcond=~s/\|$//;
3235: if ($ENV{'request.course.id'}) {
3236: if ($allpathcond) {
3237: my $operand='|';
3238: my @stack;
3239: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
3240: if ($_ eq '(') {
3241: push @stack,($operand,$result)
3242: } elsif ($_ eq ')') {
3243: my $before=pop @stack;
3244: if (pop @stack eq '&') {
3245: $result=$result>$before?$before:$result;
3246: } else {
3247: $result=$result>$before?$result:$before;
3248: }
3249: } elsif (($_ eq '&') || ($_ eq '|')) {
3250: $operand=$_;
3251: } else {
3252: my $new=directcondval($_);
3253: if ($operand eq '&') {
3254: $result=$result>$new?$new:$result;
3255: } else {
3256: $result=$result>$new?$result:$new;
3257: }
3258: }
3259: }
3260: }
3261: }
3262: return $result;
3263: }
3264:
3265: # ---------------------------------------------------- Devalidate courseresdata
3266:
3267: sub devalidatecourseresdata {
3268: my ($coursenum,$coursedomain)=@_;
3269: my $hashid=$coursenum.':'.$coursedomain;
3270: delete $courseresdatacache{$hashid.'.time'};
3271: }
3272:
3273: # --------------------------------------------------- Course Resourcedata Query
3274:
3275: sub courseresdata {
3276: my ($coursenum,$coursedomain,@which)=@_;
3277: my $coursehom=&homeserver($coursenum,$coursedomain);
3278: my $hashid=$coursenum.':'.$coursedomain;
3279: my $dodump=0;
3280: if (!defined($courseresdatacache{$hashid.'.time'})) {
3281: $dodump=1;
3282: } else {
3283: if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
3284: }
3285: if ($dodump) {
3286: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
3287: my ($tmp) = keys(%dumpreply);
3288: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
3289: $courseresdatacache{$hashid.'.time'}=time;
3290: $courseresdatacache{$hashid}=\%dumpreply;
3291: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
3292: return $tmp;
3293: }
3294: }
3295: foreach my $item (@which) {
3296: if (defined($courseresdatacache{$hashid}->{$item})) {
3297: return $courseresdatacache{$hashid}->{$item};
3298: }
3299: }
3300: return undef;
3301: }
3302:
3303: #
3304: # EXT resource caching routines
3305: #
3306:
3307: sub clear_EXT_cache_status {
3308: &delenv('cache.EXT.');
3309: }
3310:
3311: sub EXT_cache_status {
3312: my ($target_domain,$target_user) = @_;
3313: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
3314: if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
3315: # We know already the user has no data
3316: return 1;
3317: } else {
3318: return 0;
3319: }
3320: }
3321:
3322: sub EXT_cache_set {
3323: my ($target_domain,$target_user) = @_;
3324: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
3325: &appenv($cachename => time);
3326: }
3327:
3328: # --------------------------------------------------------- Value of a Variable
3329: sub EXT {
3330: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
3331:
3332: unless ($varname) { return ''; }
3333: #get real user name/domain, courseid and symb
3334: my $courseid;
3335: my $publicuser;
3336: if (!($uname && $udom)) {
3337: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
3338: &Apache::lonxml::whichuser($symbparm);
3339: if (!$symbparm) { $symbparm=$cursymb; }
3340: } else {
3341: $courseid=$ENV{'request.course.id'};
3342: }
3343: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
3344: my $rest;
3345: if (defined($therest[0])) {
3346: $rest=join('.',@therest);
3347: } else {
3348: $rest='';
3349: }
3350:
3351: my $qualifierrest=$qualifier;
3352: if ($rest) { $qualifierrest.='.'.$rest; }
3353: my $spacequalifierrest=$space;
3354: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
3355: if ($realm eq 'user') {
3356: # --------------------------------------------------------------- user.resource
3357: if ($space eq 'resource') {
3358: if (defined($Apache::lonhomework::parsing_a_problem)) {
3359: return $Apache::lonhomework::history{$qualifierrest};
3360: } else {
3361: my %restored;
3362: if ($publicuser || $ENV{'request.state'} eq 'construct') {
3363: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
3364: } else {
3365: %restored=&restore($symbparm,$courseid,$udom,$uname);
3366: }
3367: return $restored{$qualifierrest};
3368: }
3369: # ----------------------------------------------------------------- user.access
3370: } elsif ($space eq 'access') {
3371: # FIXME - not supporting calls for a specific user
3372: return &allowed($qualifier,$rest);
3373: # ------------------------------------------ user.preferences, user.environment
3374: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
3375: if (($uname eq $ENV{'user.name'}) &&
3376: ($udom eq $ENV{'user.domain'})) {
3377: return $ENV{join('.',('environment',$qualifierrest))};
3378: } else {
3379: my %returnhash;
3380: if (!$publicuser) {
3381: %returnhash=&userenvironment($udom,$uname,
3382: $qualifierrest);
3383: }
3384: return $returnhash{$qualifierrest};
3385: }
3386: # ----------------------------------------------------------------- user.course
3387: } elsif ($space eq 'course') {
3388: # FIXME - not supporting calls for a specific user
3389: return $ENV{join('.',('request.course',$qualifier))};
3390: # ------------------------------------------------------------------- user.role
3391: } elsif ($space eq 'role') {
3392: # FIXME - not supporting calls for a specific user
3393: my ($role,$where)=split(/\./,$ENV{'request.role'});
3394: if ($qualifier eq 'value') {
3395: return $role;
3396: } elsif ($qualifier eq 'extent') {
3397: return $where;
3398: }
3399: # ----------------------------------------------------------------- user.domain
3400: } elsif ($space eq 'domain') {
3401: return $udom;
3402: # ------------------------------------------------------------------- user.name
3403: } elsif ($space eq 'name') {
3404: return $uname;
3405: # ---------------------------------------------------- Any other user namespace
3406: } else {
3407: my %reply;
3408: if (!$publicuser) {
3409: %reply=&get($space,[$qualifierrest],$udom,$uname);
3410: }
3411: return $reply{$qualifierrest};
3412: }
3413: } elsif ($realm eq 'query') {
3414: # ---------------------------------------------- pull stuff out of query string
3415: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
3416: [$spacequalifierrest]);
3417: return $ENV{'form.'.$spacequalifierrest};
3418: } elsif ($realm eq 'request') {
3419: # ------------------------------------------------------------- request.browser
3420: if ($space eq 'browser') {
3421: return $ENV{'browser.'.$qualifier};
3422: # ------------------------------------------------------------ request.filename
3423: } else {
3424: return $ENV{'request.'.$spacequalifierrest};
3425: }
3426: } elsif ($realm eq 'course') {
3427: # ---------------------------------------------------------- course.description
3428: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
3429: } elsif ($realm eq 'resource') {
3430:
3431: my $section;
3432: if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
3433:
3434: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
3435:
3436: # ----------------------------------------------------- Cascading lookup scheme
3437: if (!$symbparm) { $symbparm=&symbread(); }
3438: my $symbp=$symbparm;
3439: my $mapp=(&decode_symb($symbp))[0];
3440:
3441: my $symbparm=$symbp.'.'.$spacequalifierrest;
3442: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
3443:
3444: if (($ENV{'user.name'} eq $uname) &&
3445: ($ENV{'user.domain'} eq $udom)) {
3446: $section=$ENV{'request.course.sec'};
3447: } else {
3448: if (! defined($usection)) {
3449: $section=&usection($udom,$uname,$courseid);
3450: } else {
3451: $section = $usection;
3452: }
3453: }
3454:
3455: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
3456: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
3457: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
3458:
3459: my $courselevel=$courseid.'.'.$spacequalifierrest;
3460: my $courselevelr=$courseid.'.'.$symbparm;
3461: my $courselevelm=$courseid.'.'.$mapparm;
3462:
3463: # ----------------------------------------------------------- first, check user
3464: #most student don\'t have any data set, check if there is some data
3465: #every thirty minutes
3466: if (! &EXT_cache_status($udom,$uname)) {
3467: my %resourcedata=&get('resourcedata',
3468: [$courselevelr,$courselevelm,$courselevel],
3469: $udom,$uname);
3470: my ($tmp)=keys(%resourcedata);
3471: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
3472: if ($resourcedata{$courselevelr}) {
3473: return $resourcedata{$courselevelr}; }
3474: if ($resourcedata{$courselevelm}) {
3475: return $resourcedata{$courselevelm}; }
3476: if ($resourcedata{$courselevel}) {
3477: return $resourcedata{$courselevel}; }
3478: } else {
3479: if ($tmp!~/No such file/) {
3480: &logthis("<font color=blue>WARNING:".
3481: " Trying to get resource data for ".
3482: $uname." at ".$udom.": ".
3483: $tmp."</font>");
3484: } elsif ($tmp=~/error:No such file/) {
3485: &EXT_cache_set($udom,$uname);
3486: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
3487: return $tmp;
3488: }
3489: }
3490: }
3491:
3492: # -------------------------------------------------------- second, check course
3493:
3494: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
3495: $ENV{'course.'.$courseid.'.domain'},
3496: ($seclevelr,$seclevelm,$seclevel,
3497: $courselevelr,$courselevelm,
3498: $courselevel));
3499: if (defined($coursereply)) { return $coursereply; }
3500:
3501: # ------------------------------------------------------ third, check map parms
3502: my %parmhash=();
3503: my $thisparm='';
3504: if (tie(%parmhash,'GDBM_File',
3505: $ENV{'request.course.fn'}.'_parms.db',
3506: &GDBM_READER(),0640)) {
3507: $thisparm=$parmhash{$symbparm};
3508: untie(%parmhash);
3509: }
3510: if ($thisparm) { return $thisparm; }
3511: }
3512: # --------------------------------------------- last, look in resource metadata
3513:
3514: $spacequalifierrest=~s/\./\_/;
3515: my $filename;
3516: if (!$symbparm) { $symbparm=&symbread(); }
3517: if ($symbparm) {
3518: $filename=(&decode_symb($symbparm))[2];
3519: } else {
3520: $filename=$ENV{'request.filename'};
3521: }
3522: my $metadata=&metadata($filename,$spacequalifierrest);
3523: if (defined($metadata)) { return $metadata; }
3524: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
3525: if (defined($metadata)) { return $metadata; }
3526:
3527: # ------------------------------------------------------------------ Cascade up
3528: unless ($space eq '0') {
3529: my @parts=split(/_/,$space);
3530: my $id=pop(@parts);
3531: my $part=join('_',@parts);
3532: if ($part eq '') { $part='0'; }
3533: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
3534: $symbparm,$udom,$uname,$section,1);
3535: if (defined($partgeneral)) { return $partgeneral; }
3536: }
3537: if ($recurse) { return undef; }
3538: my $pack_def=&packages_tab_default($filename,$varname);
3539: if (defined($pack_def)) { return $pack_def; }
3540:
3541: # ---------------------------------------------------- Any other user namespace
3542: } elsif ($realm eq 'environment') {
3543: # ----------------------------------------------------------------- environment
3544: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
3545: return $ENV{'environment.'.$spacequalifierrest};
3546: } else {
3547: my %returnhash=&userenvironment($udom,$uname,
3548: $spacequalifierrest);
3549: return $returnhash{$spacequalifierrest};
3550: }
3551: } elsif ($realm eq 'system') {
3552: # ----------------------------------------------------------------- system.time
3553: if ($space eq 'time') {
3554: return time;
3555: }
3556: }
3557: return '';
3558: }
3559:
3560: sub packages_tab_default {
3561: my ($uri,$varname)=@_;
3562: my (undef,$part,$name)=split(/\./,$varname);
3563: my $packages=&metadata($uri,'packages');
3564: foreach my $package (split(/,/,$packages)) {
3565: my ($pack_type,$pack_part)=split(/_/,$package,2);
3566: if ($pack_part eq $part) {
3567: return $packagetab{"$pack_type&$name&default"};
3568: }
3569: }
3570: return undef;
3571: }
3572:
3573: sub add_prefix_and_part {
3574: my ($prefix,$part)=@_;
3575: my $keyroot;
3576: if (defined($prefix) && $prefix !~ /^__/) {
3577: # prefix that has a part already
3578: $keyroot=$prefix;
3579: } elsif (defined($prefix)) {
3580: # prefix that is missing a part
3581: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
3582: } else {
3583: # no prefix at all
3584: if (defined($part)) { $keyroot='_'.$part; }
3585: }
3586: return $keyroot;
3587: }
3588:
3589: # ---------------------------------------------------------------- Get metadata
3590:
3591: sub metadata {
3592: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
3593:
3594: $uri=&declutter($uri);
3595: # if it is a non metadata possible uri return quickly
3596: if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
3597: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
3598: return '';
3599: }
3600: my $filename=$uri;
3601: $uri=~s/\.meta$//;
3602: #
3603: # Is the metadata already cached?
3604: # Look at timestamp of caching
3605: # Everything is cached by the main uri, libraries are never directly cached
3606: #
3607: unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
3608: #
3609: # Is this a recursive call for a library?
3610: #
3611: if ($liburi) {
3612: $liburi=&declutter($liburi);
3613: $filename=$liburi;
3614: } else {
3615: delete($metacache{$uri.':packages'});
3616: }
3617: my %metathesekeys=();
3618: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
3619: my $metastring=&getfile(&filelocation('',&clutter($filename)));
3620: my $parser=HTML::LCParser->new(\$metastring);
3621: my $token;
3622: undef %metathesekeys;
3623: while ($token=$parser->get_token) {
3624: if ($token->[0] eq 'S') {
3625: if (defined($token->[2]->{'package'})) {
3626: #
3627: # This is a package - get package info
3628: #
3629: my $package=$token->[2]->{'package'};
3630: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
3631: if (defined($token->[2]->{'id'})) {
3632: $keyroot.='_'.$token->[2]->{'id'};
3633: }
3634: if ($metacache{$uri.':packages'}) {
3635: $metacache{$uri.':packages'}.=','.$package.$keyroot;
3636: } else {
3637: $metacache{$uri.':packages'}=$package.$keyroot;
3638: }
3639: foreach (keys %packagetab) {
3640: if ($_=~/^$package\&/) {
3641: my ($pack,$name,$subp)=split(/\&/,$_);
3642: # ignore package.tab specified default values
3643: # here &package_tab_default() will fetch those
3644: if ($subp eq 'default') { next; }
3645: my $value=$packagetab{$_};
3646: my $part=$keyroot;
3647: $part=~s/^\_//;
3648: if ($subp eq 'display') {
3649: $value.=' [Part: '.$part.']';
3650: }
3651: my $unikey='parameter'.$keyroot.'_'.$name;
3652: $metacache{$uri.':'.$unikey.'.part'}=$part;
3653: $metathesekeys{$unikey}=1;
3654: unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
3655: $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
3656: }
3657: if (defined($metacache{$uri.':'.$unikey.'.default'})) {
3658: $metacache{$uri.':'.$unikey}=
3659: $metacache{$uri.':'.$unikey.'.default'};
3660: }
3661: }
3662: }
3663: } else {
3664: #
3665: # This is not a package - some other kind of start tag
3666: #
3667: my $entry=$token->[1];
3668: my $unikey;
3669: if ($entry eq 'import') {
3670: $unikey='';
3671: } else {
3672: $unikey=$entry;
3673: }
3674: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
3675:
3676: if (defined($token->[2]->{'id'})) {
3677: $unikey.='_'.$token->[2]->{'id'};
3678: }
3679:
3680: if ($entry eq 'import') {
3681: #
3682: # Importing a library here
3683: #
3684: if ($depthcount<20) {
3685: my $location=$parser->get_text('/import');
3686: my $dir=$filename;
3687: $dir=~s|[^/]*$||;
3688: $location=&filelocation($dir,$location);
3689: foreach (sort(split(/\,/,&metadata($uri,'keys',
3690: $location,$unikey,
3691: $depthcount+1)))) {
3692: $metathesekeys{$_}=1;
3693: }
3694: }
3695: } else {
3696:
3697: if (defined($token->[2]->{'name'})) {
3698: $unikey.='_'.$token->[2]->{'name'};
3699: }
3700: $metathesekeys{$unikey}=1;
3701: foreach (@{$token->[3]}) {
3702: $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
3703: }
3704: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
3705: my $default=$metacache{$uri.':'.$unikey.'.default'};
3706: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
3707: # only ws inside the tag, and not in default, so use default
3708: # as value
3709: $metacache{$uri.':'.$unikey}=$default;
3710: } else {
3711: # either something interesting inside the tag or default
3712: # uninteresting
3713: $metacache{$uri.':'.$unikey}=$internaltext;
3714: }
3715: # end of not-a-package not-a-library import
3716: }
3717: # end of not-a-package start tag
3718: }
3719: # the next is the end of "start tag"
3720: }
3721: }
3722: # are there custom rights to evaluate
3723: if ($metacache{$uri.':copyright'} eq 'custom') {
3724:
3725: #
3726: # Importing a rights file here
3727: #
3728: unless ($depthcount) {
3729: my $location=$metacache{$uri.':customdistributionfile'};
3730: my $dir=$filename;
3731: $dir=~s|[^/]*$||;
3732: $location=&filelocation($dir,$location);
3733: foreach (sort(split(/\,/,&metadata($uri,'keys',
3734: $location,'_rights',
3735: $depthcount+1)))) {
3736: $metathesekeys{$_}=1;
3737: }
3738: }
3739: }
3740: $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
3741: &metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
3742: $metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
3743: $metacache{$uri.':cachedtimestamp'}=time;
3744: # this is the end of "was not already recently cached
3745: }
3746: return $metacache{$uri.':'.$what};
3747: }
3748:
3749: sub metadata_generate_part0 {
3750: my ($metadata,$metacache,$uri) = @_;
3751: my %allnames;
3752: foreach my $metakey (sort keys %$metadata) {
3753: if ($metakey=~/^parameter\_(.*)/) {
3754: my $part=$$metacache{$uri.':'.$metakey.'.part'};
3755: my $name=$$metacache{$uri.':'.$metakey.'.name'};
3756: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
3757: $allnames{$name}=$part;
3758: }
3759: }
3760: }
3761: foreach my $name (keys(%allnames)) {
3762: $$metadata{"parameter_0_$name"}=1;
3763: my $key="$uri:parameter_0_$name";
3764: $$metacache{"$key.part"}='0';
3765: $$metacache{"$key.name"}=$name;
3766: $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
3767: $allnames{$name}.'_'.$name.
3768: '.type'};
3769: my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
3770: '.display'};
3771: my $expr='\\[Part: '.$allnames{$name}.'\\]';
3772: $olddis=~s/$expr/\[Part: 0\]/;
3773: $$metacache{"$key.display"}=$olddis;
3774: }
3775: }
3776:
3777: # ------------------------------------------------- Get the title of a resource
3778:
3779: sub gettitle {
3780: my $urlsymb=shift;
3781: my $symb=&symbread($urlsymb);
3782: unless ($symb) {
3783: unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
3784: return &metadata($urlsymb,'title');
3785: }
3786: if ($titlecache{$symb}) {
3787: if (time < ($titlecache{$symb}[1] + 600)) {
3788: return $titlecache{$symb}[0];
3789: } else {
3790: delete($titlecache{$symb});
3791: }
3792: }
3793: my ($map,$resid,$url)=&decode_symb($symb);
3794: my $title='';
3795: my %bighash;
3796: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3797: &GDBM_READER(),0640)) {
3798: my $mapid=$bighash{'map_pc_'.&clutter($map)};
3799: $title=$bighash{'title_'.$mapid.'.'.$resid};
3800: untie %bighash;
3801: }
3802: $title=~s/\&colon\;/\:/gs;
3803: if ($title) {
3804: $titlecache{$symb}=[$title,time];
3805: return $title;
3806: } else {
3807: return &metadata($urlsymb,'title');
3808: }
3809: }
3810:
3811: # ------------------------------------------------- Update symbolic store links
3812:
3813: sub symblist {
3814: my ($mapname,%newhash)=@_;
3815: $mapname=declutter($mapname);
3816: my %hash;
3817: if (($ENV{'request.course.fn'}) && (%newhash)) {
3818: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
3819: &GDBM_WRCREAT(),0640)) {
3820: foreach (keys %newhash) {
3821: $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
3822: }
3823: if (untie(%hash)) {
3824: return 'ok';
3825: }
3826: }
3827: }
3828: return 'error';
3829: }
3830:
3831: # --------------------------------------------------------------- Verify a symb
3832:
3833: sub symbverify {
3834: my ($symb,$thisfn)=@_;
3835: $thisfn=&declutter($thisfn);
3836: # direct jump to resource in page or to a sequence - will construct own symbs
3837: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
3838: # check URL part
3839: my ($map,$resid,$url)=&decode_symb($symb);
3840: unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
3841:
3842: $symb=&symbclean($symb);
3843:
3844: my %bighash;
3845: my $okay=0;
3846: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3847: &GDBM_READER(),0640)) {
3848: my $ids=$bighash{'ids_'.&clutter($thisfn)};
3849: unless ($ids) {
3850: $ids=$bighash{'ids_/'.$thisfn};
3851: }
3852: if ($ids) {
3853: # ------------------------------------------------------------------- Has ID(s)
3854: foreach (split(/\,/,$ids)) {
3855: my ($mapid,$resid)=split(/\./,$_);
3856: if (
3857: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
3858: eq $symb) {
3859: $okay=1;
3860: }
3861: }
3862: }
3863: untie(%bighash);
3864: }
3865: return $okay;
3866: }
3867:
3868: # --------------------------------------------------------------- Clean-up symb
3869:
3870: sub symbclean {
3871: my $symb=shift;
3872:
3873: # remove version from map
3874: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
3875:
3876: # remove version from URL
3877: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
3878:
3879: return $symb;
3880: }
3881:
3882: # ---------------------------------------------- Split symb to find map and url
3883:
3884: sub decode_symb {
3885: my ($map,$resid,$url)=split(/\_\_\_/,shift);
3886: return (&fixversion($map),$resid,&fixversion($url));
3887: }
3888:
3889: sub fixversion {
3890: my $fn=shift;
3891: if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
3892: my ($match,$cond,$versioned)=&is_on_map($fn);
3893: unless ($match) {
3894: $fn=$versioned;
3895: }
3896: return $fn;
3897: }
3898:
3899: # ------------------------------------------------------ Return symb list entry
3900:
3901: sub symbread {
3902: my ($thisfn,$donotrecurse)=@_;
3903: # no filename provided? try from environment
3904: unless ($thisfn) {
3905: if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
3906: $thisfn=$ENV{'request.filename'};
3907: }
3908: # is that filename actually a symb? Verify, clean, and return
3909: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
3910: if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
3911: }
3912: $thisfn=declutter($thisfn);
3913: my %hash;
3914: my %bighash;
3915: my $syval='';
3916: if (($ENV{'request.course.fn'}) && ($thisfn)) {
3917: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
3918: &GDBM_READER(),0640)) {
3919: $syval=$hash{$thisfn};
3920: untie(%hash);
3921: }
3922: # ---------------------------------------------------------- There was an entry
3923: if ($syval) {
3924: unless ($syval=~/\_\d+$/) {
3925: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
3926: &appenv('request.ambiguous' => $thisfn);
3927: return '';
3928: }
3929: $syval.=$1;
3930: }
3931: } else {
3932: # ------------------------------------------------------- Was not in symb table
3933: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3934: &GDBM_READER(),0640)) {
3935: # ---------------------------------------------- Get ID(s) for current resource
3936: my $ids=$bighash{'ids_'.&clutter($thisfn)};
3937: unless ($ids) {
3938: $ids=$bighash{'ids_/'.$thisfn};
3939: }
3940: unless ($ids) {
3941: # alias?
3942: $ids=$bighash{'mapalias_'.$thisfn};
3943: }
3944: if ($ids) {
3945: # ------------------------------------------------------------------- Has ID(s)
3946: my @possibilities=split(/\,/,$ids);
3947: if ($#possibilities==0) {
3948: # ----------------------------------------------- There is only one possibility
3949: my ($mapid,$resid)=split(/\./,$ids);
3950: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
3951: } elsif (!$donotrecurse) {
3952: # ------------------------------------------ There is more than one possibility
3953: my $realpossible=0;
3954: foreach (@possibilities) {
3955: my $file=$bighash{'src_'.$_};
3956: if (&allowed('bre',$file)) {
3957: my ($mapid,$resid)=split(/\./,$_);
3958: if ($bighash{'map_type_'.$mapid} ne 'page') {
3959: $realpossible++;
3960: $syval=declutter($bighash{'map_id_'.$mapid}).
3961: '___'.$resid;
3962: }
3963: }
3964: }
3965: if ($realpossible!=1) { $syval=''; }
3966: } else {
3967: $syval='';
3968: }
3969: }
3970: untie(%bighash)
3971: }
3972: }
3973: if ($syval) {
3974: return &symbclean($syval.'___'.$thisfn);
3975: }
3976: }
3977: &appenv('request.ambiguous' => $thisfn);
3978: return '';
3979: }
3980:
3981: # ---------------------------------------------------------- Return random seed
3982:
3983: sub numval {
3984: my $txt=shift;
3985: $txt=~tr/A-J/0-9/;
3986: $txt=~tr/a-j/0-9/;
3987: $txt=~tr/K-T/0-9/;
3988: $txt=~tr/k-t/0-9/;
3989: $txt=~tr/U-Z/0-5/;
3990: $txt=~tr/u-z/0-5/;
3991: $txt=~s/\D//g;
3992: return int($txt);
3993: }
3994:
3995: sub latest_rnd_algorithm_id {
3996: return '64bit';
3997: }
3998:
3999: sub rndseed {
4000: my ($symb,$courseid,$domain,$username)=@_;
4001:
4002: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
4003: if (!$symb) {
4004: unless ($symb=$wsymb) { return time; }
4005: }
4006: if (!$courseid) { $courseid=$wcourseid; }
4007: if (!$domain) { $domain=$wdomain; }
4008: if (!$username) { $username=$wusername }
4009: my $which=$ENV{"course.$courseid.rndseed"};
4010: my $CODE=$ENV{'scantron.CODE'};
4011: if (defined($CODE)) {
4012: &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
4013: } elsif ($which eq '64bit') {
4014: return &rndseed_64bit($symb,$courseid,$domain,$username);
4015: }
4016: return &rndseed_32bit($symb,$courseid,$domain,$username);
4017: }
4018:
4019: sub rndseed_32bit {
4020: my ($symb,$courseid,$domain,$username)=@_;
4021: {
4022: use integer;
4023: my $symbchck=unpack("%32C*",$symb) << 27;
4024: my $symbseed=numval($symb) << 22;
4025: my $namechck=unpack("%32C*",$username) << 17;
4026: my $nameseed=numval($username) << 12;
4027: my $domainseed=unpack("%32C*",$domain) << 7;
4028: my $courseseed=unpack("%32C*",$courseid);
4029: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
4030: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4031: #&Apache::lonxml::debug("rndseed :$num:$symb");
4032: return $num;
4033: }
4034: }
4035:
4036: sub rndseed_64bit {
4037: my ($symb,$courseid,$domain,$username)=@_;
4038: {
4039: use integer;
4040: my $symbchck=unpack("%32S*",$symb) << 21;
4041: my $symbseed=numval($symb) << 10;
4042: my $namechck=unpack("%32S*",$username);
4043:
4044: my $nameseed=numval($username) << 21;
4045: my $domainseed=unpack("%32S*",$domain) << 10;
4046: my $courseseed=unpack("%32S*",$courseid);
4047:
4048: my $num1=$symbchck+$symbseed+$namechck;
4049: my $num2=$nameseed+$domainseed+$courseseed;
4050: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4051: #&Apache::lonxml::debug("rndseed :$num:$symb");
4052: return "$num1,$num2";
4053: }
4054: }
4055:
4056: sub rndseed_CODE_64bit {
4057: my ($symb,$courseid,$domain,$username)=@_;
4058: {
4059: use integer;
4060: my $symbchck=unpack("%32S*",$symb) << 16;
4061: my $symbseed=numval($symb);
4062: my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
4063: my $courseseed=unpack("%32S*",$courseid);
4064: my $num1=$symbseed+$CODEseed;
4065: my $num2=$courseseed+$symbchck;
4066: #&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
4067: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
4068: return "$num1,$num2";
4069: }
4070: }
4071:
4072: sub setup_random_from_rndseed {
4073: my ($rndseed)=@_;
4074: if ($rndseed =~/,/) {
4075: my ($num1,$num2)=split(/,/,$rndseed);
4076: &Math::Random::random_set_seed(abs($num1),abs($num2));
4077: } else {
4078: &Math::Random::random_set_seed_from_phrase($rndseed);
4079: }
4080: }
4081:
4082: sub ireceipt {
4083: my ($funame,$fudom,$fucourseid,$fusymb)=@_;
4084: my $cuname=unpack("%32C*",$funame);
4085: my $cudom=unpack("%32C*",$fudom);
4086: my $cucourseid=unpack("%32C*",$fucourseid);
4087: my $cusymb=unpack("%32C*",$fusymb);
4088: my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
4089: return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
4090: ($cunique%$cuname+
4091: $cunique%$cudom+
4092: $cusymb%$cuname+
4093: $cusymb%$cudom+
4094: $cucourseid%$cuname+
4095: $cucourseid%$cudom);
4096: }
4097:
4098: sub receipt {
4099: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
4100: return &ireceipt($name,$domain,$courseid,$symb);
4101: }
4102:
4103: # ------------------------------------------------------------ Serves up a file
4104: # returns either the contents of the file or a -1
4105: sub getfile {
4106: my $file=shift;
4107: if ($file=~/^\/*uploaded\//) { # user file
4108: my $ua=new LWP::UserAgent;
4109: my $request=new HTTP::Request('GET',&tokenwrapper($file));
4110: my $response=$ua->request($request);
4111: if ($response->is_success()) {
4112: return $response->content;
4113: } else {
4114: return -1;
4115: }
4116: } else { # normal file from res space
4117: &repcopy($file);
4118: if (! -e $file ) { return -1; };
4119: my $fh=Apache::File->new($file);
4120: my $a='';
4121: while (<$fh>) { $a .=$_; }
4122: return $a;
4123: }
4124: }
4125:
4126: sub filelocation {
4127: my ($dir,$file) = @_;
4128: my $location;
4129: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
4130: if ($file=~m:^/~:) { # is a contruction space reference
4131: $location = $file;
4132: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
4133: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
4134: $location=$file;
4135: } else {
4136: $file=~s/^$perlvar{'lonDocRoot'}//;
4137: $file=~s:^/*res::;
4138: if ( !( $file =~ m:^/:) ) {
4139: $location = $dir. '/'.$file;
4140: } else {
4141: $location = '/home/httpd/html/res'.$file;
4142: }
4143: }
4144: $location=~s://+:/:g; # remove duplicate /
4145: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
4146: return $location;
4147: }
4148:
4149: sub hreflocation {
4150: my ($dir,$file)=@_;
4151: unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
4152: my $finalpath=filelocation($dir,$file);
4153: $finalpath=~s/^\/home\/httpd\/html//;
4154: $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
4155: return $finalpath;
4156: } else {
4157: return $file;
4158: }
4159: }
4160:
4161: # ------------------------------------------------------------- Declutters URLs
4162:
4163: sub declutter {
4164: my $thisfn=shift;
4165: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
4166: $thisfn=~s/^\///;
4167: $thisfn=~s/^res\///;
4168: $thisfn=~s/\?.+$//;
4169: return $thisfn;
4170: }
4171:
4172: # ------------------------------------------------------------- Clutter up URLs
4173:
4174: sub clutter {
4175: my $thisfn='/'.&declutter(shift);
4176: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) {
4177: $thisfn='/res'.$thisfn;
4178: }
4179: return $thisfn;
4180: }
4181:
4182: # -------------------------------------------------------- Escape Special Chars
4183:
4184: sub escape {
4185: my $str=shift;
4186: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4187: return $str;
4188: }
4189:
4190: # ----------------------------------------------------- Un-Escape Special Chars
4191:
4192: sub unescape {
4193: my $str=shift;
4194: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4195: return $str;
4196: }
4197:
4198: # ================================================================ Main Program
4199:
4200: sub goodbye {
4201: &logthis("Starting Shut down");
4202: &flushcourselogs();
4203: &logthis("Shutting down");
4204: return DONE;
4205: }
4206:
4207: BEGIN {
4208: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
4209: unless ($readit) {
4210: {
4211: my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
4212:
4213: while (my $configline=<$config>) {
4214: if ($configline =~ /^[^\#]*PerlSetVar/) {
4215: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
4216: chomp($varvalue);
4217: $perlvar{$varname}=$varvalue;
4218: }
4219: }
4220: }
4221: {
4222: my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
4223:
4224: while (my $configline=<$config>) {
4225: if ($configline =~ /^[^\#]*PerlSetVar/) {
4226: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
4227: chomp($varvalue);
4228: $perlvar{$varname}=$varvalue;
4229: }
4230: }
4231: }
4232:
4233: # ------------------------------------------------------------ Read domain file
4234: {
4235: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
4236: '/domain.tab');
4237: %domaindescription = ();
4238: %domain_auth_def = ();
4239: %domain_auth_arg_def = ();
4240: if ($fh) {
4241: while (<$fh>) {
4242: next if (/^(\#|\s*$)/);
4243: # next if /^\#/;
4244: chomp;
4245: my ($domain, $domain_description, $def_auth, $def_auth_arg,
4246: $def_lang, $city, $longi, $lati) = split(/:/,$_);
4247: $domain_auth_def{$domain}=$def_auth;
4248: $domain_auth_arg_def{$domain}=$def_auth_arg;
4249: $domaindescription{$domain}=$domain_description;
4250: $domain_lang_def{$domain}=$def_lang;
4251: $domain_city{$domain}=$city;
4252: $domain_longi{$domain}=$longi;
4253: $domain_lati{$domain}=$lati;
4254:
4255: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
4256: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
4257: }
4258: }
4259: }
4260:
4261:
4262: # ------------------------------------------------------------- Read hosts file
4263: {
4264: my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
4265:
4266: while (my $configline=<$config>) {
4267: next if ($configline =~ /^(\#|\s*$)/);
4268: chomp($configline);
4269: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
4270: if ($id && $domain && $role && $name && $ip) {
4271: $hostname{$id}=$name;
4272: $hostdom{$id}=$domain;
4273: $hostip{$id}=$ip;
4274: $iphost{$ip}=$id;
4275: if ($role eq 'library') { $libserv{$id}=$name; }
4276: } else {
4277: if ($configline) {
4278: &logthis("Skipping hosts.tab line -$configline-");
4279: }
4280: }
4281: }
4282: }
4283:
4284: # ------------------------------------------------------ Read spare server file
4285: {
4286: my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
4287:
4288: while (my $configline=<$config>) {
4289: chomp($configline);
4290: if ($configline) {
4291: $spareid{$configline}=1;
4292: }
4293: }
4294: }
4295: # ------------------------------------------------------------ Read permissions
4296: {
4297: my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
4298:
4299: while (my $configline=<$config>) {
4300: chomp($configline);
4301: if ($configline) {
4302: my ($role,$perm)=split(/ /,$configline);
4303: if ($perm ne '') { $pr{$role}=$perm; }
4304: }
4305: }
4306: }
4307:
4308: # -------------------------------------------- Read plain texts for permissions
4309: {
4310: my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
4311:
4312: while (my $configline=<$config>) {
4313: chomp($configline);
4314: if ($configline) {
4315: my ($short,$plain)=split(/:/,$configline);
4316: if ($plain ne '') { $prp{$short}=$plain; }
4317: }
4318: }
4319: }
4320:
4321: # ---------------------------------------------------------- Read package table
4322: {
4323: my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
4324:
4325: while (my $configline=<$config>) {
4326: chomp($configline);
4327: my ($short,$plain)=split(/:/,$configline);
4328: my ($pack,$name)=split(/\&/,$short);
4329: if ($plain ne '') {
4330: $packagetab{$pack.'&'.$name.'&name'}=$name;
4331: $packagetab{$short}=$plain;
4332: }
4333: }
4334: }
4335:
4336: # ------------- set up temporary directory
4337: {
4338: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
4339:
4340: }
4341:
4342: %metacache=();
4343:
4344: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
4345: $dumpcount=0;
4346:
4347: &logtouch();
4348: &logthis('<font color=yellow>INFO: Read configuration</font>');
4349: $readit=1;
4350: }
4351: }
4352:
4353: 1;
4354: __END__
4355:
4356: =pod
4357:
4358: =head1 NAME
4359:
4360: Apache::lonnet - Subroutines to ask questions about things in the network.
4361:
4362: =head1 SYNOPSIS
4363:
4364: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
4365:
4366: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
4367:
4368: Common parameters:
4369:
4370: =over 4
4371:
4372: =item *
4373:
4374: $uname : an internal username (if $cname expecting a course Id specifically)
4375:
4376: =item *
4377:
4378: $udom : a domain (if $cdom expecting a course's domain specifically)
4379:
4380: =item *
4381:
4382: $symb : a resource instance identifier
4383:
4384: =item *
4385:
4386: $namespace : the name of a .db file that contains the data needed or
4387: being set.
4388:
4389: =back
4390:
4391: =head1 OVERVIEW
4392:
4393: lonnet provides subroutines which interact with the
4394: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
4395: about classes, users, and resources.
4396:
4397: For many of these objects you can also use this to store data about
4398: them or modify them in various ways.
4399:
4400: =head2 Symbs
4401:
4402: To identify a specific instance of a resource, LON-CAPA uses symbols
4403: or "symbs"X<symb>. These identifiers are built from the URL of the
4404: map, the resource number of the resource in the map, and the URL of
4405: the resource itself. The latter is somewhat redundant, but might help
4406: if maps change.
4407:
4408: An example is
4409:
4410: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
4411:
4412: The respective map entry is
4413:
4414: <resource id="19" src="/res/msu/korte/tests/part12.problem"
4415: title="Problem 2">
4416: </resource>
4417:
4418: Symbs are used by the random number generator, as well as to store and
4419: restore data specific to a certain instance of for example a problem.
4420:
4421: =head2 Storing And Retrieving Data
4422:
4423: X<store()>X<cstore()>X<restore()>Three of the most important functions
4424: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
4425: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
4426: is is the non-critical message twin of cstore. These functions are for
4427: handlers to store a perl hash to a user's permanent data space in an
4428: easy manner, and to retrieve it again on another call. It is expected
4429: that a handler would use this once at the beginning to retrieve data,
4430: and then again once at the end to send only the new data back.
4431:
4432: The data is stored in the user's data directory on the user's
4433: homeserver under the ID of the course.
4434:
4435: The hash that is returned by restore will have all of the previous
4436: value for all of the elements of the hash.
4437:
4438: Example:
4439:
4440: #creating a hash
4441: my %hash;
4442: $hash{'foo'}='bar';
4443:
4444: #storing it
4445: &Apache::lonnet::cstore(\%hash);
4446:
4447: #changing a value
4448: $hash{'foo'}='notbar';
4449:
4450: #adding a new value
4451: $hash{'bar'}='foo';
4452: &Apache::lonnet::cstore(\%hash);
4453:
4454: #retrieving the hash
4455: my %history=&Apache::lonnet::restore();
4456:
4457: #print the hash
4458: foreach my $key (sort(keys(%history))) {
4459: print("\%history{$key} = $history{$key}");
4460: }
4461:
4462: Will print out:
4463:
4464: %history{1:foo} = bar
4465: %history{1:keys} = foo:timestamp
4466: %history{1:timestamp} = 990455579
4467: %history{2:bar} = foo
4468: %history{2:foo} = notbar
4469: %history{2:keys} = foo:bar:timestamp
4470: %history{2:timestamp} = 990455580
4471: %history{bar} = foo
4472: %history{foo} = notbar
4473: %history{timestamp} = 990455580
4474: %history{version} = 2
4475:
4476: Note that the special hash entries C<keys>, C<version> and
4477: C<timestamp> were added to the hash. C<version> will be equal to the
4478: total number of versions of the data that have been stored. The
4479: C<timestamp> attribute will be the UNIX time the hash was
4480: stored. C<keys> is available in every historical section to list which
4481: keys were added or changed at a specific historical revision of a
4482: hash.
4483:
4484: B<Warning>: do not store the hash that restore returns directly. This
4485: will cause a mess since it will restore the historical keys as if the
4486: were new keys. I.E. 1:foo will become 1:1:foo etc.
4487:
4488: Calling convention:
4489:
4490: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
4491: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
4492:
4493: For more detailed information, see lonnet specific documentation.
4494:
4495: =head1 RETURN MESSAGES
4496:
4497: =over 4
4498:
4499: =item * B<con_lost>: unable to contact remote host
4500:
4501: =item * B<con_delayed>: unable to contact remote host, message will be delivered
4502: when the connection is brought back up
4503:
4504: =item * B<con_failed>: unable to contact remote host and unable to save message
4505: for later delivery
4506:
4507: =item * B<error:>: an error a occured, a description of the error follows the :
4508:
4509: =item * B<no_such_host>: unable to fund a host associated with the user/domain
4510: that was requested
4511:
4512: =back
4513:
4514: =head1 PUBLIC SUBROUTINES
4515:
4516: =head2 Session Environment Functions
4517:
4518: =over 4
4519:
4520: =item *
4521: X<appenv()>
4522: B<appenv(%hash)>: the value of %hash is written to
4523: the user envirnoment file, and will be restored for each access this
4524: user makes during this session, also modifies the %ENV for the current
4525: process
4526:
4527: =item *
4528: X<delenv()>
4529: B<delenv($regexp)>: removes all items from the session
4530: environment file that matches the regular expression in $regexp. The
4531: values are also delted from the current processes %ENV.
4532:
4533: =back
4534:
4535: =head2 User Information
4536:
4537: =over 4
4538:
4539: =item *
4540: X<queryauthenticate()>
4541: B<queryauthenticate($uname,$udom)>: try to determine user's current
4542: authentication scheme
4543:
4544: =item *
4545: X<authenticate()>
4546: B<authenticate($uname,$upass,$udom)>: try to
4547: authenticate user from domain's lib servers (first use the current
4548: one). C<$upass> should be the users password.
4549:
4550: =item *
4551: X<homeserver()>
4552: B<homeserver($uname,$udom)>: find the server which has
4553: the user's directory and files (there must be only one), this caches
4554: the answer, and also caches if there is a borken connection.
4555:
4556: =item *
4557: X<idget()>
4558: B<idget($udom,@ids)>: find the usernames behind a list of IDs
4559: (IDs are a unique resource in a domain, there must be only 1 ID per
4560: username, and only 1 username per ID in a specific domain) (returns
4561: hash: id=>name,id=>name)
4562:
4563: =item *
4564: X<idrget()>
4565: B<idrget($udom,@unames)>: find the IDs behind a list of
4566: usernames (returns hash: name=>id,name=>id)
4567:
4568: =item *
4569: X<idput()>
4570: B<idput($udom,%ids)>: store away a list of names and associated IDs
4571:
4572: =item *
4573: X<rolesinit()>
4574: B<rolesinit($udom,$username,$authhost)>: get user privileges
4575:
4576: =item *
4577: X<usection()>
4578: B<usection($udom,$uname,$cname)>: finds the section of student in the
4579: course $cname, return section name/number or '' for "not in course"
4580: and '-1' for "no section"
4581:
4582: =item *
4583: X<userenvironment()>
4584: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
4585: passed in @what from the requested user's environment, returns a hash
4586:
4587: =back
4588:
4589: =head2 User Roles
4590:
4591: =over 4
4592:
4593: =item *
4594:
4595: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
4596: actions
4597: F: full access
4598: U,I,K: authentication modes (cxx only)
4599: '': forbidden
4600: 1: user needs to choose course
4601: 2: browse allowed
4602:
4603: =item *
4604:
4605: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
4606: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
4607: and course level
4608:
4609: =item *
4610:
4611: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
4612: explanation of a user role term
4613:
4614: =back
4615:
4616: =head2 User Modification
4617:
4618: =over 4
4619:
4620: =item *
4621:
4622: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
4623: user for the level given by URL. Optional start and end dates (leave empty
4624: string or zero for "no date")
4625:
4626: =item *
4627:
4628: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
4629: change a users, password, possible return values are: ok,
4630: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
4631: refused
4632:
4633: =item *
4634:
4635: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
4636:
4637: =item *
4638:
4639: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
4640: modify user
4641:
4642: =item *
4643:
4644: modifystudent
4645:
4646: modify a students enrollment and identification information.
4647: The course id is resolved based on the current users environment.
4648: This means the envoking user must be a course coordinator or otherwise
4649: associated with a course.
4650:
4651: This call is essentially a wrapper for lonnet::modifyuser and
4652: lonnet::modify_student_enrollment
4653:
4654: Inputs:
4655:
4656: =over 4
4657:
4658: =item B<$udom> Students loncapa domain
4659:
4660: =item B<$uname> Students loncapa login name
4661:
4662: =item B<$uid> Students id/student number
4663:
4664: =item B<$umode> Students authentication mode
4665:
4666: =item B<$upass> Students password
4667:
4668: =item B<$first> Students first name
4669:
4670: =item B<$middle> Students middle name
4671:
4672: =item B<$last> Students last name
4673:
4674: =item B<$gene> Students generation
4675:
4676: =item B<$usec> Students section in course
4677:
4678: =item B<$end> Unix time of the roles expiration
4679:
4680: =item B<$start> Unix time of the roles start date
4681:
4682: =item B<$forceid> If defined, allow $uid to be changed
4683:
4684: =item B<$desiredhome> server to use as home server for student
4685:
4686: =back
4687:
4688: =item *
4689:
4690: modify_student_enrollment
4691:
4692: Change a students enrollment status in a class. The environment variable
4693: 'role.request.course' must be defined for this function to proceed.
4694:
4695: Inputs:
4696:
4697: =over 4
4698:
4699: =item $udom, students domain
4700:
4701: =item $uname, students name
4702:
4703: =item $uid, students user id
4704:
4705: =item $first, students first name
4706:
4707: =item $middle
4708:
4709: =item $last
4710:
4711: =item $gene
4712:
4713: =item $usec
4714:
4715: =item $end
4716:
4717: =item $start
4718:
4719: =back
4720:
4721:
4722: =item *
4723:
4724: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
4725: custom role; give a custom role to a user for the level given by URL. Specify
4726: name and domain of role author, and role name
4727:
4728: =item *
4729:
4730: revokerole($udom,$uname,$url,$role) : revoke a role for url
4731:
4732: =item *
4733:
4734: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
4735:
4736: =back
4737:
4738: =head2 Course Infomation
4739:
4740: =over 4
4741:
4742: =item *
4743:
4744: coursedescription($courseid) : course description
4745:
4746: =item *
4747:
4748: courseresdata($coursenum,$coursedomain,@which) : request for current
4749: parameter setting for a specific course, @what should be a list of
4750: parameters to ask about. This routine caches answers for 5 minutes.
4751:
4752: =back
4753:
4754: =head2 Course Modification
4755:
4756: =over 4
4757:
4758: =item *
4759:
4760: writecoursepref($courseid,%prefs) : write preferences (environment
4761: database) for a course
4762:
4763: =item *
4764:
4765: createcourse($udom,$description,$url) : make/modify course
4766:
4767: =back
4768:
4769: =head2 Resource Subroutines
4770:
4771: =over 4
4772:
4773: =item *
4774:
4775: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
4776:
4777: =item *
4778:
4779: repcopy($filename) : subscribes to the requested file, and attempts to
4780: replicate from the owning library server, Might return
4781: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
4782: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
4783: resource. Expects the local filesystem pathname
4784: (/home/httpd/html/res/....)
4785:
4786: =back
4787:
4788: =head2 Resource Information
4789:
4790: =over 4
4791:
4792: =item *
4793:
4794: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
4795: a vairety of different possible values, $varname should be a request
4796: string, and the other parameters can be used to specify who and what
4797: one is asking about.
4798:
4799: Possible values for $varname are environment.lastname (or other item
4800: from the envirnment hash), user.name (or someother aspect about the
4801: user), resource.0.maxtries (or some other part and parameter of a
4802: resource)
4803:
4804: =item *
4805:
4806: directcondval($number) : get current value of a condition; reads from a state
4807: string
4808:
4809: =item *
4810:
4811: condval($condidx) : value of condition index based on state
4812:
4813: =item *
4814:
4815: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
4816: resource's metadata, $what should be either a specific key, or either
4817: 'keys' (to get a list of possible keys) or 'packages' to get a list of
4818: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
4819:
4820: this function automatically caches all requests
4821:
4822: =item *
4823:
4824: metadata_query($query,$custom,$customshow) : make a metadata query against the
4825: network of library servers; returns file handle of where SQL and regex results
4826: will be stored for query
4827:
4828: =item *
4829:
4830: symbread($filename) : return symbolic list entry (filename argument optional);
4831: returns the data handle
4832:
4833: =item *
4834:
4835: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
4836: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
4837: failure, user must be in a course, as it assumes the existance of the
4838: course initi hash, and uses $ENV('request.course.id'}
4839:
4840:
4841: =item *
4842:
4843: symbclean($symb) : removes versions numbers from a symb, returns the
4844: cleaned symb
4845:
4846: =item *
4847:
4848: is_on_map($uri) : checks if the $uri is somewhere on the current
4849: course map, user must be in a course for it to work.
4850:
4851: =item *
4852:
4853: numval($salt) : return random seed value (addend for rndseed)
4854:
4855: =item *
4856:
4857: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
4858: a random seed, all arguments are optional, if they aren't sent it uses the
4859: environment to derive them. Note: if symb isn't sent and it can't get one
4860: from &symbread it will use the current time as its return value
4861:
4862: =item *
4863:
4864: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
4865: unfakeable, receipt
4866:
4867: =item *
4868:
4869: receipt() : API to ireceipt working off of ENV values; given out to users
4870:
4871: =item *
4872:
4873: countacc($url) : count the number of accesses to a given URL
4874:
4875: =item *
4876:
4877: 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
4878:
4879: =item *
4880:
4881: 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)
4882:
4883: =item *
4884:
4885: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
4886:
4887: =item *
4888:
4889: devalidate($symb) : devalidate temporary spreadsheet calculations,
4890: forcing spreadsheet to reevaluate the resource scores next time.
4891:
4892: =back
4893:
4894: =head2 Storing/Retreiving Data
4895:
4896: =over 4
4897:
4898: =item *
4899:
4900: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
4901: for this url; hashref needs to be given and should be a \%hashname; the
4902: remaining args aren't required and if they aren't passed or are '' they will
4903: be derived from the ENV
4904:
4905: =item *
4906:
4907: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
4908: uses critical subroutine
4909:
4910: =item *
4911:
4912: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
4913: all args are optional
4914:
4915: =item *
4916:
4917: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
4918: works very similar to store/cstore, but all data is stored in a
4919: temporary location and can be reset using tmpreset, $storehash should
4920: be a hash reference, returns nothing on success
4921:
4922: =item *
4923:
4924: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
4925: similar to restore, but all data is stored in a temporary location and
4926: can be reset using tmpreset. Returns a hash of values on success,
4927: error string otherwise.
4928:
4929: =item *
4930:
4931: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
4932: deltes all keys for $symb form the temporary storage hash.
4933:
4934: =item *
4935:
4936: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
4937: reference filled in from namesp ($udom and $uname are optional)
4938:
4939: =item *
4940:
4941: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
4942: namesp ($udom and $uname are optional)
4943:
4944: =item *
4945:
4946: dump($namespace,$udom,$uname,$regexp) :
4947: dumps the complete (or key matching regexp) namespace into a hash
4948: ($udom, $uname and $regexp are optional)
4949:
4950: =item *
4951:
4952: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
4953: ($udom and $uname are optional)
4954:
4955: =item *
4956:
4957: cput($namespace,$storehash,$udom,$uname) : critical put
4958: ($udom and $uname are optional)
4959:
4960: =item *
4961:
4962: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
4963: reference filled in from namesp (encrypts the return communication)
4964: ($udom and $uname are optional)
4965:
4966: =item *
4967:
4968: log($udom,$name,$home,$message) : write to permanent log for user; use
4969: critical subroutine
4970:
4971: =back
4972:
4973: =head2 Network Status Functions
4974:
4975: =over 4
4976:
4977: =item *
4978:
4979: dirlist($uri) : return directory list based on URI
4980:
4981: =item *
4982:
4983: spareserver() : find server with least workload from spare.tab
4984:
4985: =back
4986:
4987: =head2 Apache Request
4988:
4989: =over 4
4990:
4991: =item *
4992:
4993: ssi($url,%hash) : server side include, does a complete request cycle on url to
4994: localhost, posts hash
4995:
4996: =back
4997:
4998: =head2 Data to String to Data
4999:
5000: =over 4
5001:
5002: =item *
5003:
5004: hash2str(%hash) : convert a hash into a string complete with escaping and '='
5005: and '&' separators, supports elements that are arrayrefs and hashrefs
5006:
5007: =item *
5008:
5009: hashref2str($hashref) : convert a hashref into a string complete with
5010: escaping and '=' and '&' separators, supports elements that are
5011: arrayrefs and hashrefs
5012:
5013: =item *
5014:
5015: arrayref2str($arrayref) : convert an arrayref into a string complete
5016: with escaping and '&' separators, supports elements that are arrayrefs
5017: and hashrefs
5018:
5019: =item *
5020:
5021: str2hash($string) : convert string to hash using unescaping and
5022: splitting on '=' and '&', supports elements that are arrayrefs and
5023: hashrefs
5024:
5025: =item *
5026:
5027: str2array($string) : convert string to hash using unescaping and
5028: splitting on '&', supports elements that are arrayrefs and hashrefs
5029:
5030: =back
5031:
5032: =head2 Logging Routines
5033:
5034: =over 4
5035:
5036: These routines allow one to make log messages in the lonnet.log and
5037: lonnet.perm logfiles.
5038:
5039: =item *
5040:
5041: logtouch() : make sure the logfile, lonnet.log, exists
5042:
5043: =item *
5044:
5045: logthis() : append message to the normal lonnet.log file, it gets
5046: preiodically rolled over and deleted.
5047:
5048: =item *
5049:
5050: logperm() : append a permanent message to lonnet.perm.log, this log
5051: file never gets deleted by any automated portion of the system, only
5052: messages of critical importance should go in here.
5053:
5054: =back
5055:
5056: =head2 General File Helper Routines
5057:
5058: =over 4
5059:
5060: =item *
5061:
5062: getfile($file) : returns the entire contents of a file or -1; it
5063: properly subscribes to and replicates the file if neccessary.
5064:
5065: =item *
5066:
5067: filelocation($dir,$file) : returns file system location of a file
5068: based on URI; meant to be "fairly clean" absolute reference, $dir is a
5069: directory that relative $file lookups are to looked in ($dir of /a/dir
5070: and a file of ../bob will become /a/bob)
5071:
5072: =item *
5073:
5074: hreflocation($dir,$file) : returns file system location or a URL; same as
5075: filelocation except for hrefs
5076:
5077: =item *
5078:
5079: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
5080:
5081: =back
5082:
5083: =head2 HTTP Helper Routines
5084:
5085: =over 4
5086:
5087: =item *
5088:
5089: escape() : unpack non-word characters into CGI-compatible hex codes
5090:
5091: =item *
5092:
5093: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
5094:
5095: =back
5096:
5097: =head1 PRIVATE SUBROUTINES
5098:
5099: =head2 Underlying communication routines (Shouldn't call)
5100:
5101: =over 4
5102:
5103: =item *
5104:
5105: subreply() : tries to pass a message to lonc, returns con_lost if incapable
5106:
5107: =item *
5108:
5109: reply() : uses subreply to send a message to remote machine, logs all failures
5110:
5111: =item *
5112:
5113: critical() : passes a critical message to another server; if cannot
5114: get through then place message in connection buffer directory and
5115: returns con_delayed, if incapable of saving message, returns
5116: con_failed
5117:
5118: =item *
5119:
5120: reconlonc() : tries to reconnect lonc client processes.
5121:
5122: =back
5123:
5124: =head2 Resource Access Logging
5125:
5126: =over 4
5127:
5128: =item *
5129:
5130: flushcourselogs() : flush (save) buffer logs and access logs
5131:
5132: =item *
5133:
5134: courselog($what) : save message for course in hash
5135:
5136: =item *
5137:
5138: courseacclog($what) : save message for course using &courselog(). Perform
5139: special processing for specific resource types (problems, exams, quizzes, etc).
5140:
5141: =item *
5142:
5143: goodbye() : flush course logs and log shutting down; it is called in srm.conf
5144: as a PerlChildExitHandler
5145:
5146: =back
5147:
5148: =head2 Other
5149:
5150: =over 4
5151:
5152: =item *
5153:
5154: symblist($mapname,%newhash) : update symbolic storage links
5155:
5156: =back
5157:
5158: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>