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