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