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