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