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