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