1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.677 2005/11/15 18:39:16 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: package Apache::lonnet;
31:
32: use strict;
33: use LWP::UserAgent();
34: use HTTP::Headers;
35: use HTTP::Date;
36: # use Date::Parse;
37: use vars
38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom
39: %libserv %pr %prp $memcache %packagetab
40: %courselogs %accesshash %userrolehash %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 $now=time;
2579: my $userroles="user.login.time=$now\n";
2580:
2581: if ($rolesdump ne '') {
2582: foreach (split(/&/,$rolesdump)) {
2583: if ($_!~/^rolesdef_/) {
2584: my ($area,$role)=split(/=/,$_);
2585: $area=~s/\_\w\w$//;
2586: my ($trole,$tend,$tstart);
2587: if ($role=~/^cr/) {
2588: if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
2589: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
2590: ($tend,$tstart)=split('_',$trest);
2591: } else {
2592: $trole=$role;
2593: }
2594: } else {
2595: ($trole,$tend,$tstart)=split(/_/,$role);
2596: }
2597: $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
2598: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2599: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2600: if (($area ne '') && ($trole ne '')) {
2601: my $spec=$trole.'.'.$area;
2602: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2603: if ($trole =~ /^cr\//) {
2604: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2605: } else {
2606: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2607: }
2608: }
2609: }
2610: }
2611: my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
2612: $userroles.='user.adv='.$adv."\n".
2613: 'user.author='.$author."\n";
2614: $env{'user.adv'}=$adv;
2615: }
2616: return $userroles;
2617: }
2618:
2619: sub set_arearole {
2620: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2621: # log the associated role with the area
2622: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2623: return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
2624: }
2625:
2626: sub custom_roleprivs {
2627: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2628: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2629: my $homsvr=homeserver($rauthor,$rdomain);
2630: if ($hostname{$homsvr} ne '') {
2631: my ($rdummy,$roledef)=
2632: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2633: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2634: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2635: if (defined($syspriv)) {
2636: $$allroles{'cm./'}.=':'.$syspriv;
2637: $$allroles{$spec.'./'}.=':'.$syspriv;
2638: }
2639: if ($tdomain ne '') {
2640: if (defined($dompriv)) {
2641: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2642: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2643: }
2644: if (($trest ne '') && (defined($coursepriv))) {
2645: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2646: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2647: }
2648: }
2649: }
2650: }
2651: }
2652:
2653:
2654: sub standard_roleprivs {
2655: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2656: if (defined($pr{$trole.':s'})) {
2657: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2658: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2659: }
2660: if ($tdomain ne '') {
2661: if (defined($pr{$trole.':d'})) {
2662: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2663: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2664: }
2665: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2666: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2667: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2668: }
2669: }
2670: }
2671:
2672: sub set_userprivs {
2673: my ($userroles,$allroles) = @_;
2674: my $author=0;
2675: my $adv=0;
2676: foreach (keys %{$allroles}) {
2677: my %thesepriv=();
2678: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
2679: foreach (split(/:/,$$allroles{$_})) {
2680: if ($_ ne '') {
2681: my ($privilege,$restrictions)=split(/&/,$_);
2682: if ($restrictions eq '') {
2683: $thesepriv{$privilege}='F';
2684: } elsif ($thesepriv{$privilege} ne 'F') {
2685: $thesepriv{$privilege}.=$restrictions;
2686: }
2687: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2688: }
2689: }
2690: my $thesestr='';
2691: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
2692: $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
2693: }
2694: return ($author,$adv);
2695: }
2696:
2697: # --------------------------------------------------------------- get interface
2698:
2699: sub get {
2700: my ($namespace,$storearr,$udomain,$uname)=@_;
2701: my $items='';
2702: foreach (@$storearr) {
2703: $items.=escape($_).'&';
2704: }
2705: $items=~s/\&$//;
2706: if (!$udomain) { $udomain=$env{'user.domain'}; }
2707: if (!$uname) { $uname=$env{'user.name'}; }
2708: my $uhome=&homeserver($uname,$udomain);
2709:
2710: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
2711: my @pairs=split(/\&/,$rep);
2712: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2713: return @pairs;
2714: }
2715: my %returnhash=();
2716: my $i=0;
2717: foreach (@$storearr) {
2718: $returnhash{$_}=&thaw_unescape($pairs[$i]);
2719: $i++;
2720: }
2721: return %returnhash;
2722: }
2723:
2724: # --------------------------------------------------------------- del interface
2725:
2726: sub del {
2727: my ($namespace,$storearr,$udomain,$uname)=@_;
2728: my $items='';
2729: foreach (@$storearr) {
2730: $items.=escape($_).'&';
2731: }
2732: $items=~s/\&$//;
2733: if (!$udomain) { $udomain=$env{'user.domain'}; }
2734: if (!$uname) { $uname=$env{'user.name'}; }
2735: my $uhome=&homeserver($uname,$udomain);
2736:
2737: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
2738: }
2739:
2740: # -------------------------------------------------------------- dump interface
2741:
2742: sub dump {
2743: my ($namespace,$udomain,$uname,$regexp)=@_;
2744: if (!$udomain) { $udomain=$env{'user.domain'}; }
2745: if (!$uname) { $uname=$env{'user.name'}; }
2746: my $uhome=&homeserver($uname,$udomain);
2747: if ($regexp) {
2748: $regexp=&escape($regexp);
2749: } else {
2750: $regexp='.';
2751: }
2752: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
2753: my @pairs=split(/\&/,$rep);
2754: my %returnhash=();
2755: foreach (@pairs) {
2756: my ($key,$value)=split(/=/,$_);
2757: $returnhash{unescape($key)}=&thaw_unescape($value);
2758: }
2759: return %returnhash;
2760: }
2761:
2762: # -------------------------------------------------------------- keys interface
2763:
2764: sub getkeys {
2765: my ($namespace,$udomain,$uname)=@_;
2766: if (!$udomain) { $udomain=$env{'user.domain'}; }
2767: if (!$uname) { $uname=$env{'user.name'}; }
2768: my $uhome=&homeserver($uname,$udomain);
2769: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2770: my @keyarray=();
2771: foreach (split(/\&/,$rep)) {
2772: push (@keyarray,&unescape($_));
2773: }
2774: return @keyarray;
2775: }
2776:
2777: # --------------------------------------------------------------- currentdump
2778: sub currentdump {
2779: my ($courseid,$sdom,$sname)=@_;
2780: $courseid = $env{'request.course.id'} if (! defined($courseid));
2781: $sdom = $env{'user.domain'} if (! defined($sdom));
2782: $sname = $env{'user.name'} if (! defined($sname));
2783: my $uhome = &homeserver($sname,$sdom);
2784: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
2785: return if ($rep =~ /^(error:|no_such_host)/);
2786: #
2787: my %returnhash=();
2788: #
2789: if ($rep eq "unknown_cmd") {
2790: # an old lond will not know currentdump
2791: # Do a dump and make it look like a currentdump
2792: my @tmp = &dump($courseid,$sdom,$sname,'.');
2793: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2794: my %hash = @tmp;
2795: @tmp=();
2796: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
2797: } else {
2798: my @pairs=split(/\&/,$rep);
2799: foreach (@pairs) {
2800: my ($key,$value)=split(/=/,$_);
2801: my ($symb,$param) = split(/:/,$key);
2802: $returnhash{&unescape($symb)}->{&unescape($param)} =
2803: &thaw_unescape($value);
2804: }
2805: }
2806: return %returnhash;
2807: }
2808:
2809: sub convert_dump_to_currentdump{
2810: my %hash = %{shift()};
2811: my %returnhash;
2812: # Code ripped from lond, essentially. The only difference
2813: # here is the unescaping done by lonnet::dump(). Conceivably
2814: # we might run in to problems with parameter names =~ /^v\./
2815: while (my ($key,$value) = each(%hash)) {
2816: my ($v,$symb,$param) = split(/:/,$key);
2817: next if ($v eq 'version' || $symb eq 'keys');
2818: next if (exists($returnhash{$symb}) &&
2819: exists($returnhash{$symb}->{$param}) &&
2820: $returnhash{$symb}->{'v.'.$param} > $v);
2821: $returnhash{$symb}->{$param}=$value;
2822: $returnhash{$symb}->{'v.'.$param}=$v;
2823: }
2824: #
2825: # Remove all of the keys in the hashes which keep track of
2826: # the version of the parameter.
2827: while (my ($symb,$param_hash) = each(%returnhash)) {
2828: # use a foreach because we are going to delete from the hash.
2829: foreach my $key (keys(%$param_hash)) {
2830: delete($param_hash->{$key}) if ($key =~ /^v\./);
2831: }
2832: }
2833: return \%returnhash;
2834: }
2835:
2836: # ------------------------------------------------------ critical inc interface
2837:
2838: sub cinc {
2839: return &inc(@_,'critical');
2840: }
2841:
2842: # --------------------------------------------------------------- inc interface
2843:
2844: sub inc {
2845: my ($namespace,$store,$udomain,$uname,$critical) = @_;
2846: if (!$udomain) { $udomain=$env{'user.domain'}; }
2847: if (!$uname) { $uname=$env{'user.name'}; }
2848: my $uhome=&homeserver($uname,$udomain);
2849: my $items='';
2850: if (! ref($store)) {
2851: # got a single value, so use that instead
2852: $items = &escape($store).'=&';
2853: } elsif (ref($store) eq 'SCALAR') {
2854: $items = &escape($$store).'=&';
2855: } elsif (ref($store) eq 'ARRAY') {
2856: $items = join('=&',map {&escape($_);} @{$store});
2857: } elsif (ref($store) eq 'HASH') {
2858: while (my($key,$value) = each(%{$store})) {
2859: $items.= &escape($key).'='.&escape($value).'&';
2860: }
2861: }
2862: $items=~s/\&$//;
2863: if ($critical) {
2864: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
2865: } else {
2866: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
2867: }
2868: }
2869:
2870: # --------------------------------------------------------------- put interface
2871:
2872: sub put {
2873: my ($namespace,$storehash,$udomain,$uname)=@_;
2874: if (!$udomain) { $udomain=$env{'user.domain'}; }
2875: if (!$uname) { $uname=$env{'user.name'}; }
2876: my $uhome=&homeserver($uname,$udomain);
2877: my $items='';
2878: foreach (keys %$storehash) {
2879: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
2880: }
2881: $items=~s/\&$//;
2882: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
2883: }
2884:
2885: # ------------------------------------------------------------ newput interface
2886:
2887: sub newput {
2888: my ($namespace,$storehash,$udomain,$uname)=@_;
2889: if (!$udomain) { $udomain=$env{'user.domain'}; }
2890: if (!$uname) { $uname=$env{'user.name'}; }
2891: my $uhome=&homeserver($uname,$udomain);
2892: my $items='';
2893: foreach my $key (keys(%$storehash)) {
2894: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2895: }
2896: $items=~s/\&$//;
2897: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
2898: }
2899:
2900: # --------------------------------------------------------- putstore interface
2901:
2902: sub putstore {
2903: my ($namespace,$storehash,$udomain,$uname)=@_;
2904: if (!$udomain) { $udomain=$env{'user.domain'}; }
2905: if (!$uname) { $uname=$env{'user.name'}; }
2906: my $uhome=&homeserver($uname,$udomain);
2907: my $items='';
2908: my %allitems = ();
2909: foreach (keys %$storehash) {
2910: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
2911: my $key = $1.':keys:'.$2;
2912: $allitems{$key} .= $3.':';
2913: }
2914: $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
2915: }
2916: foreach (keys %allitems) {
2917: $allitems{$_} =~ s/\:$//;
2918: $items.= $_.'='.$allitems{$_}.'&';
2919: }
2920: $items=~s/\&$//;
2921: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
2922: }
2923:
2924: # ------------------------------------------------------ critical put interface
2925:
2926: sub cput {
2927: my ($namespace,$storehash,$udomain,$uname)=@_;
2928: if (!$udomain) { $udomain=$env{'user.domain'}; }
2929: if (!$uname) { $uname=$env{'user.name'}; }
2930: my $uhome=&homeserver($uname,$udomain);
2931: my $items='';
2932: foreach (keys %$storehash) {
2933: $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
2934: }
2935: $items=~s/\&$//;
2936: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
2937: }
2938:
2939: # -------------------------------------------------------------- eget interface
2940:
2941: sub eget {
2942: my ($namespace,$storearr,$udomain,$uname)=@_;
2943: my $items='';
2944: foreach (@$storearr) {
2945: $items.=escape($_).'&';
2946: }
2947: $items=~s/\&$//;
2948: if (!$udomain) { $udomain=$env{'user.domain'}; }
2949: if (!$uname) { $uname=$env{'user.name'}; }
2950: my $uhome=&homeserver($uname,$udomain);
2951: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
2952: my @pairs=split(/\&/,$rep);
2953: my %returnhash=();
2954: my $i=0;
2955: foreach (@$storearr) {
2956: $returnhash{$_}=&thaw_unescape($pairs[$i]);
2957: $i++;
2958: }
2959: return %returnhash;
2960: }
2961:
2962: # ------------------------------------------------------------ tmpput interface
2963: sub tmpput {
2964: my ($storehash,$server)=@_;
2965: my $items='';
2966: foreach (keys(%$storehash)) {
2967: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
2968: }
2969: $items=~s/\&$//;
2970: return &reply("tmpput:$items",$server);
2971: }
2972:
2973: # ------------------------------------------------------------ tmpget interface
2974: sub tmpget {
2975: my ($token)=@_;
2976: my $rep=&reply("tmpget:$token",$perlvar{'lonHostID'});
2977: my %returnhash;
2978: foreach my $item (split(/\&/,$rep)) {
2979: my ($key,$value)=split(/=/,$item);
2980: $returnhash{&unescape($key)}=&thaw_unescape($value);
2981: }
2982: return %returnhash;
2983: }
2984:
2985: # ---------------------------------------------- Custom access rule evaluation
2986:
2987: sub customaccess {
2988: my ($priv,$uri)=@_;
2989: my ($urole,$urealm)=split(/\./,$env{'request.role'});
2990: $urealm=~s/^\W//;
2991: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
2992: my $access=0;
2993: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
2994: my ($effect,$realm,$role)=split(/\:/,$_);
2995: if ($role) {
2996: if ($role ne $urole) { next; }
2997: }
2998: foreach (split(/\s*\,\s*/,$realm)) {
2999: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
3000: if ($tdom) {
3001: if ($tdom ne $udom) { next; }
3002: }
3003: if ($tcrs) {
3004: if ($tcrs ne $ucrs) { next; }
3005: }
3006: if ($tsec) {
3007: if ($tsec ne $usec) { next; }
3008: }
3009: $access=($effect eq 'allow');
3010: last;
3011: }
3012: if ($realm eq '' && $role eq '') {
3013: $access=($effect eq 'allow');
3014: }
3015: }
3016: return $access;
3017: }
3018:
3019: # ------------------------------------------------- Check for a user privilege
3020:
3021: sub allowed {
3022: my ($priv,$uri,$symb)=@_;
3023: $uri=&deversion($uri);
3024: my $orguri=$uri;
3025: $uri=&declutter($uri);
3026:
3027:
3028:
3029: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3030: # Free bre access to adm and meta resources
3031: if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|))
3032: || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
3033: return 'F';
3034: }
3035:
3036: # Free bre access to user's own portfolio contents
3037: my ($space,$domain,$name,$dir)=split('/',$uri);
3038: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3039: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
3040: return 'F';
3041: }
3042:
3043: # Free bre to public access
3044:
3045: if ($priv eq 'bre') {
3046: my $copyright=&metadata($uri,'copyright');
3047: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3048: return 'F';
3049: }
3050: if ($copyright eq 'priv') {
3051: $uri=~/([^\/]+)\/([^\/]+)\//;
3052: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3053: return '';
3054: }
3055: }
3056: if ($copyright eq 'domain') {
3057: $uri=~/([^\/]+)\/([^\/]+)\//;
3058: unless (($env{'user.domain'} eq $1) ||
3059: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3060: return '';
3061: }
3062: }
3063: if ($env{'request.role'}=~ /li\.\//) {
3064: # Library role, so allow browsing of resources in this domain.
3065: return 'F';
3066: }
3067: if ($copyright eq 'custom') {
3068: unless (&customaccess($priv,$uri)) { return ''; }
3069: }
3070: }
3071: # Domain coordinator is trying to create a course
3072: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3073: # uri is the requested domain in this case.
3074: # comparison to 'request.role.domain' shows if the user has selected
3075: # a role of dc for the domain in question.
3076: return 'F' if ($uri eq $env{'request.role.domain'});
3077: }
3078:
3079: my $thisallowed='';
3080: my $statecond=0;
3081: my $courseprivid='';
3082:
3083: # Course
3084:
3085: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3086: $thisallowed.=$1;
3087: }
3088:
3089: # Domain
3090:
3091: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3092: =~/\Q$priv\E\&([^\:]*)/) {
3093: $thisallowed.=$1;
3094: }
3095:
3096: # Course: uri itself is a course
3097: my $courseuri=$uri;
3098: $courseuri=~s/\_(\d)/\/$1/;
3099: $courseuri=~s/^([^\/])/\/$1/;
3100:
3101: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3102: =~/\Q$priv\E\&([^\:]*)/) {
3103: $thisallowed.=$1;
3104: }
3105:
3106: # URI is an uploaded document for this course, default permissions don't matter
3107: # not allowing 'edit' access (editupload) to uploaded course docs
3108: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3109: $thisallowed='';
3110: my ($match)=&is_on_map($uri);
3111: if ($match) {
3112: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3113: =~/\Q$priv\E\&([^\:]*)/) {
3114: $thisallowed.=$1;
3115: }
3116: } else {
3117: my $refuri=$env{'httpref.'.$orguri};
3118: if ($refuri) {
3119: if ($refuri =~ m|^/adm/|) {
3120: $thisallowed='F';
3121: } else {
3122: $refuri=&declutter($refuri);
3123: my ($match) = &is_on_map($refuri);
3124: if ($match) {
3125: $thisallowed='F';
3126: }
3127: }
3128: }
3129: }
3130: }
3131:
3132: # Full access at system, domain or course-wide level? Exit.
3133:
3134: if ($thisallowed=~/F/) {
3135: return 'F';
3136: }
3137:
3138: # If this is generating or modifying users, exit with special codes
3139:
3140: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3141: if (($priv eq 'cca') || ($priv eq 'caa')) {
3142: my ($audom,$auname)=split('/',$uri);
3143: # no author name given, so this just checks on the general right to make a co-author in this domain
3144: unless ($auname) { return $thisallowed; }
3145: # an author name is given, so we are about to actually make a co-author for a certain account
3146: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3147: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3148: ($audom ne $env{'request.role.domain'}))) { return ''; }
3149: }
3150: return $thisallowed;
3151: }
3152: #
3153: # Gathered so far: system, domain and course wide privileges
3154: #
3155: # Course: See if uri or referer is an individual resource that is part of
3156: # the course
3157:
3158: if ($env{'request.course.id'}) {
3159:
3160: $courseprivid=$env{'request.course.id'};
3161: if ($env{'request.course.sec'}) {
3162: $courseprivid.='/'.$env{'request.course.sec'};
3163: }
3164: $courseprivid=~s/\_/\//;
3165: my $checkreferer=1;
3166: my ($match,$cond)=&is_on_map($uri);
3167: if ($match) {
3168: $statecond=$cond;
3169: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3170: =~/\Q$priv\E\&([^\:]*)/) {
3171: $thisallowed.=$1;
3172: $checkreferer=0;
3173: }
3174: }
3175:
3176: if ($checkreferer) {
3177: my $refuri=$env{'httpref.'.$orguri};
3178: unless ($refuri) {
3179: foreach (keys %env) {
3180: if ($_=~/^httpref\..*\*/) {
3181: my $pattern=$_;
3182: $pattern=~s/^httpref\.\/res\///;
3183: $pattern=~s/\*/\[\^\/\]\+/g;
3184: $pattern=~s/\//\\\//g;
3185: if ($orguri=~/$pattern/) {
3186: $refuri=$env{$_};
3187: }
3188: }
3189: }
3190: }
3191:
3192: if ($refuri) {
3193: $refuri=&declutter($refuri);
3194: my ($match,$cond)=&is_on_map($refuri);
3195: if ($match) {
3196: my $refstatecond=$cond;
3197: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3198: =~/\Q$priv\E\&([^\:]*)/) {
3199: $thisallowed.=$1;
3200: $uri=$refuri;
3201: $statecond=$refstatecond;
3202: }
3203: }
3204: }
3205: }
3206: }
3207:
3208: #
3209: # Gathered now: all privileges that could apply, and condition number
3210: #
3211: #
3212: # Full or no access?
3213: #
3214:
3215: if ($thisallowed=~/F/) {
3216: return 'F';
3217: }
3218:
3219: unless ($thisallowed) {
3220: return '';
3221: }
3222:
3223: # Restrictions exist, deal with them
3224: #
3225: # C:according to course preferences
3226: # R:according to resource settings
3227: # L:unless locked
3228: # X:according to user session state
3229: #
3230:
3231: # Possibly locked functionality, check all courses
3232: # Locks might take effect only after 10 minutes cache expiration for other
3233: # courses, and 2 minutes for current course
3234:
3235: my $envkey;
3236: if ($thisallowed=~/L/) {
3237: foreach $envkey (keys %env) {
3238: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3239: my $courseid=$2;
3240: my $roleid=$1.'.'.$2;
3241: $courseid=~s/^\///;
3242: my $expiretime=600;
3243: if ($env{'request.role'} eq $roleid) {
3244: $expiretime=120;
3245: }
3246: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3247: my $prefix='course.'.$cdom.'_'.$cnum.'.';
3248: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
3249: &coursedescription($courseid);
3250: }
3251: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3252: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3253: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3254: &log($env{'user.domain'},$env{'user.name'},
3255: $env{'user.home'},
3256: 'Locked by res: '.$priv.' for '.$uri.' due to '.
3257: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3258: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3259: return '';
3260: }
3261: }
3262: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3263: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3264: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3265: &log($env{'user.domain'},$env{'user.name'},
3266: $env{'user.home'},
3267: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
3268: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3269: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3270: return '';
3271: }
3272: }
3273: }
3274: }
3275: }
3276:
3277: #
3278: # Rest of the restrictions depend on selected course
3279: #
3280:
3281: unless ($env{'request.course.id'}) {
3282: return '1';
3283: }
3284:
3285: #
3286: # Now user is definitely in a course
3287: #
3288:
3289:
3290: # Course preferences
3291:
3292: if ($thisallowed=~/C/) {
3293: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3294: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3295: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
3296: =~/\Q$rolecode\E/) {
3297: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3298: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3299: $env{'request.course.id'});
3300: return '';
3301: }
3302:
3303: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
3304: =~/\Q$unamedom\E/) {
3305: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3306: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3307: $env{'request.course.id'});
3308: return '';
3309: }
3310: }
3311:
3312: # Resource preferences
3313:
3314: if ($thisallowed=~/R/) {
3315: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3316: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
3317: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3318: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3319: return '';
3320: }
3321: }
3322:
3323: # Restricted by state or randomout?
3324:
3325: if ($thisallowed=~/X/) {
3326: if ($env{'acc.randomout'}) {
3327: if (!$symb) { $symb=&symbread($uri,1); }
3328: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
3329: return '';
3330: }
3331: }
3332: if (&condval($statecond)) {
3333: return '2';
3334: } else {
3335: return '';
3336: }
3337: }
3338:
3339: return 'F';
3340: }
3341:
3342: # --------------------------------------------------- Is a resource on the map?
3343:
3344: sub is_on_map {
3345: my $uri=&deversion(&declutter(shift));
3346: my @uriparts=split(/\//,$uri);
3347: my $filename=$uriparts[$#uriparts];
3348: my $pathname=$uri;
3349: $pathname=~s|/\Q$filename\E$||;
3350: $pathname=~s/^adm\/wrapper\///;
3351: #Trying to find the conditional for the file
3352: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
3353: /\&\Q$filename\E\:([\d\|]+)\&/);
3354: if ($match) {
3355: return (1,$1);
3356: } else {
3357: return (0,0);
3358: }
3359: }
3360:
3361: # --------------------------------------------------------- Get symb from alias
3362:
3363: sub get_symb_from_alias {
3364: my $symb=shift;
3365: my ($map,$resid,$url)=&decode_symb($symb);
3366: # Already is a symb
3367: if ($url) { return $symb; }
3368: # Must be an alias
3369: my $aliassymb='';
3370: my %bighash;
3371: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
3372: &GDBM_READER(),0640)) {
3373: my $rid=$bighash{'mapalias_'.$symb};
3374: if ($rid) {
3375: my ($mapid,$resid)=split(/\./,$rid);
3376: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3377: $resid,$bighash{'src_'.$rid});
3378: }
3379: untie %bighash;
3380: }
3381: return $aliassymb;
3382: }
3383:
3384: # ----------------------------------------------------------------- Define Role
3385:
3386: sub definerole {
3387: if (allowed('mcr','/')) {
3388: my ($rolename,$sysrole,$domrole,$courole)=@_;
3389: foreach (split(':',$sysrole)) {
3390: my ($crole,$cqual)=split(/\&/,$_);
3391: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3392: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3393: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
3394: return "refused:s:$crole&$cqual";
3395: }
3396: }
3397: }
3398: foreach (split(':',$domrole)) {
3399: my ($crole,$cqual)=split(/\&/,$_);
3400: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3401: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3402: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
3403: return "refused:d:$crole&$cqual";
3404: }
3405: }
3406: }
3407: foreach (split(':',$courole)) {
3408: my ($crole,$cqual)=split(/\&/,$_);
3409: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3410: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3411: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
3412: return "refused:c:$crole&$cqual";
3413: }
3414: }
3415: }
3416: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3417: "$env{'user.domain'}:$env{'user.name'}:".
3418: "rolesdef_$rolename=".
3419: escape($sysrole.'_'.$domrole.'_'.$courole);
3420: return reply($command,$env{'user.home'});
3421: } else {
3422: return 'refused';
3423: }
3424: }
3425:
3426: # ---------------- Make a metadata query against the network of library servers
3427:
3428: sub metadata_query {
3429: my ($query,$custom,$customshow,$server_array)=@_;
3430: my %rhash;
3431: my @server_list = (defined($server_array) ? @$server_array
3432: : keys(%libserv) );
3433: for my $server (@server_list) {
3434: unless ($custom or $customshow) {
3435: my $reply=&reply("querysend:".&escape($query),$server);
3436: $rhash{$server}=$reply;
3437: }
3438: else {
3439: my $reply=&reply("querysend:".&escape($query).':'.
3440: &escape($custom).':'.&escape($customshow),
3441: $server);
3442: $rhash{$server}=$reply;
3443: }
3444: }
3445: return \%rhash;
3446: }
3447:
3448: # ----------------------------------------- Send log queries and wait for reply
3449:
3450: sub log_query {
3451: my ($uname,$udom,$query,%filters)=@_;
3452: my $uhome=&homeserver($uname,$udom);
3453: if ($uhome eq 'no_host') { return 'error: no_host'; }
3454: my $uhost=$hostname{$uhome};
3455: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
3456: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3457: $uhome);
3458: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
3459: return get_query_reply($queryid);
3460: }
3461:
3462: # ------- Request retrieval of institutional classlists for course(s)
3463:
3464: sub fetch_enrollment_query {
3465: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
3466: my $homeserver;
3467: my $maxtries = 1;
3468: if ($context eq 'automated') {
3469: $homeserver = $perlvar{'lonHostID'};
3470: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
3471: } else {
3472: $homeserver = &homeserver($cnum,$dom);
3473: }
3474: my $host=$hostname{$homeserver};
3475: my $cmd = '';
3476: foreach (keys %{$affiliatesref}) {
3477: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
3478: }
3479: $cmd =~ s/%%$//;
3480: $cmd = &escape($cmd);
3481: my $query = 'fetchenrollment';
3482: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
3483: unless ($queryid=~/^\Q$host\E\_/) {
3484: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
3485: return 'error: '.$queryid;
3486: }
3487: my $reply = &get_query_reply($queryid);
3488: my $tries = 1;
3489: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3490: $reply = &get_query_reply($queryid);
3491: $tries ++;
3492: }
3493: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
3494: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
3495: } else {
3496: my @responses = split/:/,$reply;
3497: if ($homeserver eq $perlvar{'lonHostID'}) {
3498: foreach (@responses) {
3499: my ($key,$value) = split/=/,$_;
3500: $$replyref{$key} = $value;
3501: }
3502: } else {
3503: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3504: foreach (@responses) {
3505: my ($key,$value) = split/=/,$_;
3506: $$replyref{$key} = $value;
3507: if ($value > 0) {
3508: foreach (@{$$affiliatesref{$key}}) {
3509: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
3510: my $destname = $pathname.'/'.$filename;
3511: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
3512: if ($xml_classlist =~ /^error/) {
3513: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
3514: } else {
3515: if ( open(FILE,">$destname") ) {
3516: print FILE &unescape($xml_classlist);
3517: close(FILE);
3518: } else {
3519: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
3520: }
3521: }
3522: }
3523: }
3524: }
3525: }
3526: return 'ok';
3527: }
3528: return 'error';
3529: }
3530:
3531: sub get_query_reply {
3532: my $queryid=shift;
3533: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
3534: my $reply='';
3535: for (1..100) {
3536: sleep 2;
3537: if (-e $replyfile.'.end') {
3538: if (open(my $fh,$replyfile)) {
3539: $reply.=<$fh>;
3540: close($fh);
3541: } else { return 'error: reply_file_error'; }
3542: return &unescape($reply);
3543: }
3544: }
3545: return 'timeout:'.$queryid;
3546: }
3547:
3548: sub courselog_query {
3549: #
3550: # possible filters:
3551: # url: url or symb
3552: # username
3553: # domain
3554: # action: view, submit, grade
3555: # start: timestamp
3556: # end: timestamp
3557: #
3558: my (%filters)=@_;
3559: unless ($env{'request.course.id'}) { return 'no_course'; }
3560: if ($filters{'url'}) {
3561: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
3562: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
3563: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
3564: }
3565: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
3566: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3567: return &log_query($cname,$cdom,'courselog',%filters);
3568: }
3569:
3570: sub userlog_query {
3571: my ($uname,$udom,%filters)=@_;
3572: return &log_query($uname,$udom,'userlog',%filters);
3573: }
3574:
3575: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
3576:
3577: sub auto_run {
3578: my ($cnum,$cdom) = @_;
3579: my $homeserver = &homeserver($cnum,$cdom);
3580: my $response = &reply('autorun:'.$cdom,$homeserver);
3581: return $response;
3582: }
3583:
3584: sub auto_get_sections {
3585: my ($cnum,$cdom,$inst_coursecode) = @_;
3586: my $homeserver = &homeserver($cnum,$cdom);
3587: my @secs = ();
3588: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
3589: unless ($response eq 'refused') {
3590: @secs = split/:/,$response;
3591: }
3592: return @secs;
3593: }
3594:
3595: sub auto_new_course {
3596: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
3597: my $homeserver = &homeserver($cnum,$cdom);
3598: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
3599: return $response;
3600: }
3601:
3602: sub auto_validate_courseID {
3603: my ($cnum,$cdom,$inst_course_id) = @_;
3604: my $homeserver = &homeserver($cnum,$cdom);
3605: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
3606: return $response;
3607: }
3608:
3609: sub auto_create_password {
3610: my ($cnum,$cdom,$authparam) = @_;
3611: my $homeserver = &homeserver($cnum,$cdom);
3612: my $create_passwd = 0;
3613: my $authchk = '';
3614: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
3615: if ($response eq 'refused') {
3616: $authchk = 'refused';
3617: } else {
3618: ($authparam,$create_passwd,$authchk) = split/:/,$response;
3619: }
3620: return ($authparam,$create_passwd,$authchk);
3621: }
3622:
3623: sub auto_instcode_format {
3624: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
3625: my $courses = '';
3626: my $homeserver;
3627: if ($caller eq 'global') {
3628: foreach my $tryserver (keys %libserv) {
3629: if ($hostdom{$tryserver} eq $codedom) {
3630: $homeserver = $tryserver;
3631: last;
3632: }
3633: }
3634: if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
3635: $homeserver = &homeserver($env{'user.name'},$codedom);
3636: }
3637: } else {
3638: $homeserver = &homeserver($caller,$codedom);
3639: }
3640: foreach (keys %{$instcodes}) {
3641: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
3642: }
3643: chop($courses);
3644: my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
3645: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
3646: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
3647: %{$codes} = &str2hash($codes_str);
3648: @{$codetitles} = &str2array($codetitles_str);
3649: %{$cat_titles} = &str2hash($cat_titles_str);
3650: %{$cat_order} = &str2hash($cat_order_str);
3651: return 'ok';
3652: }
3653: return $response;
3654: }
3655:
3656: # ------------------------------------------------------------------ Plain Text
3657:
3658: sub plaintext {
3659: my $short=shift;
3660: return &Apache::lonlocal::mt($prp{$short});
3661: }
3662:
3663: # ----------------------------------------------------------------- Assign Role
3664:
3665: sub assignrole {
3666: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
3667: my $mrole;
3668: if ($role =~ /^cr\//) {
3669: my $cwosec=$url;
3670: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
3671: unless (&allowed('ccr',$cwosec)) {
3672: &logthis('Refused custom assignrole: '.
3673: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3674: $env{'user.name'}.' at '.$env{'user.domain'});
3675: return 'refused';
3676: }
3677: $mrole='cr';
3678: } else {
3679: my $cwosec=$url;
3680: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
3681: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
3682: &logthis('Refused assignrole: '.
3683: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3684: $env{'user.name'}.' at '.$env{'user.domain'});
3685: return 'refused';
3686: }
3687: $mrole=$role;
3688: }
3689: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3690: "$udom:$uname:$url".'_'."$mrole=$role";
3691: if ($end) { $command.='_'.$end; }
3692: if ($start) {
3693: if ($end) {
3694: $command.='_'.$start;
3695: } else {
3696: $command.='_0_'.$start;
3697: }
3698: }
3699: # actually delete
3700: if ($deleteflag) {
3701: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
3702: # modify command to delete the role
3703: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
3704: "$udom:$uname:$url".'_'."$mrole";
3705: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
3706: # set start and finish to negative values for userrolelog
3707: $start=-1;
3708: $end=-1;
3709: }
3710: }
3711: # send command
3712: my $answer=&reply($command,&homeserver($uname,$udom));
3713: # log new user role if status is ok
3714: if ($answer eq 'ok') {
3715: &userrolelog($role,$uname,$udom,$url,$start,$end);
3716: }
3717: return $answer;
3718: }
3719:
3720: # -------------------------------------------------- Modify user authentication
3721: # Overrides without validation
3722:
3723: sub modifyuserauth {
3724: my ($udom,$uname,$umode,$upass)=@_;
3725: my $uhome=&homeserver($uname,$udom);
3726: unless (&allowed('mau',$udom)) { return 'refused'; }
3727: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
3728: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
3729: ' in domain '.$env{'request.role.domain'});
3730: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
3731: &escape($upass),$uhome);
3732: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
3733: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
3734: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3735: &log($udom,,$uname,$uhome,
3736: 'Authentication changed by '.$env{'user.domain'}.', '.
3737: $env{'user.name'}.', '.$umode.
3738: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3739: unless ($reply eq 'ok') {
3740: &logthis('Authentication mode error: '.$reply);
3741: return 'error: '.$reply;
3742: }
3743: return 'ok';
3744: }
3745:
3746: # --------------------------------------------------------------- Modify a user
3747:
3748: sub modifyuser {
3749: my ($udom, $uname, $uid,
3750: $umode, $upass, $first,
3751: $middle, $last, $gene,
3752: $forceid, $desiredhome, $email)=@_;
3753: $udom=~s/\W//g;
3754: $uname=~s/\W//g;
3755: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
3756: $umode.', '.$first.', '.$middle.', '.
3757: $last.', '.$gene.'(forceid: '.$forceid.')'.
3758: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
3759: ' desiredhome not specified').
3760: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
3761: ' in domain '.$env{'request.role.domain'});
3762: my $uhome=&homeserver($uname,$udom,'true');
3763: # ----------------------------------------------------------------- Create User
3764: if (($uhome eq 'no_host') &&
3765: (($umode && $upass) || ($umode eq 'localauth'))) {
3766: my $unhome='';
3767: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
3768: $unhome = $desiredhome;
3769: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
3770: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
3771: } else { # load balancing routine for determining $unhome
3772: my $tryserver;
3773: my $loadm=10000000;
3774: foreach $tryserver (keys %libserv) {
3775: if ($hostdom{$tryserver} eq $udom) {
3776: my $answer=reply('load',$tryserver);
3777: if (($answer=~/\d+/) && ($answer<$loadm)) {
3778: $loadm=$answer;
3779: $unhome=$tryserver;
3780: }
3781: }
3782: }
3783: }
3784: if (($unhome eq '') || ($unhome eq 'no_host')) {
3785: return 'error: unable to find a home server for '.$uname.
3786: ' in domain '.$udom;
3787: }
3788: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
3789: &escape($upass),$unhome);
3790: unless ($reply eq 'ok') {
3791: return 'error: '.$reply;
3792: }
3793: $uhome=&homeserver($uname,$udom,'true');
3794: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
3795: return 'error: unable verify users home machine.';
3796: }
3797: } # End of creation of new user
3798: # ---------------------------------------------------------------------- Add ID
3799: if ($uid) {
3800: $uid=~tr/A-Z/a-z/;
3801: my %uidhash=&idrget($udom,$uname);
3802: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
3803: && (!$forceid)) {
3804: unless ($uid eq $uidhash{$uname}) {
3805: return 'error: user id "'.$uid.'" does not match '.
3806: 'current user id "'.$uidhash{$uname}.'".';
3807: }
3808: } else {
3809: &idput($udom,($uname => $uid));
3810: }
3811: }
3812: # -------------------------------------------------------------- Add names, etc
3813: my @tmp=&get('environment',
3814: ['firstname','middlename','lastname','generation'],
3815: $udom,$uname);
3816: my %names;
3817: if ($tmp[0] =~ m/^error:.*/) {
3818: %names=();
3819: } else {
3820: %names = @tmp;
3821: }
3822: #
3823: # Make sure to not trash student environment if instructor does not bother
3824: # to supply name and email information
3825: #
3826: if ($first) { $names{'firstname'} = $first; }
3827: if (defined($middle)) { $names{'middlename'} = $middle; }
3828: if ($last) { $names{'lastname'} = $last; }
3829: if (defined($gene)) { $names{'generation'} = $gene; }
3830: if ($email) {
3831: $email=~s/[^\w\@\.\-\,]//gs;
3832: if ($email=~/\@/) { $names{'notification'} = $email;
3833: $names{'critnotification'} = $email;
3834: $names{'permanentemail'} = $email; }
3835: }
3836: my $reply = &put('environment', \%names, $udom,$uname);
3837: if ($reply ne 'ok') { return 'error: '.$reply; }
3838: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
3839: $umode.', '.$first.', '.$middle.', '.
3840: $last.', '.$gene.' by '.
3841: $env{'user.name'}.' at '.$env{'user.domain'});
3842: return 'ok';
3843: }
3844:
3845: # -------------------------------------------------------------- Modify student
3846:
3847: sub modifystudent {
3848: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
3849: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
3850: if (!$cid) {
3851: unless ($cid=$env{'request.course.id'}) {
3852: return 'not_in_class';
3853: }
3854: }
3855: # --------------------------------------------------------------- Make the user
3856: my $reply=&modifyuser
3857: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
3858: $desiredhome,$email);
3859: unless ($reply eq 'ok') { return $reply; }
3860: # This will cause &modify_student_enrollment to get the uid from the
3861: # students environment
3862: $uid = undef if (!$forceid);
3863: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
3864: $gene,$usec,$end,$start,$type,$locktype,$cid);
3865: return $reply;
3866: }
3867:
3868: sub modify_student_enrollment {
3869: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
3870: my ($cdom,$cnum,$chome);
3871: if (!$cid) {
3872: unless ($cid=$env{'request.course.id'}) {
3873: return 'not_in_class';
3874: }
3875: $cdom=$env{'course.'.$cid.'.domain'};
3876: $cnum=$env{'course.'.$cid.'.num'};
3877: } else {
3878: ($cdom,$cnum)=split(/_/,$cid);
3879: }
3880: $chome=$env{'course.'.$cid.'.home'};
3881: if (!$chome) {
3882: $chome=&homeserver($cnum,$cdom);
3883: }
3884: if (!$chome) { return 'unknown_course'; }
3885: # Make sure the user exists
3886: my $uhome=&homeserver($uname,$udom);
3887: if (($uhome eq '') || ($uhome eq 'no_host')) {
3888: return 'error: no such user';
3889: }
3890: # Get student data if we were not given enough information
3891: if (!defined($first) || $first eq '' ||
3892: !defined($last) || $last eq '' ||
3893: !defined($uid) || $uid eq '' ||
3894: !defined($middle) || $middle eq '' ||
3895: !defined($gene) || $gene eq '') {
3896: # They did not supply us with enough data to enroll the student, so
3897: # we need to pick up more information.
3898: my %tmp = &get('environment',
3899: ['firstname','middlename','lastname', 'generation','id']
3900: ,$udom,$uname);
3901:
3902: #foreach (keys(%tmp)) {
3903: # &logthis("key $_ = ".$tmp{$_});
3904: #}
3905: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
3906: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
3907: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
3908: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
3909: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
3910: }
3911: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
3912: my $reply=cput('classlist',
3913: {"$uname:$udom" =>
3914: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
3915: $cdom,$cnum);
3916: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
3917: return 'error: '.$reply;
3918: } else {
3919: &devalidate_getsection_cache($udom,$uname,$cid);
3920: }
3921: # Add student role to user
3922: my $uurl='/'.$cid;
3923: $uurl=~s/\_/\//g;
3924: if ($usec) {
3925: $uurl.='/'.$usec;
3926: }
3927: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
3928: }
3929:
3930: sub format_name {
3931: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
3932: my $name;
3933: if ($first ne 'lastname') {
3934: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
3935: } else {
3936: if ($lastname=~/\S/) {
3937: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
3938: $name=~s/\s+,/,/;
3939: } else {
3940: $name.= $firstname.' '.$middlename.' '.$generation;
3941: }
3942: }
3943: $name=~s/^\s+//;
3944: $name=~s/\s+$//;
3945: $name=~s/\s+/ /g;
3946: return $name;
3947: }
3948:
3949: # ------------------------------------------------- Write to course preferences
3950:
3951: sub writecoursepref {
3952: my ($courseid,%prefs)=@_;
3953: $courseid=~s/^\///;
3954: $courseid=~s/\_/\//g;
3955: my ($cdomain,$cnum)=split(/\//,$courseid);
3956: my $chome=homeserver($cnum,$cdomain);
3957: if (($chome eq '') || ($chome eq 'no_host')) {
3958: return 'error: no such course';
3959: }
3960: my $cstring='';
3961: foreach (keys %prefs) {
3962: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
3963: }
3964: $cstring=~s/\&$//;
3965: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3966: }
3967:
3968: # ---------------------------------------------------------- Make/modify course
3969:
3970: sub createcourse {
3971: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
3972: $url=&declutter($url);
3973: my $cid='';
3974: unless (&allowed('ccc',$udom)) {
3975: return 'refused';
3976: }
3977: # ------------------------------------------------------------------- Create ID
3978: my $uname=int(1+rand(9)).
3979: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
3980: substr($$.time,0,5).unpack("H8",pack("I32",time)).
3981: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3982: # ----------------------------------------------- Make sure that does not exist
3983: my $uhome=&homeserver($uname,$udom,'true');
3984: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3985: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3986: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3987: $uhome=&homeserver($uname,$udom,'true');
3988: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3989: return 'error: unable to generate unique course-ID';
3990: }
3991: }
3992: # ------------------------------------------------ Check supplied server name
3993: $course_server = $env{'user.homeserver'} if (! defined($course_server));
3994: if (! exists($libserv{$course_server})) {
3995: return 'error:bad server name '.$course_server;
3996: }
3997: # ------------------------------------------------------------- Make the course
3998: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
3999: $course_server);
4000: unless ($reply eq 'ok') { return 'error: '.$reply; }
4001: $uhome=&homeserver($uname,$udom,'true');
4002: if (($uhome eq '') || ($uhome eq 'no_host')) {
4003: return 'error: no such course';
4004: }
4005: # ----------------------------------------------------------------- Course made
4006: # log existence
4007: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
4008: ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
4009: &flushcourselogs();
4010: # set toplevel url
4011: my $topurl=$url;
4012: unless ($nonstandard) {
4013: # ------------------------------------------ For standard courses, make top url
4014: my $mapurl=&clutter($url);
4015: if ($mapurl eq '/res/') { $mapurl=''; }
4016: $env{'form.initmap'}=(<<ENDINITMAP);
4017: <map>
4018: <resource id="1" type="start"></resource>
4019: <resource id="2" src="$mapurl"></resource>
4020: <resource id="3" type="finish"></resource>
4021: <link index="1" from="1" to="2"></link>
4022: <link index="2" from="2" to="3"></link>
4023: </map>
4024: ENDINITMAP
4025: $topurl=&declutter(
4026: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
4027: );
4028: }
4029: # ----------------------------------------------------------- Write preferences
4030: &writecoursepref($udom.'_'.$uname,
4031: ('description' => $description,
4032: 'url' => $topurl));
4033: return '/'.$udom.'/'.$uname;
4034: }
4035:
4036: # ---------------------------------------------------------- Assign Custom Role
4037:
4038: sub assigncustomrole {
4039: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
4040: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
4041: $end,$start,$deleteflag);
4042: }
4043:
4044: # ----------------------------------------------------------------- Revoke Role
4045:
4046: sub revokerole {
4047: my ($udom,$uname,$url,$role,$deleteflag)=@_;
4048: my $now=time;
4049: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
4050: }
4051:
4052: # ---------------------------------------------------------- Revoke Custom Role
4053:
4054: sub revokecustomrole {
4055: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
4056: my $now=time;
4057: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
4058: $deleteflag);
4059: }
4060:
4061: # ------------------------------------------------------------ Disk usage
4062: sub diskusage {
4063: my ($udom,$uname,$directoryRoot)=@_;
4064: $directoryRoot =~ s/\/$//;
4065: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
4066: return $listing;
4067: }
4068:
4069: sub is_locked {
4070: my ($file_name, $domain, $user) = @_;
4071: my @check;
4072: my $is_locked;
4073: push @check, $file_name;
4074: my %locked = &get('file_permissions',\@check,
4075: $env{'user.domain'},$env{'user.name'});
4076: my ($tmp)=keys(%locked);
4077: if ($tmp=~/^error:/) { undef(%locked); }
4078:
4079: if (ref($locked{$file_name}) eq 'ARRAY') {
4080: $is_locked = 'true';
4081: } else {
4082: $is_locked = 'false';
4083: }
4084: }
4085:
4086: # ------------------------------------------------------------- Mark as Read Only
4087:
4088: sub mark_as_readonly {
4089: my ($domain,$user,$files,$what) = @_;
4090: my %current_permissions = &dump('file_permissions',$domain,$user);
4091: my ($tmp)=keys(%current_permissions);
4092: if ($tmp=~/^error:/) { undef(%current_permissions); }
4093: foreach my $file (@{$files}) {
4094: push(@{$current_permissions{$file}},$what);
4095: }
4096: &put('file_permissions',\%current_permissions,$domain,$user);
4097: return;
4098: }
4099:
4100: # ------------------------------------------------------------Save Selected Files
4101:
4102: sub save_selected_files {
4103: my ($user, $path, @files) = @_;
4104: my $filename = $user."savedfiles";
4105: my @other_files = &files_not_in_path($user, $path);
4106: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4107: foreach my $file (@files) {
4108: print (OUT $env{'form.currentpath'}.$file."\n");
4109: }
4110: foreach my $file (@other_files) {
4111: print (OUT $file."\n");
4112: }
4113: close (OUT);
4114: return 'ok';
4115: }
4116:
4117: sub clear_selected_files {
4118: my ($user) = @_;
4119: my $filename = $user."savedfiles";
4120: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4121: print (OUT undef);
4122: close (OUT);
4123: return ("ok");
4124: }
4125:
4126: sub files_in_path {
4127: my ($user, $path) = @_;
4128: my $filename = $user."savedfiles";
4129: my %return_files;
4130: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4131: while (my $line_in = <IN>) {
4132: chomp ($line_in);
4133: my @paths_and_file = split (m!/!, $line_in);
4134: my $file_part = pop (@paths_and_file);
4135: my $path_part = join ('/', @paths_and_file);
4136: $path_part.='/';
4137: my $path_and_file = $path_part.$file_part;
4138: if ($path_part eq $path) {
4139: $return_files{$file_part}= 'selected';
4140: }
4141: }
4142: close (IN);
4143: return (\%return_files);
4144: }
4145:
4146: # called in portfolio select mode, to show files selected NOT in current directory
4147: sub files_not_in_path {
4148: my ($user, $path) = @_;
4149: my $filename = $user."savedfiles";
4150: my @return_files;
4151: my $path_part;
4152: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4153: while (<IN>) {
4154: #ok, I know it's clunky, but I want it to work
4155: my @paths_and_file = split m!/!, $_;
4156: my $file_part = pop (@paths_and_file);
4157: chomp ($file_part);
4158: my $path_part = join ('/', @paths_and_file);
4159: $path_part .= '/';
4160: my $path_and_file = $path_part.$file_part;
4161: if ($path_part ne $path) {
4162: push (@return_files, ($path_and_file));
4163: }
4164: }
4165: close (OUT);
4166: return (@return_files);
4167: }
4168:
4169: #--------------------------------------------------------------Get Marked as Read Only
4170:
4171:
4172: sub get_marked_as_readonly {
4173: my ($domain,$user,$what) = @_;
4174: my %current_permissions = &dump('file_permissions',$domain,$user);
4175: my ($tmp)=keys(%current_permissions);
4176: if ($tmp=~/^error:/) { undef(%current_permissions); }
4177: my @readonly_files;
4178: my $cmp1=$what;
4179: if (ref($what)) { $cmp1=join('',@{$what}) };
4180: while (my ($file_name,$value) = each(%current_permissions)) {
4181: if (ref($value) eq "ARRAY"){
4182: foreach my $stored_what (@{$value}) {
4183: my $cmp2=$stored_what;
4184: if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
4185: if ($cmp1 eq $cmp2) {
4186: push(@readonly_files, $file_name);
4187: } elsif (!defined($what)) {
4188: push(@readonly_files, $file_name);
4189: }
4190: }
4191: }
4192: }
4193: return @readonly_files;
4194: }
4195: #-----------------------------------------------------------Get Marked as Read Only Hash
4196:
4197: sub get_marked_as_readonly_hash {
4198: my ($domain,$user,$what) = @_;
4199: my %current_permissions = &dump('file_permissions',$domain,$user);
4200: my ($tmp)=keys(%current_permissions);
4201: if ($tmp=~/^error:/) { undef(%current_permissions); }
4202:
4203: my %readonly_files;
4204: while (my ($file_name,$value) = each(%current_permissions)) {
4205: if (ref($value) eq "ARRAY"){
4206: foreach my $stored_what (@{$value}) {
4207: if ($stored_what eq $what) {
4208: $readonly_files{$file_name} = 'locked';
4209: } elsif (!defined($what)) {
4210: $readonly_files{$file_name} = 'locked';
4211: }
4212: }
4213: }
4214: }
4215: return %readonly_files;
4216: }
4217: # ------------------------------------------------------------ Unmark as Read Only
4218:
4219: sub unmark_as_readonly {
4220: # unmarks $file_name (if $file_name is defined), or all files locked by $what
4221: # for portfolio submissions, $what contains [$symb,$crsid]
4222: my ($domain,$user,$what,$file_name) = @_;
4223: my $symb_crs = $what;
4224: if (ref($what)) { $symb_crs=join('',@$what); }
4225: my %current_permissions = &dump('file_permissions',$domain,$user);
4226: my ($tmp)=keys(%current_permissions);
4227: if ($tmp=~/^error:/) { undef(%current_permissions); }
4228: my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
4229: foreach my $file (@readonly_files) {
4230: if (defined($file_name) && ($file_name ne $file)) { next; }
4231: my $current_locks = $current_permissions{$file};
4232: my @new_locks;
4233: my @del_keys;
4234: if (ref($current_locks) eq "ARRAY"){
4235: foreach my $locker (@{$current_locks}) {
4236: my $compare=$locker;
4237: if (ref($locker)) { $compare=join('',@{$locker}) };
4238: if ($compare ne $symb_crs) {
4239: push(@new_locks, $locker);
4240: }
4241: }
4242: if (scalar(@new_locks) > 0) {
4243: $current_permissions{$file} = \@new_locks;
4244: } else {
4245: push(@del_keys, $file);
4246: &del('file_permissions',\@del_keys, $domain, $user);
4247: delete($current_permissions{$file});
4248: }
4249: }
4250: }
4251: &put('file_permissions',\%current_permissions,$domain,$user);
4252: return;
4253: }
4254:
4255: # ------------------------------------------------------------ Directory lister
4256:
4257: sub dirlist {
4258: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
4259:
4260: $uri=~s/^\///;
4261: $uri=~s/\/$//;
4262: my ($udom, $uname);
4263: (undef,$udom,$uname)=split(/\//,$uri);
4264: if(defined($userdomain)) {
4265: $udom = $userdomain;
4266: }
4267: if(defined($username)) {
4268: $uname = $username;
4269: }
4270:
4271: my $dirRoot = $perlvar{'lonDocRoot'};
4272: if(defined($alternateDirectoryRoot)) {
4273: $dirRoot = $alternateDirectoryRoot;
4274: $dirRoot =~ s/\/$//;
4275: }
4276:
4277: if($udom) {
4278: if($uname) {
4279: my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
4280: homeserver($uname,$udom));
4281: my @listing_results;
4282: if ($listing eq 'unknown_cmd') {
4283: $listing=reply('ls:'.$dirRoot.'/'.$uri,
4284: homeserver($uname,$udom));
4285: @listing_results = split(/:/,$listing);
4286: } else {
4287: @listing_results = map { &unescape($_); } split(/:/,$listing);
4288: }
4289: return @listing_results;
4290: } elsif(!defined($alternateDirectoryRoot)) {
4291: my $tryserver;
4292: my %allusers=();
4293: foreach $tryserver (keys %libserv) {
4294: if($hostdom{$tryserver} eq $udom) {
4295: my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
4296: $udom, $tryserver);
4297: my @listing_results;
4298: if ($listing eq 'unknown_cmd') {
4299: $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
4300: $udom, $tryserver);
4301: @listing_results = split(/:/,$listing);
4302: } else {
4303: @listing_results =
4304: map { &unescape($_); } split(/:/,$listing);
4305: }
4306: if ($listing_results[0] ne 'no_such_dir' &&
4307: $listing_results[0] ne 'empty' &&
4308: $listing_results[0] ne 'con_lost') {
4309: foreach (@listing_results) {
4310: my ($entry,@stat)=split(/&/,$_);
4311: $allusers{$entry}=1;
4312: }
4313: }
4314: }
4315: }
4316: my $alluserstr='';
4317: foreach (sort keys %allusers) {
4318: $alluserstr.=$_.'&user:';
4319: }
4320: $alluserstr=~s/:$//;
4321: return split(/:/,$alluserstr);
4322: } else {
4323: my @emptyResults = ();
4324: push(@emptyResults, 'missing user name');
4325: return split(':',@emptyResults);
4326: }
4327: } elsif(!defined($alternateDirectoryRoot)) {
4328: my $tryserver;
4329: my %alldom=();
4330: foreach $tryserver (keys %libserv) {
4331: $alldom{$hostdom{$tryserver}}=1;
4332: }
4333: my $alldomstr='';
4334: foreach (sort keys %alldom) {
4335: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
4336: }
4337: $alldomstr=~s/:$//;
4338: return split(/:/,$alldomstr);
4339: } else {
4340: my @emptyResults = ();
4341: push(@emptyResults, 'missing domain');
4342: return split(':',@emptyResults);
4343: }
4344: }
4345:
4346: # --------------------------------------------- GetFileTimestamp
4347: # This function utilizes dirlist and returns the date stamp for
4348: # when it was last modified. It will also return an error of -1
4349: # if an error occurs
4350:
4351: ##
4352: ## FIXME: This subroutine assumes its caller knows something about the
4353: ## directory structure of the home server for the student ($root).
4354: ## Not a good assumption to make. Since this is for looking up files
4355: ## in user directories, the full path should be constructed by lond, not
4356: ## whatever machine we request data from.
4357: ##
4358: sub GetFileTimestamp {
4359: my ($studentDomain,$studentName,$filename,$root)=@_;
4360: $studentDomain=~s/\W//g;
4361: $studentName=~s/\W//g;
4362: my $subdir=$studentName.'__';
4363: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
4364: my $proname="$studentDomain/$subdir/$studentName";
4365: $proname .= '/'.$filename;
4366: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
4367: $studentName, $root);
4368: my @stats = split('&', $fileStat);
4369: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
4370: # @stats contains first the filename, then the stat output
4371: return $stats[10]; # so this is 10 instead of 9.
4372: } else {
4373: return -1;
4374: }
4375: }
4376:
4377: # -------------------------------------------------------- Value of a Condition
4378:
4379: sub directcondval {
4380: my $number=shift;
4381: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
4382: &Apache::lonuserstate::evalstate();
4383: }
4384: if ($env{'user.state.'.$env{'request.course.id'}}) {
4385: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
4386: } else {
4387: return 2;
4388: }
4389: }
4390:
4391: sub condval {
4392: my $condidx=shift;
4393: my $result=0;
4394: my $allpathcond='';
4395: foreach (split(/\|/,$condidx)) {
4396: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
4397: $allpathcond.=
4398: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
4399: }
4400: }
4401: $allpathcond=~s/\|$//;
4402: if ($env{'request.course.id'}) {
4403: if ($allpathcond) {
4404: my $operand='|';
4405: my @stack;
4406: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
4407: if ($_ eq '(') {
4408: push @stack,($operand,$result)
4409: } elsif ($_ eq ')') {
4410: my $before=pop @stack;
4411: if (pop @stack eq '&') {
4412: $result=$result>$before?$before:$result;
4413: } else {
4414: $result=$result>$before?$result:$before;
4415: }
4416: } elsif (($_ eq '&') || ($_ eq '|')) {
4417: $operand=$_;
4418: } else {
4419: my $new=directcondval($_);
4420: if ($operand eq '&') {
4421: $result=$result>$new?$new:$result;
4422: } else {
4423: $result=$result>$new?$result:$new;
4424: }
4425: }
4426: }
4427: }
4428: }
4429: return $result;
4430: }
4431:
4432: # ---------------------------------------------------- Devalidate courseresdata
4433:
4434: sub devalidatecourseresdata {
4435: my ($coursenum,$coursedomain)=@_;
4436: my $hashid=$coursenum.':'.$coursedomain;
4437: &devalidate_cache_new('courseres',$hashid);
4438: }
4439:
4440: # --------------------------------------------------- Course Resourcedata Query
4441:
4442: sub get_courseresdata {
4443: my ($coursenum,$coursedomain)=@_;
4444: my $coursehom=&homeserver($coursenum,$coursedomain);
4445: my $hashid=$coursenum.':'.$coursedomain;
4446: my ($result,$cached)=&is_cached_new('courseres',$hashid);
4447: my %dumpreply;
4448: unless (defined($cached)) {
4449: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
4450: $result=\%dumpreply;
4451: my ($tmp) = keys(%dumpreply);
4452: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
4453: &do_cache_new('courseres',$hashid,$result,600);
4454: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
4455: return $tmp;
4456: } elsif ($tmp =~ /^(error)/) {
4457: $result=undef;
4458: &do_cache_new('courseres',$hashid,$result,600);
4459: }
4460: }
4461: return $result;
4462: }
4463:
4464: sub devalidateuserresdata {
4465: my ($uname,$udom)=@_;
4466: my $hashid="$udom:$uname";
4467: &devalidate_cache_new('userres',$hashid);
4468: }
4469:
4470: sub get_userresdata {
4471: my ($uname,$udom)=@_;
4472: #most student don\'t have any data set, check if there is some data
4473: if (&EXT_cache_status($udom,$uname)) { return undef; }
4474:
4475: my $hashid="$udom:$uname";
4476: my ($result,$cached)=&is_cached_new('userres',$hashid);
4477: if (!defined($cached)) {
4478: my %resourcedata=&dump('resourcedata',$udom,$uname);
4479: $result=\%resourcedata;
4480: &do_cache_new('userres',$hashid,$result,600);
4481: }
4482: my ($tmp)=keys(%$result);
4483: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
4484: return $result;
4485: }
4486: #error 2 occurs when the .db doesn't exist
4487: if ($tmp!~/error: 2 /) {
4488: &logthis("<font color=\"blue\">WARNING:".
4489: " Trying to get resource data for ".
4490: $uname." at ".$udom.": ".
4491: $tmp."</font>");
4492: } elsif ($tmp=~/error: 2 /) {
4493: #&EXT_cache_set($udom,$uname);
4494: &do_cache_new('userres',$hashid,undef,600);
4495: undef($tmp); # not really an error so don't send it back
4496: }
4497: return $tmp;
4498: }
4499:
4500: sub resdata {
4501: my ($name,$domain,$type,@which)=@_;
4502: my $result;
4503: if ($type eq 'course') {
4504: $result=&get_courseresdata($name,$domain);
4505: } elsif ($type eq 'user') {
4506: $result=&get_userresdata($name,$domain);
4507: }
4508: if (!ref($result)) { return $result; }
4509: foreach my $item (@which) {
4510: if (defined($result->{$item})) {
4511: return $result->{$item};
4512: }
4513: }
4514: return undef;
4515: }
4516:
4517: #
4518: # EXT resource caching routines
4519: #
4520:
4521: sub clear_EXT_cache_status {
4522: &delenv('cache.EXT.');
4523: }
4524:
4525: sub EXT_cache_status {
4526: my ($target_domain,$target_user) = @_;
4527: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
4528: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
4529: # We know already the user has no data
4530: return 1;
4531: } else {
4532: return 0;
4533: }
4534: }
4535:
4536: sub EXT_cache_set {
4537: my ($target_domain,$target_user) = @_;
4538: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
4539: #&appenv($cachename => time);
4540: }
4541:
4542: # --------------------------------------------------------- Value of a Variable
4543: sub EXT {
4544: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
4545:
4546: unless ($varname) { return ''; }
4547: #get real user name/domain, courseid and symb
4548: my $courseid;
4549: my $publicuser;
4550: if ($symbparm) {
4551: $symbparm=&get_symb_from_alias($symbparm);
4552: }
4553: if (!($uname && $udom)) {
4554: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
4555: &Apache::lonxml::whichuser($symbparm);
4556: if (!$symbparm) { $symbparm=$cursymb; }
4557: } else {
4558: $courseid=$env{'request.course.id'};
4559: }
4560: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
4561: my $rest;
4562: if (defined($therest[0])) {
4563: $rest=join('.',@therest);
4564: } else {
4565: $rest='';
4566: }
4567:
4568: my $qualifierrest=$qualifier;
4569: if ($rest) { $qualifierrest.='.'.$rest; }
4570: my $spacequalifierrest=$space;
4571: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
4572: if ($realm eq 'user') {
4573: # --------------------------------------------------------------- user.resource
4574: if ($space eq 'resource') {
4575: if ( (defined($Apache::lonhomework::parsing_a_problem)
4576: || defined($Apache::lonhomework::parsing_a_task))
4577: &&
4578: ($symbparm eq &symbread()) ) {
4579: return $Apache::lonhomework::history{$qualifierrest};
4580: } else {
4581: my %restored;
4582: if ($publicuser || $env{'request.state'} eq 'construct') {
4583: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
4584: } else {
4585: %restored=&restore($symbparm,$courseid,$udom,$uname);
4586: }
4587: return $restored{$qualifierrest};
4588: }
4589: # ----------------------------------------------------------------- user.access
4590: } elsif ($space eq 'access') {
4591: # FIXME - not supporting calls for a specific user
4592: return &allowed($qualifier,$rest);
4593: # ------------------------------------------ user.preferences, user.environment
4594: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
4595: if (($uname eq $env{'user.name'}) &&
4596: ($udom eq $env{'user.domain'})) {
4597: return $env{join('.',('environment',$qualifierrest))};
4598: } else {
4599: my %returnhash;
4600: if (!$publicuser) {
4601: %returnhash=&userenvironment($udom,$uname,
4602: $qualifierrest);
4603: }
4604: return $returnhash{$qualifierrest};
4605: }
4606: # ----------------------------------------------------------------- user.course
4607: } elsif ($space eq 'course') {
4608: # FIXME - not supporting calls for a specific user
4609: return $env{join('.',('request.course',$qualifier))};
4610: # ------------------------------------------------------------------- user.role
4611: } elsif ($space eq 'role') {
4612: # FIXME - not supporting calls for a specific user
4613: my ($role,$where)=split(/\./,$env{'request.role'});
4614: if ($qualifier eq 'value') {
4615: return $role;
4616: } elsif ($qualifier eq 'extent') {
4617: return $where;
4618: }
4619: # ----------------------------------------------------------------- user.domain
4620: } elsif ($space eq 'domain') {
4621: return $udom;
4622: # ------------------------------------------------------------------- user.name
4623: } elsif ($space eq 'name') {
4624: return $uname;
4625: # ---------------------------------------------------- Any other user namespace
4626: } else {
4627: my %reply;
4628: if (!$publicuser) {
4629: %reply=&get($space,[$qualifierrest],$udom,$uname);
4630: }
4631: return $reply{$qualifierrest};
4632: }
4633: } elsif ($realm eq 'query') {
4634: # ---------------------------------------------- pull stuff out of query string
4635: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
4636: [$spacequalifierrest]);
4637: return $env{'form.'.$spacequalifierrest};
4638: } elsif ($realm eq 'request') {
4639: # ------------------------------------------------------------- request.browser
4640: if ($space eq 'browser') {
4641: if ($qualifier eq 'textremote') {
4642: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
4643: return 1;
4644: } else {
4645: return 0;
4646: }
4647: } else {
4648: return $env{'browser.'.$qualifier};
4649: }
4650: # ------------------------------------------------------------ request.filename
4651: } else {
4652: return $env{'request.'.$spacequalifierrest};
4653: }
4654: } elsif ($realm eq 'course') {
4655: # ---------------------------------------------------------- course.description
4656: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
4657: } elsif ($realm eq 'resource') {
4658:
4659: my $section;
4660: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
4661: if (!$symbparm) { $symbparm=&symbread(); }
4662: }
4663: my ($courselevelm,$courselevel);
4664: if ($symbparm && defined($courseid) &&
4665: $courseid eq $env{'request.course.id'}) {
4666:
4667: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
4668:
4669: # ----------------------------------------------------- Cascading lookup scheme
4670: my $symbp=$symbparm;
4671: my $mapp=(&decode_symb($symbp))[0];
4672:
4673: my $symbparm=$symbp.'.'.$spacequalifierrest;
4674: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
4675:
4676: if (($env{'user.name'} eq $uname) &&
4677: ($env{'user.domain'} eq $udom)) {
4678: $section=$env{'request.course.sec'};
4679: } else {
4680: if (! defined($usection)) {
4681: $section=&getsection($udom,$uname,$courseid);
4682: } else {
4683: $section = $usection;
4684: }
4685: }
4686:
4687: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
4688: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
4689: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
4690:
4691: $courselevel=$courseid.'.'.$spacequalifierrest;
4692: my $courselevelr=$courseid.'.'.$symbparm;
4693: $courselevelm=$courseid.'.'.$mapparm;
4694:
4695: # ----------------------------------------------------------- first, check user
4696:
4697: my $userreply=&resdata($uname,$udom,'user',
4698: ($courselevelr,$courselevelm,
4699: $courselevel));
4700:
4701: if (defined($userreply)) { return $userreply; }
4702:
4703: # ------------------------------------------------ second, check some of course
4704:
4705: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
4706: $env{'course.'.$courseid.'.domain'},
4707: 'course',
4708: ($seclevelr,$seclevelm,$seclevel,
4709: $courselevelr));
4710: if (defined($coursereply)) { return $coursereply; }
4711:
4712: # ------------------------------------------------------ third, check map parms
4713: my %parmhash=();
4714: my $thisparm='';
4715: if (tie(%parmhash,'GDBM_File',
4716: $env{'request.course.fn'}.'_parms.db',
4717: &GDBM_READER(),0640)) {
4718: $thisparm=$parmhash{$symbparm};
4719: untie(%parmhash);
4720: }
4721: if ($thisparm) { return $thisparm; }
4722: }
4723: # ------------------------------------------ fourth, look in resource metadata
4724:
4725: $spacequalifierrest=~s/\./\_/;
4726: my $filename;
4727: if (!$symbparm) { $symbparm=&symbread(); }
4728: if ($symbparm) {
4729: $filename=(&decode_symb($symbparm))[2];
4730: } else {
4731: $filename=$env{'request.filename'};
4732: }
4733: my $metadata=&metadata($filename,$spacequalifierrest);
4734: if (defined($metadata)) { return $metadata; }
4735: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
4736: if (defined($metadata)) { return $metadata; }
4737:
4738: # ---------------------------------------------- fourth, look in rest pf course
4739: if ($symbparm && defined($courseid) &&
4740: $courseid eq $env{'request.course.id'}) {
4741: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
4742: $env{'course.'.$courseid.'.domain'},
4743: 'course',
4744: ($courselevelm,$courselevel));
4745: if (defined($coursereply)) { return $coursereply; }
4746: }
4747: # ------------------------------------------------------------------ Cascade up
4748: unless ($space eq '0') {
4749: my @parts=split(/_/,$space);
4750: my $id=pop(@parts);
4751: my $part=join('_',@parts);
4752: if ($part eq '') { $part='0'; }
4753: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
4754: $symbparm,$udom,$uname,$section,1);
4755: if (defined($partgeneral)) { return $partgeneral; }
4756: }
4757: if ($recurse) { return undef; }
4758: my $pack_def=&packages_tab_default($filename,$varname);
4759: if (defined($pack_def)) { return $pack_def; }
4760:
4761: # ---------------------------------------------------- Any other user namespace
4762: } elsif ($realm eq 'environment') {
4763: # ----------------------------------------------------------------- environment
4764: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
4765: return $env{'environment.'.$spacequalifierrest};
4766: } else {
4767: my %returnhash=&userenvironment($udom,$uname,
4768: $spacequalifierrest);
4769: return $returnhash{$spacequalifierrest};
4770: }
4771: } elsif ($realm eq 'system') {
4772: # ----------------------------------------------------------------- system.time
4773: if ($space eq 'time') {
4774: return time;
4775: }
4776: }
4777: return '';
4778: }
4779:
4780: sub packages_tab_default {
4781: my ($uri,$varname)=@_;
4782: my (undef,$part,$name)=split(/\./,$varname);
4783: my $packages=&metadata($uri,'packages');
4784: foreach my $package (split(/,/,$packages)) {
4785: my ($pack_type,$pack_part)=split(/_/,$package,2);
4786: if (defined($packagetab{"$pack_type&$name&default"})) {
4787: return $packagetab{"$pack_type&$name&default"};
4788: }
4789: if ($pack_type eq 'part') { $pack_part='0'; }
4790: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
4791: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
4792: }
4793: }
4794: return undef;
4795: }
4796:
4797: sub add_prefix_and_part {
4798: my ($prefix,$part)=@_;
4799: my $keyroot;
4800: if (defined($prefix) && $prefix !~ /^__/) {
4801: # prefix that has a part already
4802: $keyroot=$prefix;
4803: } elsif (defined($prefix)) {
4804: # prefix that is missing a part
4805: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
4806: } else {
4807: # no prefix at all
4808: if (defined($part)) { $keyroot='_'.$part; }
4809: }
4810: return $keyroot;
4811: }
4812:
4813: # ---------------------------------------------------------------- Get metadata
4814:
4815: my %metaentry;
4816: sub metadata {
4817: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
4818: $uri=&declutter($uri);
4819: # if it is a non metadata possible uri return quickly
4820: if (($uri eq '') ||
4821: (($uri =~ m|^/*adm/|) &&
4822: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
4823: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
4824: ($uri =~ m|home/[^/]+/public_html/|)) {
4825: return undef;
4826: }
4827: my $filename=$uri;
4828: $uri=~s/\.meta$//;
4829: #
4830: # Is the metadata already cached?
4831: # Look at timestamp of caching
4832: # Everything is cached by the main uri, libraries are never directly cached
4833: #
4834: if (!defined($liburi)) {
4835: my ($result,$cached)=&is_cached_new('meta',$uri);
4836: if (defined($cached)) { return $result->{':'.$what}; }
4837: }
4838: {
4839: #
4840: # Is this a recursive call for a library?
4841: #
4842: # if (! exists($metacache{$uri})) {
4843: # $metacache{$uri}={};
4844: # }
4845: if ($liburi) {
4846: $liburi=&declutter($liburi);
4847: $filename=$liburi;
4848: } else {
4849: &devalidate_cache_new('meta',$uri);
4850: undef(%metaentry);
4851: }
4852: my %metathesekeys=();
4853: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
4854: my $metastring;
4855: if ($uri !~ m -^(uploaded|editupload)/-) {
4856: my $file=&filelocation('',&clutter($filename));
4857: #push(@{$metaentry{$uri.'.file'}},$file);
4858: $metastring=&getfile($file);
4859: }
4860: my $parser=HTML::LCParser->new(\$metastring);
4861: my $token;
4862: undef %metathesekeys;
4863: while ($token=$parser->get_token) {
4864: if ($token->[0] eq 'S') {
4865: if (defined($token->[2]->{'package'})) {
4866: #
4867: # This is a package - get package info
4868: #
4869: my $package=$token->[2]->{'package'};
4870: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4871: if (defined($token->[2]->{'id'})) {
4872: $keyroot.='_'.$token->[2]->{'id'};
4873: }
4874: if ($metaentry{':packages'}) {
4875: $metaentry{':packages'}.=','.$package.$keyroot;
4876: } else {
4877: $metaentry{':packages'}=$package.$keyroot;
4878: }
4879: foreach (sort keys %packagetab) {
4880: my $part=$keyroot;
4881: $part=~s/^\_//;
4882: if ($_=~/^\Q$package\E\&/ ||
4883: $_=~/^\Q$package\E_0\&/) {
4884: my ($pack,$name,$subp)=split(/\&/,$_);
4885: # ignore package.tab specified default values
4886: # here &package_tab_default() will fetch those
4887: if ($subp eq 'default') { next; }
4888: my $value=$packagetab{$_};
4889: my $unikey;
4890: if ($pack =~ /_0$/) {
4891: $unikey='parameter_0_'.$name;
4892: $part=0;
4893: } else {
4894: $unikey='parameter'.$keyroot.'_'.$name;
4895: }
4896: if ($subp eq 'display') {
4897: $value.=' [Part: '.$part.']';
4898: }
4899: $metaentry{':'.$unikey.'.part'}=$part;
4900: $metathesekeys{$unikey}=1;
4901: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
4902: $metaentry{':'.$unikey.'.'.$subp}=$value;
4903: }
4904: if (defined($metaentry{':'.$unikey.'.default'})) {
4905: $metaentry{':'.$unikey}=
4906: $metaentry{':'.$unikey.'.default'};
4907: }
4908: }
4909: }
4910: } else {
4911: #
4912: # This is not a package - some other kind of start tag
4913: #
4914: my $entry=$token->[1];
4915: my $unikey;
4916: if ($entry eq 'import') {
4917: $unikey='';
4918: } else {
4919: $unikey=$entry;
4920: }
4921: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4922:
4923: if (defined($token->[2]->{'id'})) {
4924: $unikey.='_'.$token->[2]->{'id'};
4925: }
4926:
4927: if ($entry eq 'import') {
4928: #
4929: # Importing a library here
4930: #
4931: if ($depthcount<20) {
4932: my $location=$parser->get_text('/import');
4933: my $dir=$filename;
4934: $dir=~s|[^/]*$||;
4935: $location=&filelocation($dir,$location);
4936: foreach (sort(split(/\,/,&metadata($uri,'keys',
4937: $location,$unikey,
4938: $depthcount+1)))) {
4939: $metaentry{':'.$_}=$metaentry{':'.$_};
4940: $metathesekeys{$_}=1;
4941: }
4942: }
4943: } else {
4944:
4945: if (defined($token->[2]->{'name'})) {
4946: $unikey.='_'.$token->[2]->{'name'};
4947: }
4948: $metathesekeys{$unikey}=1;
4949: foreach (@{$token->[3]}) {
4950: $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
4951: }
4952: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
4953: my $default=$metaentry{':'.$unikey.'.default'};
4954: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
4955: # only ws inside the tag, and not in default, so use default
4956: # as value
4957: $metaentry{':'.$unikey}=$default;
4958: } else {
4959: # either something interesting inside the tag or default
4960: # uninteresting
4961: $metaentry{':'.$unikey}=$internaltext;
4962: }
4963: # end of not-a-package not-a-library import
4964: }
4965: # end of not-a-package start tag
4966: }
4967: # the next is the end of "start tag"
4968: }
4969: }
4970: my ($extension) = ($uri =~ /\.(\w+)$/);
4971: foreach my $key (sort(keys(%packagetab))) {
4972: #no specific packages #how's our extension
4973: if ($key!~/^extension_\Q$extension\E&/) { next; }
4974: &metadata_create_package_def($uri,$key,'extension_'.$extension,
4975: \%metathesekeys);
4976: }
4977: if (!exists($metaentry{':packages'})) {
4978: foreach my $key (sort(keys(%packagetab))) {
4979: #no specific packages well let's get default then
4980: if ($key!~/^default&/) { next; }
4981: &metadata_create_package_def($uri,$key,'default',
4982: \%metathesekeys);
4983: }
4984: }
4985: # are there custom rights to evaluate
4986: if ($metaentry{':copyright'} eq 'custom') {
4987:
4988: #
4989: # Importing a rights file here
4990: #
4991: unless ($depthcount) {
4992: my $location=$metaentry{':customdistributionfile'};
4993: my $dir=$filename;
4994: $dir=~s|[^/]*$||;
4995: $location=&filelocation($dir,$location);
4996: foreach (sort(split(/\,/,&metadata($uri,'keys',
4997: $location,'_rights',
4998: $depthcount+1)))) {
4999: #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
5000: $metathesekeys{$_}=1;
5001: }
5002: }
5003: }
5004: $metaentry{':keys'}=join(',',keys %metathesekeys);
5005: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
5006: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
5007: &do_cache_new('meta',$uri,\%metaentry,60*60*24);
5008: # this is the end of "was not already recently cached
5009: }
5010: return $metaentry{':'.$what};
5011: }
5012:
5013: sub metadata_create_package_def {
5014: my ($uri,$key,$package,$metathesekeys)=@_;
5015: my ($pack,$name,$subp)=split(/\&/,$key);
5016: if ($subp eq 'default') { next; }
5017:
5018: if (defined($metaentry{':packages'})) {
5019: $metaentry{':packages'}.=','.$package;
5020: } else {
5021: $metaentry{':packages'}=$package;
5022: }
5023: my $value=$packagetab{$key};
5024: my $unikey;
5025: $unikey='parameter_0_'.$name;
5026: $metaentry{':'.$unikey.'.part'}=0;
5027: $$metathesekeys{$unikey}=1;
5028: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
5029: $metaentry{':'.$unikey.'.'.$subp}=$value;
5030: }
5031: if (defined($metaentry{':'.$unikey.'.default'})) {
5032: $metaentry{':'.$unikey}=
5033: $metaentry{':'.$unikey.'.default'};
5034: }
5035: }
5036:
5037: sub metadata_generate_part0 {
5038: my ($metadata,$metacache,$uri) = @_;
5039: my %allnames;
5040: foreach my $metakey (sort keys %$metadata) {
5041: if ($metakey=~/^parameter\_(.*)/) {
5042: my $part=$$metacache{':'.$metakey.'.part'};
5043: my $name=$$metacache{':'.$metakey.'.name'};
5044: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
5045: $allnames{$name}=$part;
5046: }
5047: }
5048: }
5049: foreach my $name (keys(%allnames)) {
5050: $$metadata{"parameter_0_$name"}=1;
5051: my $key=":parameter_0_$name";
5052: $$metacache{"$key.part"}='0';
5053: $$metacache{"$key.name"}=$name;
5054: $$metacache{"$key.type"}=$$metacache{':parameter_'.
5055: $allnames{$name}.'_'.$name.
5056: '.type'};
5057: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
5058: '.display'};
5059: my $expr='[Part: '.$allnames{$name}.']';
5060: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
5061: $$metacache{"$key.display"}=$olddis;
5062: }
5063: }
5064:
5065: # ------------------------------------------------- Get the title of a resource
5066:
5067: sub gettitle {
5068: my $urlsymb=shift;
5069: my $symb=&symbread($urlsymb);
5070: if ($symb) {
5071: my $key=$env{'request.course.id'}."\0".$symb;
5072: my ($result,$cached)=&is_cached_new('title',$key);
5073: if (defined($cached)) {
5074: return $result;
5075: }
5076: my ($map,$resid,$url)=&decode_symb($symb);
5077: my $title='';
5078: my %bighash;
5079: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5080: &GDBM_READER(),0640)) {
5081: my $mapid=$bighash{'map_pc_'.&clutter($map)};
5082: $title=$bighash{'title_'.$mapid.'.'.$resid};
5083: untie %bighash;
5084: }
5085: $title=~s/\&colon\;/\:/gs;
5086: if ($title) {
5087: return &do_cache_new('title',$key,$title,600);
5088: }
5089: $urlsymb=$url;
5090: }
5091: my $title=&metadata($urlsymb,'title');
5092: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
5093: return $title;
5094: }
5095:
5096: sub get_slot {
5097: my ($which,$cnum,$cdom)=@_;
5098: if (!$cnum || !$cdom) {
5099: (undef,my $courseid)=&Apache::lonxml::whichuser();
5100: $cdom=$env{'course.'.$courseid.'.domain'};
5101: $cnum=$env{'course.'.$courseid.'.num'};
5102: }
5103: my %slotinfo=&get('slots',[$which],$cdom,$cnum);
5104: &Apache::lonhomework::showhash(%slotinfo);
5105: my ($tmp)=keys(%slotinfo);
5106: if ($tmp=~/^error:/) { return (); }
5107: if (ref($slotinfo{$which}) eq 'HASH') {
5108: return %{$slotinfo{$which}};
5109: }
5110: return $slotinfo{$which};
5111: }
5112: # ------------------------------------------------- Update symbolic store links
5113:
5114: sub symblist {
5115: my ($mapname,%newhash)=@_;
5116: $mapname=&deversion(&declutter($mapname));
5117: my %hash;
5118: if (($env{'request.course.fn'}) && (%newhash)) {
5119: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
5120: &GDBM_WRCREAT(),0640)) {
5121: foreach (keys %newhash) {
5122: $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
5123: $newhash{$_}->[0]);
5124: }
5125: if (untie(%hash)) {
5126: return 'ok';
5127: }
5128: }
5129: }
5130: return 'error';
5131: }
5132:
5133: # --------------------------------------------------------------- Verify a symb
5134:
5135: sub symbverify {
5136: my ($symb,$thisurl)=@_;
5137: my $thisfn=$thisurl;
5138: # wrapper not part of symbs
5139: $thisfn=~s/^\/adm\/wrapper//;
5140: $thisfn=&declutter($thisfn);
5141: # direct jump to resource in page or to a sequence - will construct own symbs
5142: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
5143: # check URL part
5144: my ($map,$resid,$url)=&decode_symb($symb);
5145:
5146: unless ($url eq $thisfn) { return 0; }
5147:
5148: $symb=&symbclean($symb);
5149: $thisurl=&deversion($thisurl);
5150: $thisfn=&deversion($thisfn);
5151:
5152: my %bighash;
5153: my $okay=0;
5154:
5155: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5156: &GDBM_READER(),0640)) {
5157: my $ids=$bighash{'ids_'.&clutter($thisurl)};
5158: unless ($ids) {
5159: $ids=$bighash{'ids_/'.$thisurl};
5160: }
5161: if ($ids) {
5162: # ------------------------------------------------------------------- Has ID(s)
5163: foreach (split(/\,/,$ids)) {
5164: my ($mapid,$resid)=split(/\./,$_);
5165: if (
5166: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
5167: eq $symb) {
5168: if (($env{'request.role.adv'}) ||
5169: $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
5170: $okay=1;
5171: }
5172: }
5173: }
5174: }
5175: untie(%bighash);
5176: }
5177: return $okay;
5178: }
5179:
5180: # --------------------------------------------------------------- Clean-up symb
5181:
5182: sub symbclean {
5183: my $symb=shift;
5184: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
5185: # remove version from map
5186: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
5187:
5188: # remove version from URL
5189: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
5190:
5191: # remove wrapper
5192:
5193: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
5194: return $symb;
5195: }
5196:
5197: # ---------------------------------------------- Split symb to find map and url
5198:
5199: sub encode_symb {
5200: my ($map,$resid,$url)=@_;
5201: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
5202: }
5203:
5204: sub decode_symb {
5205: my $symb=shift;
5206: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
5207: my ($map,$resid,$url)=split(/___/,$symb);
5208: return (&fixversion($map),$resid,&fixversion($url));
5209: }
5210:
5211: sub fixversion {
5212: my $fn=shift;
5213: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
5214: my %bighash;
5215: my $uri=&clutter($fn);
5216: my $key=$env{'request.course.id'}.'_'.$uri;
5217: # is this cached?
5218: my ($result,$cached)=&is_cached_new('courseresversion',$key);
5219: if (defined($cached)) { return $result; }
5220: # unfortunately not cached, or expired
5221: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5222: &GDBM_READER(),0640)) {
5223: if ($bighash{'version_'.$uri}) {
5224: my $version=$bighash{'version_'.$uri};
5225: unless (($version eq 'mostrecent') ||
5226: ($version==&getversion($uri))) {
5227: $uri=~s/\.(\w+)$/\.$version\.$1/;
5228: }
5229: }
5230: untie %bighash;
5231: }
5232: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
5233: }
5234:
5235: sub deversion {
5236: my $url=shift;
5237: $url=~s/\.\d+\.(\w+)$/\.$1/;
5238: return $url;
5239: }
5240:
5241: # ------------------------------------------------------ Return symb list entry
5242:
5243: sub symbread {
5244: my ($thisfn,$donotrecurse)=@_;
5245: my $cache_str='request.symbread.cached.'.$thisfn;
5246: if (defined($env{$cache_str})) { return $env{$cache_str}; }
5247: # no filename provided? try from environment
5248: unless ($thisfn) {
5249: if ($env{'request.symb'}) {
5250: return $env{$cache_str}=&symbclean($env{'request.symb'});
5251: }
5252: $thisfn=$env{'request.filename'};
5253: }
5254: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
5255: # is that filename actually a symb? Verify, clean, and return
5256: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
5257: if (&symbverify($thisfn,$1)) {
5258: return $env{$cache_str}=&symbclean($thisfn);
5259: }
5260: }
5261: $thisfn=declutter($thisfn);
5262: my %hash;
5263: my %bighash;
5264: my $syval='';
5265: if (($env{'request.course.fn'}) && ($thisfn)) {
5266: my $targetfn = $thisfn;
5267: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
5268: $targetfn = 'adm/wrapper/'.$thisfn;
5269: }
5270: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
5271: &GDBM_READER(),0640)) {
5272: $syval=$hash{$targetfn};
5273: untie(%hash);
5274: }
5275: # ---------------------------------------------------------- There was an entry
5276: if ($syval) {
5277: #unless ($syval=~/\_\d+$/) {
5278: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
5279: #&appenv('request.ambiguous' => $thisfn);
5280: #return $env{$cache_str}='';
5281: #}
5282: #$syval.=$1;
5283: #}
5284: } else {
5285: # ------------------------------------------------------- Was not in symb table
5286: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5287: &GDBM_READER(),0640)) {
5288: # ---------------------------------------------- Get ID(s) for current resource
5289: my $ids=$bighash{'ids_'.&clutter($thisfn)};
5290: unless ($ids) {
5291: $ids=$bighash{'ids_/'.$thisfn};
5292: }
5293: unless ($ids) {
5294: # alias?
5295: $ids=$bighash{'mapalias_'.$thisfn};
5296: }
5297: if ($ids) {
5298: # ------------------------------------------------------------------- Has ID(s)
5299: my @possibilities=split(/\,/,$ids);
5300: if ($#possibilities==0) {
5301: # ----------------------------------------------- There is only one possibility
5302: my ($mapid,$resid)=split(/\./,$ids);
5303: $syval=&encode_symb($bighash{'map_id_'.$mapid},
5304: $resid,$thisfn);
5305: } elsif (!$donotrecurse) {
5306: # ------------------------------------------ There is more than one possibility
5307: my $realpossible=0;
5308: foreach (@possibilities) {
5309: my $file=$bighash{'src_'.$_};
5310: if (&allowed('bre',$file)) {
5311: my ($mapid,$resid)=split(/\./,$_);
5312: if ($bighash{'map_type_'.$mapid} ne 'page') {
5313: $realpossible++;
5314: $syval=&encode_symb($bighash{'map_id_'.$mapid},
5315: $resid,$thisfn);
5316: }
5317: }
5318: }
5319: if ($realpossible!=1) { $syval=''; }
5320: } else {
5321: $syval='';
5322: }
5323: }
5324: untie(%bighash)
5325: }
5326: }
5327: if ($syval) {
5328: return $env{$cache_str}=$syval;
5329: }
5330: }
5331: &appenv('request.ambiguous' => $thisfn);
5332: return $env{$cache_str}='';
5333: }
5334:
5335: # ---------------------------------------------------------- Return random seed
5336:
5337: sub numval {
5338: my $txt=shift;
5339: $txt=~tr/A-J/0-9/;
5340: $txt=~tr/a-j/0-9/;
5341: $txt=~tr/K-T/0-9/;
5342: $txt=~tr/k-t/0-9/;
5343: $txt=~tr/U-Z/0-5/;
5344: $txt=~tr/u-z/0-5/;
5345: $txt=~s/\D//g;
5346: if ($_64bit) { if ($txt > 2**32) { return -1; } }
5347: return int($txt);
5348: }
5349:
5350: sub numval2 {
5351: my $txt=shift;
5352: $txt=~tr/A-J/0-9/;
5353: $txt=~tr/a-j/0-9/;
5354: $txt=~tr/K-T/0-9/;
5355: $txt=~tr/k-t/0-9/;
5356: $txt=~tr/U-Z/0-5/;
5357: $txt=~tr/u-z/0-5/;
5358: $txt=~s/\D//g;
5359: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
5360: my $total;
5361: foreach my $val (@txts) { $total+=$val; }
5362: if ($_64bit) { if ($total > 2**32) { return -1; } }
5363: return int($total);
5364: }
5365:
5366: sub numval3 {
5367: use integer;
5368: my $txt=shift;
5369: $txt=~tr/A-J/0-9/;
5370: $txt=~tr/a-j/0-9/;
5371: $txt=~tr/K-T/0-9/;
5372: $txt=~tr/k-t/0-9/;
5373: $txt=~tr/U-Z/0-5/;
5374: $txt=~tr/u-z/0-5/;
5375: $txt=~s/\D//g;
5376: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
5377: my $total;
5378: foreach my $val (@txts) { $total+=$val; }
5379: if ($_64bit) { $total=(($total<<32)>>32); }
5380: return $total;
5381: }
5382:
5383: sub digest {
5384: my ($data)=@_;
5385: my $digest=&Digest::MD5::md5($data);
5386: my ($a,$b,$c,$d)=unpack("iiii",$digest);
5387: my ($e,$f);
5388: {
5389: use integer;
5390: $e=($a+$b);
5391: $f=($c+$d);
5392: if ($_64bit) {
5393: $e=(($e<<32)>>32);
5394: $f=(($f<<32)>>32);
5395: }
5396: }
5397: if (wantarray) {
5398: return ($e,$f);
5399: } else {
5400: my $g;
5401: {
5402: use integer;
5403: $g=($e+$f);
5404: if ($_64bit) {
5405: $g=(($g<<32)>>32);
5406: }
5407: }
5408: return $g;
5409: }
5410: }
5411:
5412: sub latest_rnd_algorithm_id {
5413: return '64bit5';
5414: }
5415:
5416: sub get_rand_alg {
5417: my ($courseid)=@_;
5418: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
5419: if ($courseid) {
5420: return $env{"course.$courseid.rndseed"};
5421: }
5422: return &latest_rnd_algorithm_id();
5423: }
5424:
5425: sub validCODE {
5426: my ($CODE)=@_;
5427: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
5428: return 0;
5429: }
5430:
5431: sub getCODE {
5432: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
5433: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
5434: defined($Apache::lonhomework::parsing_a_task) ) &&
5435: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
5436: return $Apache::lonhomework::history{'resource.CODE'};
5437: }
5438: return undef;
5439: }
5440:
5441: sub rndseed {
5442: my ($symb,$courseid,$domain,$username)=@_;
5443:
5444: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
5445: if (!$symb) {
5446: unless ($symb=$wsymb) { return time; }
5447: }
5448: if (!$courseid) { $courseid=$wcourseid; }
5449: if (!$domain) { $domain=$wdomain; }
5450: if (!$username) { $username=$wusername }
5451: my $which=&get_rand_alg();
5452: if (defined(&getCODE())) {
5453: if ($which eq '64bit5') {
5454: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
5455: } elsif ($which eq '64bit4') {
5456: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
5457: } else {
5458: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
5459: }
5460: } elsif ($which eq '64bit5') {
5461: return &rndseed_64bit5($symb,$courseid,$domain,$username);
5462: } elsif ($which eq '64bit4') {
5463: return &rndseed_64bit4($symb,$courseid,$domain,$username);
5464: } elsif ($which eq '64bit3') {
5465: return &rndseed_64bit3($symb,$courseid,$domain,$username);
5466: } elsif ($which eq '64bit2') {
5467: return &rndseed_64bit2($symb,$courseid,$domain,$username);
5468: } elsif ($which eq '64bit') {
5469: return &rndseed_64bit($symb,$courseid,$domain,$username);
5470: }
5471: return &rndseed_32bit($symb,$courseid,$domain,$username);
5472: }
5473:
5474: sub rndseed_32bit {
5475: my ($symb,$courseid,$domain,$username)=@_;
5476: {
5477: use integer;
5478: my $symbchck=unpack("%32C*",$symb) << 27;
5479: my $symbseed=numval($symb) << 22;
5480: my $namechck=unpack("%32C*",$username) << 17;
5481: my $nameseed=numval($username) << 12;
5482: my $domainseed=unpack("%32C*",$domain) << 7;
5483: my $courseseed=unpack("%32C*",$courseid);
5484: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
5485: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5486: #&Apache::lonxml::debug("rndseed :$num:$symb");
5487: if ($_64bit) { $num=(($num<<32)>>32); }
5488: return $num;
5489: }
5490: }
5491:
5492: sub rndseed_64bit {
5493: my ($symb,$courseid,$domain,$username)=@_;
5494: {
5495: use integer;
5496: my $symbchck=unpack("%32S*",$symb) << 21;
5497: my $symbseed=numval($symb) << 10;
5498: my $namechck=unpack("%32S*",$username);
5499:
5500: my $nameseed=numval($username) << 21;
5501: my $domainseed=unpack("%32S*",$domain) << 10;
5502: my $courseseed=unpack("%32S*",$courseid);
5503:
5504: my $num1=$symbchck+$symbseed+$namechck;
5505: my $num2=$nameseed+$domainseed+$courseseed;
5506: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5507: #&Apache::lonxml::debug("rndseed :$num:$symb");
5508: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5509: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5510: return "$num1,$num2";
5511: }
5512: }
5513:
5514: sub rndseed_64bit2 {
5515: my ($symb,$courseid,$domain,$username)=@_;
5516: {
5517: use integer;
5518: # strings need to be an even # of cahracters long, it it is odd the
5519: # last characters gets thrown away
5520: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5521: my $symbseed=numval($symb) << 10;
5522: my $namechck=unpack("%32S*",$username.' ');
5523:
5524: my $nameseed=numval($username) << 21;
5525: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5526: my $courseseed=unpack("%32S*",$courseid.' ');
5527:
5528: my $num1=$symbchck+$symbseed+$namechck;
5529: my $num2=$nameseed+$domainseed+$courseseed;
5530: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5531: #&Apache::lonxml::debug("rndseed :$num:$symb");
5532: return "$num1,$num2";
5533: }
5534: }
5535:
5536: sub rndseed_64bit3 {
5537: my ($symb,$courseid,$domain,$username)=@_;
5538: {
5539: use integer;
5540: # strings need to be an even # of cahracters long, it it is odd the
5541: # last characters gets thrown away
5542: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5543: my $symbseed=numval2($symb) << 10;
5544: my $namechck=unpack("%32S*",$username.' ');
5545:
5546: my $nameseed=numval2($username) << 21;
5547: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5548: my $courseseed=unpack("%32S*",$courseid.' ');
5549:
5550: my $num1=$symbchck+$symbseed+$namechck;
5551: my $num2=$nameseed+$domainseed+$courseseed;
5552: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5553: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
5554: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5555:
5556: return "$num1:$num2";
5557: }
5558: }
5559:
5560: sub rndseed_64bit4 {
5561: my ($symb,$courseid,$domain,$username)=@_;
5562: {
5563: use integer;
5564: # strings need to be an even # of cahracters long, it it is odd the
5565: # last characters gets thrown away
5566: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5567: my $symbseed=numval3($symb) << 10;
5568: my $namechck=unpack("%32S*",$username.' ');
5569:
5570: my $nameseed=numval3($username) << 21;
5571: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5572: my $courseseed=unpack("%32S*",$courseid.' ');
5573:
5574: my $num1=$symbchck+$symbseed+$namechck;
5575: my $num2=$nameseed+$domainseed+$courseseed;
5576: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5577: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
5578: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5579:
5580: return "$num1:$num2";
5581: }
5582: }
5583:
5584: sub rndseed_64bit5 {
5585: my ($symb,$courseid,$domain,$username)=@_;
5586: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
5587: return "$num1:$num2";
5588: }
5589:
5590: sub rndseed_CODE_64bit {
5591: my ($symb,$courseid,$domain,$username)=@_;
5592: {
5593: use integer;
5594: my $symbchck=unpack("%32S*",$symb.' ') << 16;
5595: my $symbseed=numval2($symb);
5596: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
5597: my $CODEseed=numval(&getCODE());
5598: my $courseseed=unpack("%32S*",$courseid.' ');
5599: my $num1=$symbseed+$CODEchck;
5600: my $num2=$CODEseed+$courseseed+$symbchck;
5601: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
5602: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
5603: if ($_64bit) { $num1=(($num1<<32)>>32); }
5604: if ($_64bit) { $num2=(($num2<<32)>>32); }
5605: return "$num1:$num2";
5606: }
5607: }
5608:
5609: sub rndseed_CODE_64bit4 {
5610: my ($symb,$courseid,$domain,$username)=@_;
5611: {
5612: use integer;
5613: my $symbchck=unpack("%32S*",$symb.' ') << 16;
5614: my $symbseed=numval3($symb);
5615: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
5616: my $CODEseed=numval3(&getCODE());
5617: my $courseseed=unpack("%32S*",$courseid.' ');
5618: my $num1=$symbseed+$CODEchck;
5619: my $num2=$CODEseed+$courseseed+$symbchck;
5620: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
5621: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
5622: if ($_64bit) { $num1=(($num1<<32)>>32); }
5623: if ($_64bit) { $num2=(($num2<<32)>>32); }
5624: return "$num1:$num2";
5625: }
5626: }
5627:
5628: sub rndseed_CODE_64bit5 {
5629: my ($symb,$courseid,$domain,$username)=@_;
5630: my $code = &getCODE();
5631: my ($num1,$num2)=&digest("$symb,$courseid,$code");
5632: return "$num1:$num2";
5633: }
5634:
5635: sub setup_random_from_rndseed {
5636: my ($rndseed)=@_;
5637: if ($rndseed =~/([,:])/) {
5638: my ($num1,$num2)=split(/[,:]/,$rndseed);
5639: &Math::Random::random_set_seed(abs($num1),abs($num2));
5640: } else {
5641: &Math::Random::random_set_seed_from_phrase($rndseed);
5642: }
5643: }
5644:
5645: sub latest_receipt_algorithm_id {
5646: return 'receipt2';
5647: }
5648:
5649: sub recunique {
5650: my $fucourseid=shift;
5651: my $unique;
5652: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5653: $unique=$env{"course.$fucourseid.internal.encseed"};
5654: } else {
5655: $unique=$perlvar{'lonReceipt'};
5656: }
5657: return unpack("%32C*",$unique);
5658: }
5659:
5660: sub recprefix {
5661: my $fucourseid=shift;
5662: my $prefix;
5663: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5664: $prefix=$env{"course.$fucourseid.internal.encpref"};
5665: } else {
5666: $prefix=$perlvar{'lonHostID'};
5667: }
5668: return unpack("%32C*",$prefix);
5669: }
5670:
5671: sub ireceipt {
5672: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
5673: my $cuname=unpack("%32C*",$funame);
5674: my $cudom=unpack("%32C*",$fudom);
5675: my $cucourseid=unpack("%32C*",$fucourseid);
5676: my $cusymb=unpack("%32C*",$fusymb);
5677: my $cunique=&recunique($fucourseid);
5678: my $cpart=unpack("%32S*",$part);
5679: my $return =&recprefix($fucourseid).'-';
5680: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
5681: $env{'request.state'} eq 'construct') {
5682: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
5683: " and ".($cpart%$cudom));
5684:
5685: $return.= ($cunique%$cuname+
5686: $cunique%$cudom+
5687: $cusymb%$cuname+
5688: $cusymb%$cudom+
5689: $cucourseid%$cuname+
5690: $cucourseid%$cudom+
5691: $cpart%$cuname+
5692: $cpart%$cudom);
5693: } else {
5694: $return.= ($cunique%$cuname+
5695: $cunique%$cudom+
5696: $cusymb%$cuname+
5697: $cusymb%$cudom+
5698: $cucourseid%$cuname+
5699: $cucourseid%$cudom);
5700: }
5701: return $return;
5702: }
5703:
5704: sub receipt {
5705: my ($part)=@_;
5706: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
5707: return &ireceipt($name,$domain,$courseid,$symb,$part);
5708: }
5709:
5710: # ------------------------------------------------------------ Serves up a file
5711: # returns either the contents of the file or
5712: # -1 if the file doesn't exist
5713: #
5714: # if the target is a file that was uploaded via DOCS,
5715: # a check will be made to see if a current copy exists on the local server,
5716: # if it does this will be served, otherwise a copy will be retrieved from
5717: # the home server for the course and stored in /home/httpd/html/userfiles on
5718: # the local server.
5719:
5720: sub getfile {
5721: my ($file) = @_;
5722: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
5723: &repcopy($file);
5724: return &readfile($file);
5725: }
5726:
5727: sub repcopy_userfile {
5728: my ($file)=@_;
5729: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
5730: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
5731: my ($cdom,$cnum,$filename) =
5732: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
5733: my ($info,$rtncode);
5734: my $uri="/uploaded/$cdom/$cnum/$filename";
5735: if (-e "$file") {
5736: my @fileinfo = stat($file);
5737: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
5738: if ($lwpresp ne 'ok') {
5739: if ($rtncode eq '404') {
5740: unlink($file);
5741: }
5742: #my $ua=new LWP::UserAgent;
5743: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
5744: #my $response=$ua->request($request);
5745: #if ($response->is_success()) {
5746: # return $response->content;
5747: # } else {
5748: # return -1;
5749: # }
5750: return -1;
5751: }
5752: if ($info < $fileinfo[9]) {
5753: return 'ok';
5754: }
5755: $info = '';
5756: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
5757: if ($lwpresp ne 'ok') {
5758: return -1;
5759: }
5760: } else {
5761: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
5762: if ($lwpresp ne 'ok') {
5763: my $ua=new LWP::UserAgent;
5764: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
5765: my $response=$ua->request($request);
5766: if ($response->is_success()) {
5767: $info=$response->content;
5768: } else {
5769: return -1;
5770: }
5771: }
5772: my @parts = ($cdom,$cnum);
5773: if ($filename =~ m|^(.+)/[^/]+$|) {
5774: push @parts, split(/\//,$1);
5775: }
5776: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
5777: foreach my $part (@parts) {
5778: $path .= '/'.$part;
5779: if (!-e $path) {
5780: mkdir($path,0770);
5781: }
5782: }
5783: }
5784: open(FILE,">$file");
5785: print FILE $info;
5786: close(FILE);
5787: return 'ok';
5788: }
5789:
5790: sub tokenwrapper {
5791: my $uri=shift;
5792: $uri=~s|^http\://([^/]+)||;
5793: $uri=~s|^/||;
5794: $env{'user.environment'}=~/\/([^\/]+)\.id/;
5795: my $token=$1;
5796: my (undef,$udom,$uname,$file)=split('/',$uri,4);
5797: if ($udom && $uname && $file) {
5798: $file=~s|(\?\.*)*$||;
5799: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
5800: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
5801: (($uri=~/\?/)?'&':'?').'token='.$token.
5802: '&tokenissued='.$perlvar{'lonHostID'};
5803: } else {
5804: return '/adm/notfound.html';
5805: }
5806: }
5807:
5808: sub getuploaded {
5809: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
5810: $uri=~s/^\///;
5811: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
5812: my $ua=new LWP::UserAgent;
5813: my $request=new HTTP::Request($reqtype,$uri);
5814: my $response=$ua->request($request);
5815: $$rtncode = $response->code;
5816: if (! $response->is_success()) {
5817: return 'failed';
5818: }
5819: if ($reqtype eq 'HEAD') {
5820: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
5821: } elsif ($reqtype eq 'GET') {
5822: $$info = $response->content;
5823: }
5824: return 'ok';
5825: }
5826:
5827: sub readfile {
5828: my $file = shift;
5829: if ( (! -e $file ) || ($file eq '') ) { return -1; };
5830: my $fh;
5831: open($fh,"<$file");
5832: my $a='';
5833: while (<$fh>) { $a .=$_; }
5834: return $a;
5835: }
5836:
5837: sub filelocation {
5838: my ($dir,$file) = @_;
5839: my $location;
5840: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
5841: if ($file=~m:^/~:) { # is a contruction space reference
5842: $location = $file;
5843: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
5844: } elsif ($file=~m:^/home/[^/]*/public_html/:) {
5845: # is a correct contruction space reference
5846: $location = $file;
5847: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
5848: my ($udom,$uname,$filename)=
5849: ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
5850: my $home=&homeserver($uname,$udom);
5851: my $is_me=0;
5852: my @ids=¤t_machine_ids();
5853: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
5854: if ($is_me) {
5855: $location=&Apache::loncommon::propath($udom,$uname).
5856: '/userfiles/'.$filename;
5857: } else {
5858: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
5859: $udom.'/'.$uname.'/'.$filename;
5860: }
5861: } else {
5862: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
5863: $file=~s:^/res/:/:;
5864: if ( !( $file =~ m:^/:) ) {
5865: $location = $dir. '/'.$file;
5866: } else {
5867: $location = '/home/httpd/html/res'.$file;
5868: }
5869: }
5870: $location=~s://+:/:g; # remove duplicate /
5871: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
5872: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
5873: return $location;
5874: }
5875:
5876: sub hreflocation {
5877: my ($dir,$file)=@_;
5878: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
5879: $file=filelocation($dir,$file);
5880: }
5881: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
5882: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
5883: } elsif ($file=~m-/home/(\w+)/public_html/-) {
5884: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
5885: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
5886: $file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
5887: -/uploaded/$1/$2/-x;
5888: }
5889: return $file;
5890: }
5891:
5892: sub current_machine_domains {
5893: my $hostname=$hostname{$perlvar{'lonHostID'}};
5894: my @domains;
5895: while( my($id, $name) = each(%hostname)) {
5896: # &logthis("-$id-$name-$hostname-");
5897: if ($hostname eq $name) {
5898: push(@domains,$hostdom{$id});
5899: }
5900: }
5901: return @domains;
5902: }
5903:
5904: sub current_machine_ids {
5905: my $hostname=$hostname{$perlvar{'lonHostID'}};
5906: my @ids;
5907: while( my($id, $name) = each(%hostname)) {
5908: # &logthis("-$id-$name-$hostname-");
5909: if ($hostname eq $name) {
5910: push(@ids,$id);
5911: }
5912: }
5913: return @ids;
5914: }
5915:
5916: # ------------------------------------------------------------- Declutters URLs
5917:
5918: sub declutter {
5919: my $thisfn=shift;
5920: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
5921: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
5922: $thisfn=~s/^\///;
5923: $thisfn=~s/^res\///;
5924: $thisfn=~s/\?.+$//;
5925: return $thisfn;
5926: }
5927:
5928: # ------------------------------------------------------------- Clutter up URLs
5929:
5930: sub clutter {
5931: my $thisfn='/'.&declutter(shift);
5932: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
5933: $thisfn='/res'.$thisfn;
5934: }
5935: return $thisfn;
5936: }
5937:
5938: sub freeze_escape {
5939: my ($value)=@_;
5940: if (ref($value)) {
5941: $value=&nfreeze($value);
5942: return '__FROZEN__'.&escape($value);
5943: }
5944: return &escape($value);
5945: }
5946:
5947: # -------------------------------------------------------- Escape Special Chars
5948:
5949: sub escape {
5950: my $str=shift;
5951: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
5952: return $str;
5953: }
5954:
5955: # ----------------------------------------------------- Un-Escape Special Chars
5956:
5957: sub unescape {
5958: my $str=shift;
5959: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
5960: return $str;
5961: }
5962:
5963: sub thaw_unescape {
5964: my ($value)=@_;
5965: if ($value =~ /^__FROZEN__/) {
5966: substr($value,0,10,undef);
5967: $value=&unescape($value);
5968: return &thaw($value);
5969: }
5970: return &unescape($value);
5971: }
5972:
5973: sub correct_line_ends {
5974: my ($result)=@_;
5975: $$result =~s/\r\n/\n/mg;
5976: $$result =~s/\r/\n/mg;
5977: }
5978: # ================================================================ Main Program
5979:
5980: sub goodbye {
5981: &logthis("Starting Shut down");
5982: #not converted to using infrastruture and probably shouldn't be
5983: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
5984: #converted
5985: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
5986: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
5987: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
5988: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
5989: #1.1 only
5990: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
5991: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
5992: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
5993: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
5994: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
5995: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
5996: &logthis(sprintf("%-20s is %s",'hits',$hits));
5997: &flushcourselogs();
5998: &logthis("Shutting down");
5999: return DONE;
6000: }
6001:
6002: BEGIN {
6003: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
6004: unless ($readit) {
6005: {
6006: # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
6007: open(my $config,"</etc/httpd/conf/loncapa.conf");
6008:
6009: while (my $configline=<$config>) {
6010: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
6011: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
6012: chomp($varvalue);
6013: $perlvar{$varname}=$varvalue;
6014: }
6015: }
6016: close($config);
6017: }
6018: {
6019: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
6020:
6021: while (my $configline=<$config>) {
6022: if ($configline =~ /^[^\#]*PerlSetVar/) {
6023: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
6024: chomp($varvalue);
6025: $perlvar{$varname}=$varvalue;
6026: }
6027: }
6028: close($config);
6029: }
6030:
6031: # ------------------------------------------------------------ Read domain file
6032: {
6033: %domaindescription = ();
6034: %domain_auth_def = ();
6035: %domain_auth_arg_def = ();
6036: my $fh;
6037: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
6038: while (<$fh>) {
6039: next if (/^(\#|\s*$)/);
6040: # next if /^\#/;
6041: chomp;
6042: my ($domain, $domain_description, $def_auth, $def_auth_arg,
6043: $def_lang, $city, $longi, $lati) = split(/:/,$_);
6044: $domain_auth_def{$domain}=$def_auth;
6045: $domain_auth_arg_def{$domain}=$def_auth_arg;
6046: $domaindescription{$domain}=$domain_description;
6047: $domain_lang_def{$domain}=$def_lang;
6048: $domain_city{$domain}=$city;
6049: $domain_longi{$domain}=$longi;
6050: $domain_lati{$domain}=$lati;
6051:
6052: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
6053: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
6054: }
6055: }
6056: close ($fh);
6057: }
6058:
6059:
6060: # ------------------------------------------------------------- Read hosts file
6061: {
6062: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
6063:
6064: while (my $configline=<$config>) {
6065: next if ($configline =~ /^(\#|\s*$)/);
6066: chomp($configline);
6067: my ($id,$domain,$role,$name)=split(/:/,$configline);
6068: $name=~s/\s//g;
6069: if ($id && $domain && $role && $name) {
6070: $hostname{$id}=$name;
6071: $hostdom{$id}=$domain;
6072: if ($role eq 'library') { $libserv{$id}=$name; }
6073: }
6074: }
6075: close($config);
6076: # FIXME: dev server don't want this, production servers _do_ want this
6077: #&get_iphost();
6078: }
6079:
6080: sub get_iphost {
6081: if (%iphost) { return %iphost; }
6082: my %name_to_ip;
6083: foreach my $id (keys(%hostname)) {
6084: my $name=$hostname{$id};
6085: my $ip;
6086: if (!exists($name_to_ip{$name})) {
6087: $ip = gethostbyname($name);
6088: if (!$ip || length($ip) ne 4) {
6089: &logthis("Skipping host $id name $name no IP found\n");
6090: next;
6091: }
6092: $ip=inet_ntoa($ip);
6093: $name_to_ip{$name} = $ip;
6094: } else {
6095: $ip = $name_to_ip{$name};
6096: }
6097: push(@{$iphost{$ip}},$id);
6098: }
6099: return %iphost;
6100: }
6101:
6102: # ------------------------------------------------------ Read spare server file
6103: {
6104: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
6105:
6106: while (my $configline=<$config>) {
6107: chomp($configline);
6108: if ($configline) {
6109: $spareid{$configline}=1;
6110: }
6111: }
6112: close($config);
6113: }
6114: # ------------------------------------------------------------ Read permissions
6115: {
6116: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
6117:
6118: while (my $configline=<$config>) {
6119: chomp($configline);
6120: if ($configline) {
6121: my ($role,$perm)=split(/ /,$configline);
6122: if ($perm ne '') { $pr{$role}=$perm; }
6123: }
6124: }
6125: close($config);
6126: }
6127:
6128: # -------------------------------------------- Read plain texts for permissions
6129: {
6130: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
6131:
6132: while (my $configline=<$config>) {
6133: chomp($configline);
6134: if ($configline) {
6135: my ($short,$plain)=split(/:/,$configline);
6136: if ($plain ne '') { $prp{$short}=$plain; }
6137: }
6138: }
6139: close($config);
6140: }
6141:
6142: # ---------------------------------------------------------- Read package table
6143: {
6144: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
6145:
6146: while (my $configline=<$config>) {
6147: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
6148: chomp($configline);
6149: my ($short,$plain)=split(/:/,$configline);
6150: my ($pack,$name)=split(/\&/,$short);
6151: if ($plain ne '') {
6152: $packagetab{$pack.'&'.$name.'&name'}=$name;
6153: $packagetab{$short}=$plain;
6154: }
6155: }
6156: close($config);
6157: }
6158:
6159: # ------------- set up temporary directory
6160: {
6161: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
6162:
6163: }
6164:
6165: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
6166:
6167: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
6168: $dumpcount=0;
6169:
6170: &logtouch();
6171: &logthis('<font color="yellow">INFO: Read configuration</font>');
6172: $readit=1;
6173: {
6174: use integer;
6175: my $test=(2**32)+1;
6176: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
6177: &logthis(" Detected 64bit platform ($_64bit)");
6178: }
6179: }
6180: }
6181:
6182: 1;
6183: __END__
6184:
6185: =pod
6186:
6187: =head1 NAME
6188:
6189: Apache::lonnet - Subroutines to ask questions about things in the network.
6190:
6191: =head1 SYNOPSIS
6192:
6193: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
6194:
6195: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
6196:
6197: Common parameters:
6198:
6199: =over 4
6200:
6201: =item *
6202:
6203: $uname : an internal username (if $cname expecting a course Id specifically)
6204:
6205: =item *
6206:
6207: $udom : a domain (if $cdom expecting a course's domain specifically)
6208:
6209: =item *
6210:
6211: $symb : a resource instance identifier
6212:
6213: =item *
6214:
6215: $namespace : the name of a .db file that contains the data needed or
6216: being set.
6217:
6218: =back
6219:
6220: =head1 OVERVIEW
6221:
6222: lonnet provides subroutines which interact with the
6223: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
6224: about classes, users, and resources.
6225:
6226: For many of these objects you can also use this to store data about
6227: them or modify them in various ways.
6228:
6229: =head2 Symbs
6230:
6231: To identify a specific instance of a resource, LON-CAPA uses symbols
6232: or "symbs"X<symb>. These identifiers are built from the URL of the
6233: map, the resource number of the resource in the map, and the URL of
6234: the resource itself. The latter is somewhat redundant, but might help
6235: if maps change.
6236:
6237: An example is
6238:
6239: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
6240:
6241: The respective map entry is
6242:
6243: <resource id="19" src="/res/msu/korte/tests/part12.problem"
6244: title="Problem 2">
6245: </resource>
6246:
6247: Symbs are used by the random number generator, as well as to store and
6248: restore data specific to a certain instance of for example a problem.
6249:
6250: =head2 Storing And Retrieving Data
6251:
6252: X<store()>X<cstore()>X<restore()>Three of the most important functions
6253: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
6254: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
6255: is is the non-critical message twin of cstore. These functions are for
6256: handlers to store a perl hash to a user's permanent data space in an
6257: easy manner, and to retrieve it again on another call. It is expected
6258: that a handler would use this once at the beginning to retrieve data,
6259: and then again once at the end to send only the new data back.
6260:
6261: The data is stored in the user's data directory on the user's
6262: homeserver under the ID of the course.
6263:
6264: The hash that is returned by restore will have all of the previous
6265: value for all of the elements of the hash.
6266:
6267: Example:
6268:
6269: #creating a hash
6270: my %hash;
6271: $hash{'foo'}='bar';
6272:
6273: #storing it
6274: &Apache::lonnet::cstore(\%hash);
6275:
6276: #changing a value
6277: $hash{'foo'}='notbar';
6278:
6279: #adding a new value
6280: $hash{'bar'}='foo';
6281: &Apache::lonnet::cstore(\%hash);
6282:
6283: #retrieving the hash
6284: my %history=&Apache::lonnet::restore();
6285:
6286: #print the hash
6287: foreach my $key (sort(keys(%history))) {
6288: print("\%history{$key} = $history{$key}");
6289: }
6290:
6291: Will print out:
6292:
6293: %history{1:foo} = bar
6294: %history{1:keys} = foo:timestamp
6295: %history{1:timestamp} = 990455579
6296: %history{2:bar} = foo
6297: %history{2:foo} = notbar
6298: %history{2:keys} = foo:bar:timestamp
6299: %history{2:timestamp} = 990455580
6300: %history{bar} = foo
6301: %history{foo} = notbar
6302: %history{timestamp} = 990455580
6303: %history{version} = 2
6304:
6305: Note that the special hash entries C<keys>, C<version> and
6306: C<timestamp> were added to the hash. C<version> will be equal to the
6307: total number of versions of the data that have been stored. The
6308: C<timestamp> attribute will be the UNIX time the hash was
6309: stored. C<keys> is available in every historical section to list which
6310: keys were added or changed at a specific historical revision of a
6311: hash.
6312:
6313: B<Warning>: do not store the hash that restore returns directly. This
6314: will cause a mess since it will restore the historical keys as if the
6315: were new keys. I.E. 1:foo will become 1:1:foo etc.
6316:
6317: Calling convention:
6318:
6319: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
6320: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
6321:
6322: For more detailed information, see lonnet specific documentation.
6323:
6324: =head1 RETURN MESSAGES
6325:
6326: =over 4
6327:
6328: =item * B<con_lost>: unable to contact remote host
6329:
6330: =item * B<con_delayed>: unable to contact remote host, message will be delivered
6331: when the connection is brought back up
6332:
6333: =item * B<con_failed>: unable to contact remote host and unable to save message
6334: for later delivery
6335:
6336: =item * B<error:>: an error a occured, a description of the error follows the :
6337:
6338: =item * B<no_such_host>: unable to fund a host associated with the user/domain
6339: that was requested
6340:
6341: =back
6342:
6343: =head1 PUBLIC SUBROUTINES
6344:
6345: =head2 Session Environment Functions
6346:
6347: =over 4
6348:
6349: =item *
6350: X<appenv()>
6351: B<appenv(%hash)>: the value of %hash is written to
6352: the user envirnoment file, and will be restored for each access this
6353: user makes during this session, also modifies the %env for the current
6354: process
6355:
6356: =item *
6357: X<delenv()>
6358: B<delenv($regexp)>: removes all items from the session
6359: environment file that matches the regular expression in $regexp. The
6360: values are also delted from the current processes %env.
6361:
6362: =back
6363:
6364: =head2 User Information
6365:
6366: =over 4
6367:
6368: =item *
6369: X<queryauthenticate()>
6370: B<queryauthenticate($uname,$udom)>: try to determine user's current
6371: authentication scheme
6372:
6373: =item *
6374: X<authenticate()>
6375: B<authenticate($uname,$upass,$udom)>: try to
6376: authenticate user from domain's lib servers (first use the current
6377: one). C<$upass> should be the users password.
6378:
6379: =item *
6380: X<homeserver()>
6381: B<homeserver($uname,$udom)>: find the server which has
6382: the user's directory and files (there must be only one), this caches
6383: the answer, and also caches if there is a borken connection.
6384:
6385: =item *
6386: X<idget()>
6387: B<idget($udom,@ids)>: find the usernames behind a list of IDs
6388: (IDs are a unique resource in a domain, there must be only 1 ID per
6389: username, and only 1 username per ID in a specific domain) (returns
6390: hash: id=>name,id=>name)
6391:
6392: =item *
6393: X<idrget()>
6394: B<idrget($udom,@unames)>: find the IDs behind a list of
6395: usernames (returns hash: name=>id,name=>id)
6396:
6397: =item *
6398: X<idput()>
6399: B<idput($udom,%ids)>: store away a list of names and associated IDs
6400:
6401: =item *
6402: X<rolesinit()>
6403: B<rolesinit($udom,$username,$authhost)>: get user privileges
6404:
6405: =item *
6406: X<getsection()>
6407: B<getsection($udom,$uname,$cname)>: finds the section of student in the
6408: course $cname, return section name/number or '' for "not in course"
6409: and '-1' for "no section"
6410:
6411: =item *
6412: X<userenvironment()>
6413: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
6414: passed in @what from the requested user's environment, returns a hash
6415:
6416: =back
6417:
6418: =head2 User Roles
6419:
6420: =over 4
6421:
6422: =item *
6423:
6424: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
6425: actions
6426: F: full access
6427: U,I,K: authentication modes (cxx only)
6428: '': forbidden
6429: 1: user needs to choose course
6430: 2: browse allowed
6431:
6432: =item *
6433:
6434: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
6435: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
6436: and course level
6437:
6438: =item *
6439:
6440: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
6441: explanation of a user role term
6442:
6443: =back
6444:
6445: =head2 User Modification
6446:
6447: =over 4
6448:
6449: =item *
6450:
6451: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
6452: user for the level given by URL. Optional start and end dates (leave empty
6453: string or zero for "no date")
6454:
6455: =item *
6456:
6457: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
6458: change a users, password, possible return values are: ok,
6459: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
6460: refused
6461:
6462: =item *
6463:
6464: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
6465:
6466: =item *
6467:
6468: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
6469: modify user
6470:
6471: =item *
6472:
6473: modifystudent
6474:
6475: modify a students enrollment and identification information.
6476: The course id is resolved based on the current users environment.
6477: This means the envoking user must be a course coordinator or otherwise
6478: associated with a course.
6479:
6480: This call is essentially a wrapper for lonnet::modifyuser and
6481: lonnet::modify_student_enrollment
6482:
6483: Inputs:
6484:
6485: =over 4
6486:
6487: =item B<$udom> Students loncapa domain
6488:
6489: =item B<$uname> Students loncapa login name
6490:
6491: =item B<$uid> Students id/student number
6492:
6493: =item B<$umode> Students authentication mode
6494:
6495: =item B<$upass> Students password
6496:
6497: =item B<$first> Students first name
6498:
6499: =item B<$middle> Students middle name
6500:
6501: =item B<$last> Students last name
6502:
6503: =item B<$gene> Students generation
6504:
6505: =item B<$usec> Students section in course
6506:
6507: =item B<$end> Unix time of the roles expiration
6508:
6509: =item B<$start> Unix time of the roles start date
6510:
6511: =item B<$forceid> If defined, allow $uid to be changed
6512:
6513: =item B<$desiredhome> server to use as home server for student
6514:
6515: =back
6516:
6517: =item *
6518:
6519: modify_student_enrollment
6520:
6521: Change a students enrollment status in a class. The environment variable
6522: 'role.request.course' must be defined for this function to proceed.
6523:
6524: Inputs:
6525:
6526: =over 4
6527:
6528: =item $udom, students domain
6529:
6530: =item $uname, students name
6531:
6532: =item $uid, students user id
6533:
6534: =item $first, students first name
6535:
6536: =item $middle
6537:
6538: =item $last
6539:
6540: =item $gene
6541:
6542: =item $usec
6543:
6544: =item $end
6545:
6546: =item $start
6547:
6548: =back
6549:
6550:
6551: =item *
6552:
6553: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
6554: custom role; give a custom role to a user for the level given by URL. Specify
6555: name and domain of role author, and role name
6556:
6557: =item *
6558:
6559: revokerole($udom,$uname,$url,$role) : revoke a role for url
6560:
6561: =item *
6562:
6563: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
6564:
6565: =back
6566:
6567: =head2 Course Infomation
6568:
6569: =over 4
6570:
6571: =item *
6572:
6573: coursedescription($courseid) : returns a hash of information about the
6574: specified course id, including all environment settings for the
6575: course, the description of the course will be in the hash under the
6576: key 'description'
6577:
6578: =item *
6579:
6580: resdata($name,$domain,$type,@which) : request for current parameter
6581: setting for a specific $type, where $type is either 'course' or 'user',
6582: @what should be a list of parameters to ask about. This routine caches
6583: answers for 5 minutes.
6584:
6585: =back
6586:
6587: =head2 Course Modification
6588:
6589: =over 4
6590:
6591: =item *
6592:
6593: writecoursepref($courseid,%prefs) : write preferences (environment
6594: database) for a course
6595:
6596: =item *
6597:
6598: createcourse($udom,$description,$url) : make/modify course
6599:
6600: =back
6601:
6602: =head2 Resource Subroutines
6603:
6604: =over 4
6605:
6606: =item *
6607:
6608: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
6609:
6610: =item *
6611:
6612: repcopy($filename) : subscribes to the requested file, and attempts to
6613: replicate from the owning library server, Might return
6614: 'unavailable', 'not_found', 'forbidden', 'ok', or
6615: 'bad_request', also attempts to grab the metadata for the
6616: resource. Expects the local filesystem pathname
6617: (/home/httpd/html/res/....)
6618:
6619: =back
6620:
6621: =head2 Resource Information
6622:
6623: =over 4
6624:
6625: =item *
6626:
6627: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
6628: a vairety of different possible values, $varname should be a request
6629: string, and the other parameters can be used to specify who and what
6630: one is asking about.
6631:
6632: Possible values for $varname are environment.lastname (or other item
6633: from the envirnment hash), user.name (or someother aspect about the
6634: user), resource.0.maxtries (or some other part and parameter of a
6635: resource)
6636:
6637: =item *
6638:
6639: directcondval($number) : get current value of a condition; reads from a state
6640: string
6641:
6642: =item *
6643:
6644: condval($condidx) : value of condition index based on state
6645:
6646: =item *
6647:
6648: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
6649: resource's metadata, $what should be either a specific key, or either
6650: 'keys' (to get a list of possible keys) or 'packages' to get a list of
6651: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
6652:
6653: this function automatically caches all requests
6654:
6655: =item *
6656:
6657: metadata_query($query,$custom,$customshow) : make a metadata query against the
6658: network of library servers; returns file handle of where SQL and regex results
6659: will be stored for query
6660:
6661: =item *
6662:
6663: symbread($filename) : return symbolic list entry (filename argument optional);
6664: returns the data handle
6665:
6666: =item *
6667:
6668: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
6669: a possible symb for the URL in $thisfn, and if is an encryypted
6670: resource that the user accessed using /enc/ returns a 1 on success, 0
6671: on failure, user must be in a course, as it assumes the existance of
6672: the course initial hash, and uses $env('request.course.id'}
6673:
6674:
6675: =item *
6676:
6677: symbclean($symb) : removes versions numbers from a symb, returns the
6678: cleaned symb
6679:
6680: =item *
6681:
6682: is_on_map($uri) : checks if the $uri is somewhere on the current
6683: course map, user must be in a course for it to work.
6684:
6685: =item *
6686:
6687: numval($salt) : return random seed value (addend for rndseed)
6688:
6689: =item *
6690:
6691: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
6692: a random seed, all arguments are optional, if they aren't sent it uses the
6693: environment to derive them. Note: if symb isn't sent and it can't get one
6694: from &symbread it will use the current time as its return value
6695:
6696: =item *
6697:
6698: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
6699: unfakeable, receipt
6700:
6701: =item *
6702:
6703: receipt() : API to ireceipt working off of env values; given out to users
6704:
6705: =item *
6706:
6707: countacc($url) : count the number of accesses to a given URL
6708:
6709: =item *
6710:
6711: 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
6712:
6713: =item *
6714:
6715: 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)
6716:
6717: =item *
6718:
6719: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
6720:
6721: =item *
6722:
6723: devalidate($symb) : devalidate temporary spreadsheet calculations,
6724: forcing spreadsheet to reevaluate the resource scores next time.
6725:
6726: =back
6727:
6728: =head2 Storing/Retreiving Data
6729:
6730: =over 4
6731:
6732: =item *
6733:
6734: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
6735: for this url; hashref needs to be given and should be a \%hashname; the
6736: remaining args aren't required and if they aren't passed or are '' they will
6737: be derived from the env
6738:
6739: =item *
6740:
6741: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
6742: uses critical subroutine
6743:
6744: =item *
6745:
6746: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
6747: all args are optional
6748:
6749: =item *
6750:
6751: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
6752: works very similar to store/cstore, but all data is stored in a
6753: temporary location and can be reset using tmpreset, $storehash should
6754: be a hash reference, returns nothing on success
6755:
6756: =item *
6757:
6758: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
6759: similar to restore, but all data is stored in a temporary location and
6760: can be reset using tmpreset. Returns a hash of values on success,
6761: error string otherwise.
6762:
6763: =item *
6764:
6765: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
6766: deltes all keys for $symb form the temporary storage hash.
6767:
6768: =item *
6769:
6770: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6771: reference filled in from namesp ($udom and $uname are optional)
6772:
6773: =item *
6774:
6775: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
6776: namesp ($udom and $uname are optional)
6777:
6778: =item *
6779:
6780: dump($namespace,$udom,$uname,$regexp) :
6781: dumps the complete (or key matching regexp) namespace into a hash
6782: ($udom, $uname and $regexp are optional)
6783:
6784: =item *
6785:
6786: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
6787: $store can be a scalar, an array reference, or if the amount to be
6788: incremented is > 1, a hash reference.
6789:
6790: ($udom and $uname are optional)
6791:
6792: =item *
6793:
6794: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
6795: ($udom and $uname are optional)
6796:
6797: =item *
6798:
6799: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
6800: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
6801: used in records written by &store and retrieved by &restore. This function
6802: was created for use in editing discussion posts, without incrementing the
6803: version number included in the key for a particular post. The colon
6804: separated list of attribute names (e.g., the value associated with the key
6805: 1:keys:$symb) is also generated and passed in the ampersand separated
6806: items sent to lonnet::reply().
6807:
6808: =item *
6809:
6810: cput($namespace,$storehash,$udom,$uname) : critical put
6811: ($udom and $uname are optional)
6812:
6813: =item *
6814:
6815: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6816: reference filled in from namesp (encrypts the return communication)
6817: ($udom and $uname are optional)
6818:
6819: =item *
6820:
6821: log($udom,$name,$home,$message) : write to permanent log for user; use
6822: critical subroutine
6823:
6824: =back
6825:
6826: =head2 Network Status Functions
6827:
6828: =over 4
6829:
6830: =item *
6831:
6832: dirlist($uri) : return directory list based on URI
6833:
6834: =item *
6835:
6836: spareserver() : find server with least workload from spare.tab
6837:
6838: =back
6839:
6840: =head2 Apache Request
6841:
6842: =over 4
6843:
6844: =item *
6845:
6846: ssi($url,%hash) : server side include, does a complete request cycle on url to
6847: localhost, posts hash
6848:
6849: =back
6850:
6851: =head2 Data to String to Data
6852:
6853: =over 4
6854:
6855: =item *
6856:
6857: hash2str(%hash) : convert a hash into a string complete with escaping and '='
6858: and '&' separators, supports elements that are arrayrefs and hashrefs
6859:
6860: =item *
6861:
6862: hashref2str($hashref) : convert a hashref into a string complete with
6863: escaping and '=' and '&' separators, supports elements that are
6864: arrayrefs and hashrefs
6865:
6866: =item *
6867:
6868: arrayref2str($arrayref) : convert an arrayref into a string complete
6869: with escaping and '&' separators, supports elements that are arrayrefs
6870: and hashrefs
6871:
6872: =item *
6873:
6874: str2hash($string) : convert string to hash using unescaping and
6875: splitting on '=' and '&', supports elements that are arrayrefs and
6876: hashrefs
6877:
6878: =item *
6879:
6880: str2array($string) : convert string to hash using unescaping and
6881: splitting on '&', supports elements that are arrayrefs and hashrefs
6882:
6883: =back
6884:
6885: =head2 Logging Routines
6886:
6887: =over 4
6888:
6889: These routines allow one to make log messages in the lonnet.log and
6890: lonnet.perm logfiles.
6891:
6892: =item *
6893:
6894: logtouch() : make sure the logfile, lonnet.log, exists
6895:
6896: =item *
6897:
6898: logthis() : append message to the normal lonnet.log file, it gets
6899: preiodically rolled over and deleted.
6900:
6901: =item *
6902:
6903: logperm() : append a permanent message to lonnet.perm.log, this log
6904: file never gets deleted by any automated portion of the system, only
6905: messages of critical importance should go in here.
6906:
6907: =back
6908:
6909: =head2 General File Helper Routines
6910:
6911: =over 4
6912:
6913: =item *
6914:
6915: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
6916: (a) files in /uploaded
6917: (i) If a local copy of the file exists -
6918: compares modification date of local copy with last-modified date for
6919: definitive version stored on home server for course. If local copy is
6920: stale, requests a new version from the home server and stores it.
6921: If the original has been removed from the home server, then local copy
6922: is unlinked.
6923: (ii) If local copy does not exist -
6924: requests the file from the home server and stores it.
6925:
6926: If $caller is 'uploadrep':
6927: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
6928: for request for files originally uploaded via DOCS.
6929: - returns 'ok' if fresh local copy now available, -1 otherwise.
6930:
6931: Otherwise:
6932: This indicates a call from the content generation phase of the request.
6933: - returns the entire contents of the file or -1.
6934:
6935: (b) files in /res
6936: - returns the entire contents of a file or -1;
6937: it properly subscribes to and replicates the file if neccessary.
6938:
6939: =item *
6940:
6941: filelocation($dir,$file) : returns file system location of a file
6942: based on URI; meant to be "fairly clean" absolute reference, $dir is a
6943: directory that relative $file lookups are to looked in ($dir of /a/dir
6944: and a file of ../bob will become /a/bob)
6945:
6946: =item *
6947:
6948: hreflocation($dir,$file) : returns file system location or a URL; same as
6949: filelocation except for hrefs
6950:
6951: =item *
6952:
6953: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
6954:
6955: =back
6956:
6957: =head2 Usererfile file routines (/uploaded*)
6958:
6959: =over 4
6960:
6961: =item *
6962:
6963: userfileupload(): main rotine for putting a file in a user or course's
6964: filespace, arguments are,
6965:
6966: formname - required - this is the name of the element in $env where the
6967: filename, and the contents of the file to create/modifed exist
6968: the filename is in $env{'form.'.$formname.'.filename'} and the
6969: contents of the file is located in $env{'form.'.$formname}
6970: coursedoc - if true, store the file in the course of the active role
6971: of the current user
6972: subdir - required - subdirectory to put the file in under ../userfiles/
6973: if undefined, it will be placed in "unknown"
6974:
6975: (This routine calls clean_filename() to remove any dangerous
6976: characters from the filename, and then calls finuserfileupload() to
6977: complete the transaction)
6978:
6979: returns either the url of the uploaded file (/uploaded/....) if successful
6980: and /adm/notfound.html if unsuccessful
6981:
6982: =item *
6983:
6984: clean_filename(): routine for cleaing a filename up for storage in
6985: userfile space, argument is:
6986:
6987: filename - proposed filename
6988:
6989: returns: the new clean filename
6990:
6991: =item *
6992:
6993: finishuserfileupload(): routine that creaes and sends the file to
6994: userspace, probably shouldn't be called directly
6995:
6996: docuname: username or courseid of destination for the file
6997: docudom: domain of user/course of destination for the file
6998: formname: same as for userfileupload()
6999: fname: filename (inculding subdirectories) for the file
7000:
7001: returns either the url of the uploaded file (/uploaded/....) if successful
7002: and /adm/notfound.html if unsuccessful
7003:
7004: =item *
7005:
7006: renameuserfile(): renames an existing userfile to a new name
7007:
7008: Args:
7009: docuname: username or courseid of destination for the file
7010: docudom: domain of user/course of destination for the file
7011: old: current file name (including any subdirs under userfiles)
7012: new: desired file name (including any subdirs under userfiles)
7013:
7014: =item *
7015:
7016: mkdiruserfile(): creates a directory is a userfiles dir
7017:
7018: Args:
7019: docuname: username or courseid of destination for the file
7020: docudom: domain of user/course of destination for the file
7021: dir: dir to create (including any subdirs under userfiles)
7022:
7023: =item *
7024:
7025: removeuserfile(): removes a file that exists in userfiles
7026:
7027: Args:
7028: docuname: username or courseid of destination for the file
7029: docudom: domain of user/course of destination for the file
7030: fname: filname to delete (including any subdirs under userfiles)
7031:
7032: =item *
7033:
7034: removeuploadedurl(): convience function for removeuserfile()
7035:
7036: Args:
7037: url: a full /uploaded/... url to delete
7038:
7039: =back
7040:
7041: =head2 HTTP Helper Routines
7042:
7043: =over 4
7044:
7045: =item *
7046:
7047: escape() : unpack non-word characters into CGI-compatible hex codes
7048:
7049: =item *
7050:
7051: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
7052:
7053: =back
7054:
7055: =head1 PRIVATE SUBROUTINES
7056:
7057: =head2 Underlying communication routines (Shouldn't call)
7058:
7059: =over 4
7060:
7061: =item *
7062:
7063: subreply() : tries to pass a message to lonc, returns con_lost if incapable
7064:
7065: =item *
7066:
7067: reply() : uses subreply to send a message to remote machine, logs all failures
7068:
7069: =item *
7070:
7071: critical() : passes a critical message to another server; if cannot
7072: get through then place message in connection buffer directory and
7073: returns con_delayed, if incapable of saving message, returns
7074: con_failed
7075:
7076: =item *
7077:
7078: reconlonc() : tries to reconnect lonc client processes.
7079:
7080: =back
7081:
7082: =head2 Resource Access Logging
7083:
7084: =over 4
7085:
7086: =item *
7087:
7088: flushcourselogs() : flush (save) buffer logs and access logs
7089:
7090: =item *
7091:
7092: courselog($what) : save message for course in hash
7093:
7094: =item *
7095:
7096: courseacclog($what) : save message for course using &courselog(). Perform
7097: special processing for specific resource types (problems, exams, quizzes, etc).
7098:
7099: =item *
7100:
7101: goodbye() : flush course logs and log shutting down; it is called in srm.conf
7102: as a PerlChildExitHandler
7103:
7104: =back
7105:
7106: =head2 Other
7107:
7108: =over 4
7109:
7110: =item *
7111:
7112: symblist($mapname,%newhash) : update symbolic storage links
7113:
7114: =back
7115:
7116: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>