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