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