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