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