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