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