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