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