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