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