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