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