1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.756 2006/06/22 14:48:40 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 %coursetypebuf
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 HTML::LCParser;
49: use HTML::Parser;
50: use Fcntl qw(:flock);
51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
52: use Time::HiRes qw( gettimeofday tv_interval );
53: use Cache::Memcached;
54: use Digest::MD5;
55: use lib '/home/httpd/lib/perl';
56: use LONCAPA;
57: use LONCAPA::Configuration;
58:
59: my $readit;
60: my $max_connection_retries = 10; # Or some such value.
61:
62: require Exporter;
63:
64: our @ISA = qw (Exporter);
65: our @EXPORT = qw(%env);
66:
67: =pod
68:
69: =head1 Package Variables
70:
71: These are largely undocumented, so if you decipher one please note it here.
72:
73: =over 4
74:
75: =item $processmarker
76:
77: Contains the time this process was started and this servers host id.
78:
79: =item $dumpcount
80:
81: Counts the number of times a message log flush has been attempted (regardless
82: of success) by this process. Used as part of the filename when messages are
83: delayed.
84:
85: =back
86:
87: =cut
88:
89:
90: # --------------------------------------------------------------------- Logging
91: {
92: my $logid;
93: sub instructor_log {
94: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
95: $logid++;
96: my $id=time().'00000'.$$.'00000'.$logid;
97: return &Apache::lonnet::put('nohist_'.$hash_name,
98: { $id => {
99: 'exe_uname' => $env{'user.name'},
100: 'exe_udom' => $env{'user.domain'},
101: 'exe_time' => time(),
102: 'exe_ip' => $ENV{'REMOTE_ADDR'},
103: 'delflag' => $delflag,
104: 'logentry' => $storehash,
105: 'uname' => $uname,
106: 'udom' => $udom,
107: }
108: },
109: $env{'course.'.$env{'request.course.id'}.'.domain'},
110: $env{'course.'.$env{'request.course.id'}.'.num'}
111: );
112: }
113: }
114:
115: sub logtouch {
116: my $execdir=$perlvar{'lonDaemons'};
117: unless (-e "$execdir/logs/lonnet.log") {
118: open(my $fh,">>$execdir/logs/lonnet.log");
119: close $fh;
120: }
121: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
122: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
123: }
124:
125: sub logthis {
126: my $message=shift;
127: my $execdir=$perlvar{'lonDaemons'};
128: my $now=time;
129: my $local=localtime($now);
130: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
131: print $fh "$local ($$): $message\n";
132: close($fh);
133: }
134: return 1;
135: }
136:
137: sub logperm {
138: my $message=shift;
139: my $execdir=$perlvar{'lonDaemons'};
140: my $now=time;
141: my $local=localtime($now);
142: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
143: print $fh "$now:$message:$local\n";
144: close($fh);
145: }
146: return 1;
147: }
148:
149: # -------------------------------------------------- Non-critical communication
150: sub subreply {
151: my ($cmd,$server)=@_;
152: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
153: #
154: # With loncnew process trimming, there's a timing hole between lonc server
155: # process exit and the master server picking up the listen on the AF_UNIX
156: # socket. In that time interval, a lock file will exist:
157:
158: my $lockfile=$peerfile.".lock";
159: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
160: sleep(1);
161: }
162: # At this point, either a loncnew parent is listening or an old lonc
163: # or loncnew child is listening so we can connect or everything's dead.
164: #
165: # We'll give the connection a few tries before abandoning it. If
166: # connection is not possible, we'll con_lost back to the client.
167: #
168: my $client;
169: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
170: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
171: Type => SOCK_STREAM,
172: Timeout => 10);
173: if($client) {
174: last; # Connected!
175: }
176: sleep(1); # Try again later if failed connection.
177: }
178: my $answer;
179: if ($client) {
180: print $client "sethost:$server:$cmd\n";
181: $answer=<$client>;
182: if (!$answer) { $answer="con_lost"; }
183: chomp($answer);
184: } else {
185: $answer = 'con_lost'; # Failed connection.
186: }
187: return $answer;
188: }
189:
190: sub reply {
191: my ($cmd,$server)=@_;
192: unless (defined($hostname{$server})) { return 'no_such_host'; }
193: my $answer=subreply($cmd,$server);
194: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
195: &logthis("<font color=\"blue\">WARNING:".
196: " $cmd to $server returned $answer</font>");
197: }
198: return $answer;
199: }
200:
201: # ----------------------------------------------------------- Send USR1 to lonc
202:
203: sub reconlonc {
204: my $peerfile=shift;
205: &logthis("Trying to reconnect for $peerfile");
206: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
207: if (open(my $fh,"<$loncfile")) {
208: my $loncpid=<$fh>;
209: chomp($loncpid);
210: if (kill 0 => $loncpid) {
211: &logthis("lonc at pid $loncpid responding, sending USR1");
212: kill USR1 => $loncpid;
213: sleep 1;
214: if (-e "$peerfile") { return; }
215: &logthis("$peerfile still not there, give it another try");
216: sleep 5;
217: if (-e "$peerfile") { return; }
218: &logthis(
219: "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
220: } else {
221: &logthis(
222: "<font color=\"blue\">WARNING:".
223: " lonc at pid $loncpid not responding, giving up</font>");
224: }
225: } else {
226: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
227: }
228: }
229:
230: # ------------------------------------------------------ Critical communication
231:
232: sub critical {
233: my ($cmd,$server)=@_;
234: unless ($hostname{$server}) {
235: &logthis("<font color=\"blue\">WARNING:".
236: " Critical message to unknown server ($server)</font>");
237: return 'no_such_host';
238: }
239: my $answer=reply($cmd,$server);
240: if ($answer eq 'con_lost') {
241: &reconlonc("$perlvar{'lonSockDir'}/$server");
242: my $answer=reply($cmd,$server);
243: if ($answer eq 'con_lost') {
244: my $now=time;
245: my $middlename=$cmd;
246: $middlename=substr($middlename,0,16);
247: $middlename=~s/\W//g;
248: my $dfilename=
249: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
250: $dumpcount++;
251: {
252: my $dfh;
253: if (open($dfh,">$dfilename")) {
254: print $dfh "$cmd\n";
255: close($dfh);
256: }
257: }
258: sleep 2;
259: my $wcmd='';
260: {
261: my $dfh;
262: if (open($dfh,"<$dfilename")) {
263: $wcmd=<$dfh>;
264: close($dfh);
265: }
266: }
267: chomp($wcmd);
268: if ($wcmd eq $cmd) {
269: &logthis("<font color=\"blue\">WARNING: ".
270: "Connection buffer $dfilename: $cmd</font>");
271: &logperm("D:$server:$cmd");
272: return 'con_delayed';
273: } else {
274: &logthis("<font color=\"red\">CRITICAL:"
275: ." Critical connection failed: $server $cmd</font>");
276: &logperm("F:$server:$cmd");
277: return 'con_failed';
278: }
279: }
280: }
281: return $answer;
282: }
283:
284: # ------------------------------------------- check if return value is an error
285:
286: sub error {
287: my ($result) = @_;
288: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
289: if ($2 == 2) { return undef; }
290: return $1;
291: }
292: return undef;
293: }
294:
295: # ------------------------------------------- Transfer profile into environment
296:
297: sub transfer_profile_to_env {
298: my ($lonidsdir,$handle)=@_;
299: if (!defined($lonidsdir)) {
300: $lonidsdir = $perlvar{'lonIDsDir'};
301: }
302: if (!defined($handle)) {
303: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
304: }
305:
306: my @profile;
307: {
308: open(my $idf,"$lonidsdir/$handle.id");
309: flock($idf,LOCK_SH);
310: @profile=<$idf>;
311: close($idf);
312: }
313: my $envi;
314: my %Remove;
315: for ($envi=0;$envi<=$#profile;$envi++) {
316: chomp($profile[$envi]);
317: my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
318: $envname=&unescape($envname);
319: $envvalue=&unescape($envvalue);
320: $env{$envname} = $envvalue;
321: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
322: if ($time < time-300) {
323: $Remove{$key}++;
324: }
325: }
326: }
327: $env{'user.environment'} = "$lonidsdir/$handle.id";
328: foreach my $expired_key (keys(%Remove)) {
329: &delenv($expired_key);
330: }
331: }
332:
333: # ---------------------------------------------------------- Append Environment
334:
335: sub appenv {
336: my %newenv=@_;
337: foreach my $key (keys(%newenv)) {
338: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
339: &logthis("<font color=\"blue\">WARNING: ".
340: "Attempt to modify environment ".$key." to ".$newenv{$key}
341: .'</font>');
342: delete($newenv{$key});
343: } else {
344: $env{$key}=$newenv{$key};
345: }
346: }
347:
348: my $lockfh;
349: unless (open($lockfh,"$env{'user.environment'}")) {
350: return 'error: '.$!;
351: }
352: unless (flock($lockfh,LOCK_EX)) {
353: &logthis("<font color=\"blue\">WARNING: ".
354: 'Could not obtain exclusive lock in appenv: '.$!);
355: close($lockfh);
356: return 'error: '.$!;
357: }
358:
359: my @oldenv;
360: {
361: my $fh;
362: unless (open($fh,"$env{'user.environment'}")) {
363: return 'error: '.$!;
364: }
365: @oldenv=<$fh>;
366: close($fh);
367: }
368: for (my $i=0; $i<=$#oldenv; $i++) {
369: chomp($oldenv[$i]);
370: if ($oldenv[$i] ne '') {
371: my ($name,$value)=split(/=/,$oldenv[$i],2);
372: $name=&unescape($name);
373: $value=&unescape($value);
374: unless (defined($newenv{$name})) {
375: $newenv{$name}=$value;
376: }
377: }
378: }
379: {
380: my $fh;
381: unless (open($fh,">$env{'user.environment'}")) {
382: return 'error';
383: }
384: my $newname;
385: foreach $newname (keys %newenv) {
386: print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
387: }
388: close($fh);
389: }
390:
391: close($lockfh);
392: return 'ok';
393: }
394: # ----------------------------------------------------- Delete from Environment
395:
396: sub delenv {
397: my $delthis=shift;
398: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
399: &logthis("<font color=\"blue\">WARNING: ".
400: "Attempt to delete from environment ".$delthis);
401: return 'error';
402: }
403: my @oldenv;
404: {
405: my $fh;
406: unless (open($fh,"$env{'user.environment'}")) {
407: return 'error';
408: }
409: unless (flock($fh,LOCK_SH)) {
410: &logthis("<font color=\"blue\">WARNING: ".
411: 'Could not obtain shared lock in delenv: '.$!);
412: close($fh);
413: return 'error: '.$!;
414: }
415: @oldenv=<$fh>;
416: close($fh);
417: }
418: {
419: my $fh;
420: unless (open($fh,">$env{'user.environment'}")) {
421: return 'error';
422: }
423: unless (flock($fh,LOCK_EX)) {
424: &logthis("<font color=\"blue\">WARNING: ".
425: 'Could not obtain exclusive lock in delenv: '.$!);
426: close($fh);
427: return 'error: '.$!;
428: }
429: foreach my $cur_key (@oldenv) {
430: my $unescaped_cur_key = &unescape($cur_key);
431: if ($unescaped_cur_key=~/^$delthis/) {
432: my ($key) = split('=',$cur_key,2);
433: $key = &unescape($key);
434: delete($env{$key});
435: } else {
436: print $fh $cur_key;
437: }
438: }
439: close($fh);
440: }
441: return 'ok';
442: }
443:
444: # ------------------------------------------ Find out current server userload
445: # there is a copy in lond
446: sub userload {
447: my $numusers=0;
448: {
449: opendir(LONIDS,$perlvar{'lonIDsDir'});
450: my $filename;
451: my $curtime=time;
452: while ($filename=readdir(LONIDS)) {
453: if ($filename eq '.' || $filename eq '..') {next;}
454: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
455: if ($curtime-$mtime < 1800) { $numusers++; }
456: }
457: closedir(LONIDS);
458: }
459: my $userloadpercent=0;
460: my $maxuserload=$perlvar{'lonUserLoadLim'};
461: if ($maxuserload) {
462: $userloadpercent=100*$numusers/$maxuserload;
463: }
464: $userloadpercent=sprintf("%.2f",$userloadpercent);
465: return $userloadpercent;
466: }
467:
468: # ------------------------------------------ Fight off request when overloaded
469:
470: sub overloaderror {
471: my ($r,$checkserver)=@_;
472: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
473: my $loadavg;
474: if ($checkserver eq $perlvar{'lonHostID'}) {
475: open(my $loadfile,'/proc/loadavg');
476: $loadavg=<$loadfile>;
477: $loadavg =~ s/\s.*//g;
478: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
479: close($loadfile);
480: } else {
481: $loadavg=&reply('load',$checkserver);
482: }
483: my $overload=$loadavg-100;
484: if ($overload>0) {
485: $r->err_headers_out->{'Retry-After'}=$overload;
486: $r->log_error('Overload of '.$overload.' on '.$checkserver);
487: return 413;
488: }
489: return '';
490: }
491:
492: # ------------------------------ Find server with least workload from spare.tab
493:
494: sub spareserver {
495: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
496: my $tryserver;
497: my $spareserver='';
498: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
499: my $lowestserver=$loadpercent > $userloadpercent?
500: $loadpercent : $userloadpercent;
501: foreach $tryserver (keys(%spareid)) {
502: my $loadans=&reply('load',$tryserver);
503: my $userloadans=&reply('userload',$tryserver);
504: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
505: next; #didn't get a number from the server
506: }
507: my $answer;
508: if ($loadans =~ /\d/) {
509: if ($userloadans =~ /\d/) {
510: #both are numbers, pick the bigger one
511: $answer=$loadans > $userloadans?
512: $loadans : $userloadans;
513: } else {
514: $answer = $loadans;
515: }
516: } else {
517: $answer = $userloadans;
518: }
519: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
520: if ($want_server_name) {
521: $spareserver=$tryserver;
522: } else {
523: $spareserver="http://$hostname{$tryserver}";
524: }
525: $lowestserver=$answer;
526: }
527: }
528: return $spareserver;
529: }
530:
531: # --------------------------------------------- Try to change a user's password
532:
533: sub changepass {
534: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
535: $currentpass = &escape($currentpass);
536: $newpass = &escape($newpass);
537: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
538: $server);
539: if (! $answer) {
540: &logthis("No reply on password change request to $server ".
541: "by $uname in domain $udom.");
542: } elsif ($answer =~ "^ok") {
543: &logthis("$uname in $udom successfully changed their password ".
544: "on $server.");
545: } elsif ($answer =~ "^pwchange_failure") {
546: &logthis("$uname in $udom was unable to change their password ".
547: "on $server. The action was blocked by either lcpasswd ".
548: "or pwchange");
549: } elsif ($answer =~ "^non_authorized") {
550: &logthis("$uname in $udom did not get their password correct when ".
551: "attempting to change it on $server.");
552: } elsif ($answer =~ "^auth_mode_error") {
553: &logthis("$uname in $udom attempted to change their password despite ".
554: "not being locally or internally authenticated on $server.");
555: } elsif ($answer =~ "^unknown_user") {
556: &logthis("$uname in $udom attempted to change their password ".
557: "on $server but were unable to because $server is not ".
558: "their home server.");
559: } elsif ($answer =~ "^refused") {
560: &logthis("$server refused to change $uname in $udom password because ".
561: "it was sent an unencrypted request to change the password.");
562: }
563: return $answer;
564: }
565:
566: # ----------------------- Try to determine user's current authentication scheme
567:
568: sub queryauthenticate {
569: my ($uname,$udom)=@_;
570: my $uhome=&homeserver($uname,$udom);
571: if (!$uhome) {
572: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
573: return 'no_host';
574: }
575: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
576: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
577: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
578: }
579: return $answer;
580: }
581:
582: # --------- Try to authenticate user from domain's lib servers (first this one)
583:
584: sub authenticate {
585: my ($uname,$upass,$udom)=@_;
586: $upass=escape($upass);
587: $uname=~s/\W//g;
588: my $uhome=&homeserver($uname,$udom);
589: if (!$uhome) {
590: &logthis("User $uname at $udom is unknown in authenticate");
591: return 'no_host';
592: }
593: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
594: if ($answer eq 'authorized') {
595: &logthis("User $uname at $udom authorized by $uhome");
596: return $uhome;
597: }
598: if ($answer eq 'non_authorized') {
599: &logthis("User $uname at $udom rejected by $uhome");
600: return 'no_host';
601: }
602: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
603: return 'no_host';
604: }
605:
606: # ---------------------- Find the homebase for a user from domain's lib servers
607:
608: my %homecache;
609: sub homeserver {
610: my ($uname,$udom,$ignoreBadCache)=@_;
611: my $index="$uname:$udom";
612:
613: if (exists($homecache{$index})) { return $homecache{$index}; }
614: my $tryserver;
615: foreach $tryserver (keys %libserv) {
616: next if ($ignoreBadCache ne 'true' &&
617: exists($badServerCache{$tryserver}));
618: if ($hostdom{$tryserver} eq $udom) {
619: my $answer=reply("home:$udom:$uname",$tryserver);
620: if ($answer eq 'found') {
621: return $homecache{$index}=$tryserver;
622: } elsif ($answer eq 'no_host') {
623: $badServerCache{$tryserver}=1;
624: }
625: }
626: }
627: return 'no_host';
628: }
629:
630: # ------------------------------------- Find the usernames behind a list of IDs
631:
632: sub idget {
633: my ($udom,@ids)=@_;
634: my %returnhash=();
635:
636: my $tryserver;
637: foreach $tryserver (keys %libserv) {
638: if ($hostdom{$tryserver} eq $udom) {
639: my $idlist=join('&',@ids);
640: $idlist=~tr/A-Z/a-z/;
641: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
642: my @answer=();
643: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
644: @answer=split(/\&/,$reply);
645: } ;
646: my $i;
647: for ($i=0;$i<=$#ids;$i++) {
648: if ($answer[$i]) {
649: $returnhash{$ids[$i]}=$answer[$i];
650: }
651: }
652: }
653: }
654: return %returnhash;
655: }
656:
657: # ------------------------------------- Find the IDs behind a list of usernames
658:
659: sub idrget {
660: my ($udom,@unames)=@_;
661: my %returnhash=();
662: foreach (@unames) {
663: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
664: }
665: return %returnhash;
666: }
667:
668: # ------------------------------- Store away a list of names and associated IDs
669:
670: sub idput {
671: my ($udom,%ids)=@_;
672: my %servers=();
673: foreach (keys %ids) {
674: &cput('environment',{'id'=>$ids{$_}},$udom,$_);
675: my $uhom=&homeserver($_,$udom);
676: if ($uhom ne 'no_host') {
677: my $id=&escape($ids{$_});
678: $id=~tr/A-Z/a-z/;
679: my $unam=&escape($_);
680: if ($servers{$uhom}) {
681: $servers{$uhom}.='&'.$id.'='.$unam;
682: } else {
683: $servers{$uhom}=$id.'='.$unam;
684: }
685: }
686: }
687: foreach (keys %servers) {
688: &critical('idput:'.$udom.':'.$servers{$_},$_);
689: }
690: }
691:
692: # --------------------------------------------------- Assign a key to a student
693:
694: sub assign_access_key {
695: #
696: # a valid key looks like uname:udom#comments
697: # comments are being appended
698: #
699: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
700: $kdom=
701: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
702: $knum=
703: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
704: $cdom=
705: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
706: $cnum=
707: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
708: $udom=$env{'user.name'} unless (defined($udom));
709: $uname=$env{'user.domain'} unless (defined($uname));
710: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
711: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
712: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
713: # assigned to this person
714: # - this should not happen,
715: # unless something went wrong
716: # the first time around
717: # ready to assign
718: $logentry=$1.'; '.$logentry;
719: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
720: $kdom,$knum) eq 'ok') {
721: # key now belongs to user
722: my $envkey='key.'.$cdom.'_'.$cnum;
723: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
724: &appenv('environment.'.$envkey => $ckey);
725: return 'ok';
726: } else {
727: return
728: 'error: Count not permanently assign key, will need to be re-entered later.';
729: }
730: } else {
731: return 'error: Could not assign key, try again later.';
732: }
733: } elsif (!$existing{$ckey}) {
734: # the key does not exist
735: return 'error: The key does not exist';
736: } else {
737: # the key is somebody else's
738: return 'error: The key is already in use';
739: }
740: }
741:
742: # ------------------------------------------ put an additional comment on a key
743:
744: sub comment_access_key {
745: #
746: # a valid key looks like uname:udom#comments
747: # comments are being appended
748: #
749: my ($ckey,$cdom,$cnum,$logentry)=@_;
750: $cdom=
751: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
752: $cnum=
753: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
754: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
755: if ($existing{$ckey}) {
756: $existing{$ckey}.='; '.$logentry;
757: # ready to assign
758: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
759: $cdom,$cnum) eq 'ok') {
760: return 'ok';
761: } else {
762: return 'error: Count not store comment.';
763: }
764: } else {
765: # the key does not exist
766: return 'error: The key does not exist';
767: }
768: }
769:
770: # ------------------------------------------------------ Generate a set of keys
771:
772: sub generate_access_keys {
773: my ($number,$cdom,$cnum,$logentry)=@_;
774: $cdom=
775: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
776: $cnum=
777: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
778: unless (&allowed('mky',$cdom)) { return 0; }
779: unless (($cdom) && ($cnum)) { return 0; }
780: if ($number>10000) { return 0; }
781: sleep(2); # make sure don't get same seed twice
782: srand(time()^($$+($$<<15))); # from "Programming Perl"
783: my $total=0;
784: for (my $i=1;$i<=$number;$i++) {
785: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
786: sprintf("%lx",int(100000*rand)).'-'.
787: sprintf("%lx",int(100000*rand));
788: $newkey=~s/1/g/g; # folks mix up 1 and l
789: $newkey=~s/0/h/g; # and also 0 and O
790: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
791: if ($existing{$newkey}) {
792: $i--;
793: } else {
794: if (&put('accesskeys',
795: { $newkey => '# generated '.localtime().
796: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
797: '; '.$logentry },
798: $cdom,$cnum) eq 'ok') {
799: $total++;
800: }
801: }
802: }
803: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
804: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
805: return $total;
806: }
807:
808: # ------------------------------------------------------- Validate an accesskey
809:
810: sub validate_access_key {
811: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
812: $cdom=
813: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
814: $cnum=
815: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
816: $udom=$env{'user.domain'} unless (defined($udom));
817: $uname=$env{'user.name'} unless (defined($uname));
818: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
819: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
820: }
821:
822: # ------------------------------------- Find the section of student in a course
823: sub devalidate_getsection_cache {
824: my ($udom,$unam,$courseid)=@_;
825: $courseid=~s/\_/\//g;
826: $courseid=~s/^(\w)/\/$1/;
827: my $hashid="$udom:$unam:$courseid";
828: &devalidate_cache_new('getsection',$hashid);
829: }
830:
831: sub getsection {
832: my ($udom,$unam,$courseid)=@_;
833: my $cachetime=1800;
834: $courseid=~s/\_/\//g;
835: $courseid=~s/^(\w)/\/$1/;
836:
837: my $hashid="$udom:$unam:$courseid";
838: my ($result,$cached)=&is_cached_new('getsection',$hashid);
839: if (defined($cached)) { return $result; }
840:
841: my %Pending;
842: my %Expired;
843: #
844: # Each role can either have not started yet (pending), be active,
845: # or have expired.
846: #
847: # If there is an active role, we are done.
848: #
849: # If there is more than one role which has not started yet,
850: # choose the one which will start sooner
851: # If there is one role which has not started yet, return it.
852: #
853: # If there is more than one expired role, choose the one which ended last.
854: # If there is a role which has expired, return it.
855: #
856: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
857: &homeserver($unam,$udom)))) {
858: my ($key,$value)=split(/\=/,$_);
859: $key=&unescape($key);
860: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
861: my $section=$1;
862: if ($key eq $courseid.'_st') { $section=''; }
863: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
864: my $now=time;
865: if (defined($end) && $end && ($now > $end)) {
866: $Expired{$end}=$section;
867: next;
868: }
869: if (defined($start) && $start && ($now < $start)) {
870: $Pending{$start}=$section;
871: next;
872: }
873: return &do_cache_new('getsection',$hashid,$section,$cachetime);
874: }
875: #
876: # Presumedly there will be few matching roles from the above
877: # loop and the sorting time will be negligible.
878: if (scalar(keys(%Pending))) {
879: my ($time) = sort {$a <=> $b} keys(%Pending);
880: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
881: }
882: if (scalar(keys(%Expired))) {
883: my @sorted = sort {$a <=> $b} keys(%Expired);
884: my $time = pop(@sorted);
885: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
886: }
887: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
888: }
889:
890: sub save_cache {
891: &purge_remembered();
892: #&Apache::loncommon::validate_page();
893: undef(%env);
894: }
895:
896: my $to_remember=-1;
897: my %remembered;
898: my %accessed;
899: my $kicks=0;
900: my $hits=0;
901: sub devalidate_cache_new {
902: my ($name,$id,$debug) = @_;
903: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
904: $id=&escape($name.':'.$id);
905: $memcache->delete($id);
906: delete($remembered{$id});
907: delete($accessed{$id});
908: }
909:
910: sub is_cached_new {
911: my ($name,$id,$debug) = @_;
912: $id=&escape($name.':'.$id);
913: if (exists($remembered{$id})) {
914: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
915: $accessed{$id}=[&gettimeofday()];
916: $hits++;
917: return ($remembered{$id},1);
918: }
919: my $value = $memcache->get($id);
920: if (!(defined($value))) {
921: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
922: return (undef,undef);
923: }
924: if ($value eq '__undef__') {
925: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
926: $value=undef;
927: }
928: &make_room($id,$value,$debug);
929: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
930: return ($value,1);
931: }
932:
933: sub do_cache_new {
934: my ($name,$id,$value,$time,$debug) = @_;
935: $id=&escape($name.':'.$id);
936: my $setvalue=$value;
937: if (!defined($setvalue)) {
938: $setvalue='__undef__';
939: }
940: if (!defined($time) ) {
941: $time=600;
942: }
943: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
944: $memcache->set($id,$setvalue,$time);
945: # need to make a copy of $value
946: #&make_room($id,$value,$debug);
947: return $value;
948: }
949:
950: sub make_room {
951: my ($id,$value,$debug)=@_;
952: $remembered{$id}=$value;
953: if ($to_remember<0) { return; }
954: $accessed{$id}=[&gettimeofday()];
955: if (scalar(keys(%remembered)) <= $to_remember) { return; }
956: my $to_kick;
957: my $max_time=0;
958: foreach my $other (keys(%accessed)) {
959: if (&tv_interval($accessed{$other}) > $max_time) {
960: $to_kick=$other;
961: $max_time=&tv_interval($accessed{$other});
962: }
963: }
964: delete($remembered{$to_kick});
965: delete($accessed{$to_kick});
966: $kicks++;
967: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
968: return;
969: }
970:
971: sub purge_remembered {
972: #&logthis("Tossing ".scalar(keys(%remembered)));
973: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
974: undef(%remembered);
975: undef(%accessed);
976: }
977: # ------------------------------------- Read an entry from a user's environment
978:
979: sub userenvironment {
980: my ($udom,$unam,@what)=@_;
981: my %returnhash=();
982: my @answer=split(/\&/,
983: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
984: &homeserver($unam,$udom)));
985: my $i;
986: for ($i=0;$i<=$#what;$i++) {
987: $returnhash{$what[$i]}=&unescape($answer[$i]);
988: }
989: return %returnhash;
990: }
991:
992: # ---------------------------------------------------------- Get a studentphoto
993: sub studentphoto {
994: my ($udom,$unam,$ext) = @_;
995: my $home=&Apache::lonnet::homeserver($unam,$udom);
996: if (defined($env{'request.course.id'})) {
997: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
998: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
999: return(&retrievestudentphoto($udom,$unam,$ext));
1000: } else {
1001: my ($result,$perm_reqd)=
1002: &Apache::lonnet::auto_photo_permission($unam,$udom);
1003: if ($result eq 'ok') {
1004: if (!($perm_reqd eq 'yes')) {
1005: return(&retrievestudentphoto($udom,$unam,$ext));
1006: }
1007: }
1008: }
1009: }
1010: } else {
1011: my ($result,$perm_reqd) =
1012: &Apache::lonnet::auto_photo_permission($unam,$udom);
1013: if ($result eq 'ok') {
1014: if (!($perm_reqd eq 'yes')) {
1015: return(&retrievestudentphoto($udom,$unam,$ext));
1016: }
1017: }
1018: }
1019: return '/adm/lonKaputt/lonlogo_broken.gif';
1020: }
1021:
1022: sub retrievestudentphoto {
1023: my ($udom,$unam,$ext,$type) = @_;
1024: my $home=&Apache::lonnet::homeserver($unam,$udom);
1025: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1026: if ($ret eq 'ok') {
1027: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1028: if ($type eq 'thumbnail') {
1029: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1030: }
1031: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1032: return $tokenurl;
1033: } else {
1034: if ($type eq 'thumbnail') {
1035: return '/adm/lonKaputt/genericstudent_tn.gif';
1036: } else {
1037: return '/adm/lonKaputt/lonlogo_broken.gif';
1038: }
1039: }
1040: }
1041:
1042: # -------------------------------------------------------------------- New chat
1043:
1044: sub chatsend {
1045: my ($newentry,$anon,$group)=@_;
1046: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1047: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1048: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1049: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1050: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1051: &escape($newentry)).':'.$group,$chome);
1052: }
1053:
1054: # ------------------------------------------ Find current version of a resource
1055:
1056: sub getversion {
1057: my $fname=&clutter(shift);
1058: unless ($fname=~/^\/res\//) { return -1; }
1059: return ¤tversion(&filelocation('',$fname));
1060: }
1061:
1062: sub currentversion {
1063: my $fname=shift;
1064: my ($result,$cached)=&is_cached_new('resversion',$fname);
1065: if (defined($cached)) { return $result; }
1066: my $author=$fname;
1067: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1068: my ($udom,$uname)=split(/\//,$author);
1069: my $home=homeserver($uname,$udom);
1070: if ($home eq 'no_host') {
1071: return -1;
1072: }
1073: my $answer=reply("currentversion:$fname",$home);
1074: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1075: return -1;
1076: }
1077: return &do_cache_new('resversion',$fname,$answer,600);
1078: }
1079:
1080: # ----------------------------- Subscribe to a resource, return URL if possible
1081:
1082: sub subscribe {
1083: my $fname=shift;
1084: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1085: $fname=~s/[\n\r]//g;
1086: my $author=$fname;
1087: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1088: my ($udom,$uname)=split(/\//,$author);
1089: my $home=homeserver($uname,$udom);
1090: if ($home eq 'no_host') {
1091: return 'not_found';
1092: }
1093: my $answer=reply("sub:$fname",$home);
1094: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1095: $answer.=' by '.$home;
1096: }
1097: return $answer;
1098: }
1099:
1100: # -------------------------------------------------------------- Replicate file
1101:
1102: sub repcopy {
1103: my $filename=shift;
1104: $filename=~s/\/+/\//g;
1105: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1106: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1107: if ($filename=~m|^/home/httpd/html/userfiles/| or
1108: $filename=~m -^/*(uploaded|editupload)/-) {
1109: return &repcopy_userfile($filename);
1110: }
1111: $filename=~s/[\n\r]//g;
1112: my $transname="$filename.in.transfer";
1113: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1114: my $remoteurl=subscribe($filename);
1115: if ($remoteurl =~ /^con_lost by/) {
1116: &logthis("Subscribe returned $remoteurl: $filename");
1117: return 'unavailable';
1118: } elsif ($remoteurl eq 'not_found') {
1119: #&logthis("Subscribe returned not_found: $filename");
1120: return 'not_found';
1121: } elsif ($remoteurl =~ /^rejected by/) {
1122: &logthis("Subscribe returned $remoteurl: $filename");
1123: return 'forbidden';
1124: } elsif ($remoteurl eq 'directory') {
1125: return 'ok';
1126: } else {
1127: my $author=$filename;
1128: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1129: my ($udom,$uname)=split(/\//,$author);
1130: my $home=homeserver($uname,$udom);
1131: unless ($home eq $perlvar{'lonHostID'}) {
1132: my @parts=split(/\//,$filename);
1133: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1134: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1135: &logthis("Malconfiguration for replication: $filename");
1136: return 'bad_request';
1137: }
1138: my $count;
1139: for ($count=5;$count<$#parts;$count++) {
1140: $path.="/$parts[$count]";
1141: if ((-e $path)!=1) {
1142: mkdir($path,0777);
1143: }
1144: }
1145: my $ua=new LWP::UserAgent;
1146: my $request=new HTTP::Request('GET',"$remoteurl");
1147: my $response=$ua->request($request,$transname);
1148: if ($response->is_error()) {
1149: unlink($transname);
1150: my $message=$response->status_line;
1151: &logthis("<font color=\"blue\">WARNING:"
1152: ." LWP get: $message: $filename</font>");
1153: return 'unavailable';
1154: } else {
1155: if ($remoteurl!~/\.meta$/) {
1156: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1157: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1158: if ($mresponse->is_error()) {
1159: unlink($filename.'.meta');
1160: &logthis(
1161: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1162: }
1163: }
1164: rename($transname,$filename);
1165: return 'ok';
1166: }
1167: }
1168: }
1169: }
1170:
1171: # ------------------------------------------------ Get server side include body
1172: sub ssi_body {
1173: my ($filelink,%form)=@_;
1174: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1175: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1176: }
1177: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1178: &ssi($filelink,%form));
1179: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1180: $output=~s/^.*?\<body[^\>]*\>//si;
1181: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1182: return $output;
1183: }
1184:
1185: # --------------------------------------------------------- Server Side Include
1186:
1187: sub ssi {
1188:
1189: my ($fn,%form)=@_;
1190:
1191: my $ua=new LWP::UserAgent;
1192:
1193: my $request;
1194:
1195: $form{'no_update_last_known'}=1;
1196:
1197: if (%form) {
1198: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1199: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1200: } else {
1201: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
1202: }
1203:
1204: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1205: my $response=$ua->request($request);
1206:
1207: return $response->content;
1208: }
1209:
1210: sub externalssi {
1211: my ($url)=@_;
1212: my $ua=new LWP::UserAgent;
1213: my $request=new HTTP::Request('GET',$url);
1214: my $response=$ua->request($request);
1215: return $response->content;
1216: }
1217:
1218: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1219:
1220: sub allowuploaded {
1221: my ($srcurl,$url)=@_;
1222: $url=&clutter(&declutter($url));
1223: my $dir=$url;
1224: $dir=~s/\/[^\/]+$//;
1225: my %httpref=();
1226: my $httpurl=&hreflocation('',$url);
1227: $httpref{'httpref.'.$httpurl}=$srcurl;
1228: &Apache::lonnet::appenv(%httpref);
1229: }
1230:
1231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1232: # input: action, courseID, current domain, intended
1233: # path to file, source of file, instruction to parse file for objects,
1234: # ref to hash for embedded objects,
1235: # ref to hash for codebase of java objects.
1236: #
1237: # output: url to file (if action was uploaddoc),
1238: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1239: #
1240: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1241: # course.
1242: #
1243: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1244: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1245: # course's home server.
1246: #
1247: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1248: # be copied from $source (current location) to
1249: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1250: # and will then be copied to
1251: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1252: # course's home server.
1253: #
1254: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1255: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1256: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1257: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1258: # in course's home server.
1259: #
1260:
1261: sub process_coursefile {
1262: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1263: my $fetchresult;
1264: my $home=&homeserver($docuname,$docudom);
1265: if ($action eq 'propagate') {
1266: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1267: $home);
1268: } else {
1269: my $fpath = '';
1270: my $fname = $file;
1271: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1272: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1273: my $filepath = &build_filepath($fpath);
1274: if ($action eq 'copy') {
1275: if ($source eq '') {
1276: $fetchresult = 'no source file';
1277: return $fetchresult;
1278: } else {
1279: my $destination = $filepath.'/'.$fname;
1280: rename($source,$destination);
1281: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1282: $home);
1283: }
1284: } elsif ($action eq 'uploaddoc') {
1285: open(my $fh,'>'.$filepath.'/'.$fname);
1286: print $fh $env{'form.'.$source};
1287: close($fh);
1288: if ($parser eq 'parse') {
1289: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1290: unless ($parse_result eq 'ok') {
1291: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1292: }
1293: }
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: unless ( $fetchresult eq 'ok') {
1306: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1307: ' to host '.$home.': '.$fetchresult);
1308: }
1309: return $fetchresult;
1310: }
1311:
1312: sub build_filepath {
1313: my ($fpath) = @_;
1314: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1315: unless ($fpath eq '') {
1316: my @parts=split('/',$fpath);
1317: foreach my $part (@parts) {
1318: $filepath.= '/'.$part;
1319: if ((-e $filepath)!=1) {
1320: mkdir($filepath,0777);
1321: }
1322: }
1323: }
1324: return $filepath;
1325: }
1326:
1327: sub store_edited_file {
1328: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1329: my $file = $primary_url;
1330: $file =~ s#^/uploaded/$docudom/$docuname/##;
1331: my $fpath = '';
1332: my $fname = $file;
1333: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1334: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1335: my $filepath = &build_filepath($fpath);
1336: open(my $fh,'>'.$filepath.'/'.$fname);
1337: print $fh $content;
1338: close($fh);
1339: my $home=&homeserver($docuname,$docudom);
1340: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1341: $home);
1342: if ($$fetchresult eq 'ok') {
1343: return '/uploaded/'.$fpath.'/'.$fname;
1344: } else {
1345: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1346: ' to host '.$home.': '.$$fetchresult);
1347: return '/adm/notfound.html';
1348: }
1349: }
1350:
1351: sub clean_filename {
1352: my ($fname)=@_;
1353: # Replace Windows backslashes by forward slashes
1354: $fname=~s/\\/\//g;
1355: # Get rid of everything but the actual filename
1356: $fname=~s/^.*\/([^\/]+)$/$1/;
1357: # Replace spaces by underscores
1358: $fname=~s/\s+/\_/g;
1359: # Replace all other weird characters by nothing
1360: $fname=~s/[^\w\.\-]//g;
1361: # Replace all .\d. sequences with _\d. so they no longer look like version
1362: # numbers
1363: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1364: return $fname;
1365: }
1366:
1367: # --------------- Take an uploaded file and put it into the userfiles directory
1368: # input: $formname - the contents of the file are in $env{"form.$formname"}
1369: # the desired filenam is in $env{"form.$formname.filename"}
1370: # $coursedoc - if true up to the current course
1371: # if false
1372: # $subdir - directory in userfile to store the file into
1373: # $parser, $allfiles, $codebase - unknown
1374: #
1375: # output: url of file in userspace, or error: <message>
1376: # or /adm/notfound.html if failure to upload occurse
1377:
1378:
1379: sub userfileupload {
1380: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1381: if (!defined($subdir)) { $subdir='unknown'; }
1382: my $fname=$env{'form.'.$formname.'.filename'};
1383: $fname=&clean_filename($fname);
1384: # See if there is anything left
1385: unless ($fname) { return 'error: no uploaded file'; }
1386: chop($env{'form.'.$formname});
1387: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1388: my $now = time;
1389: my $filepath = 'tmp/helprequests/'.$now;
1390: my @parts=split(/\//,$filepath);
1391: my $fullpath = $perlvar{'lonDaemons'};
1392: for (my $i=0;$i<@parts;$i++) {
1393: $fullpath .= '/'.$parts[$i];
1394: if ((-e $fullpath)!=1) {
1395: mkdir($fullpath,0777);
1396: }
1397: }
1398: open(my $fh,'>'.$fullpath.'/'.$fname);
1399: print $fh $env{'form.'.$formname};
1400: close($fh);
1401: return $fullpath.'/'.$fname;
1402: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1403: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1404: '_'.$env{'user.domain'}.'/pending';
1405: my @parts=split(/\//,$filepath);
1406: my $fullpath = $perlvar{'lonDaemons'};
1407: for (my $i=0;$i<@parts;$i++) {
1408: $fullpath .= '/'.$parts[$i];
1409: if ((-e $fullpath)!=1) {
1410: mkdir($fullpath,0777);
1411: }
1412: }
1413: open(my $fh,'>'.$fullpath.'/'.$fname);
1414: print $fh $env{'form.'.$formname};
1415: close($fh);
1416: return $fullpath.'/'.$fname;
1417: }
1418:
1419: # Create the directory if not present
1420: $fname="$subdir/$fname";
1421: if ($coursedoc) {
1422: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1423: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1424: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1425: return &finishuserfileupload($docuname,$docudom,
1426: $formname,$fname,$parser,$allfiles,
1427: $codebase);
1428: } else {
1429: $fname=$env{'form.folder'}.'/'.$fname;
1430: return &process_coursefile('uploaddoc',$docuname,$docudom,
1431: $fname,$formname,$parser,
1432: $allfiles,$codebase);
1433: }
1434: } elsif (defined($destuname)) {
1435: my $docuname=$destuname;
1436: my $docudom=$destudom;
1437: return &finishuserfileupload($docuname,$docudom,$formname,
1438: $fname,$parser,$allfiles,$codebase);
1439:
1440: } else {
1441: my $docuname=$env{'user.name'};
1442: my $docudom=$env{'user.domain'};
1443: if (exists($env{'form.group'})) {
1444: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1445: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1446: }
1447: return &finishuserfileupload($docuname,$docudom,$formname,
1448: $fname,$parser,$allfiles,$codebase);
1449: }
1450: }
1451:
1452: sub finishuserfileupload {
1453: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1454: my $path=$docudom.'/'.$docuname.'/';
1455: my $filepath=$perlvar{'lonDocRoot'};
1456: my ($fnamepath,$file);
1457: $file=$fname;
1458: if ($fname=~m|/|) {
1459: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1460: $path.=$fnamepath.'/';
1461: }
1462: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1463: my $count;
1464: for ($count=4;$count<=$#parts;$count++) {
1465: $filepath.="/$parts[$count]";
1466: if ((-e $filepath)!=1) {
1467: mkdir($filepath,0777);
1468: }
1469: }
1470: # Save the file
1471: {
1472: if (!open(FH,'>'.$filepath.'/'.$file)) {
1473: &logthis('Failed to create '.$filepath.'/'.$file);
1474: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1475: return '/adm/notfound.html';
1476: }
1477: if (!print FH ($env{'form.'.$formname})) {
1478: &logthis('Failed to write to '.$filepath.'/'.$file);
1479: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1480: return '/adm/notfound.html';
1481: }
1482: close(FH);
1483: }
1484: if ($parser eq 'parse') {
1485: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1486: $codebase);
1487: unless ($parse_result eq 'ok') {
1488: &logthis('Failed to parse '.$filepath.$file.
1489: ' for embedded media: '.$parse_result);
1490: }
1491: }
1492: # Notify homeserver to grep it
1493: #
1494: my $docuhome=&homeserver($docuname,$docudom);
1495: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1496: if ($fetchresult eq 'ok') {
1497: #
1498: # Return the URL to it
1499: return '/uploaded/'.$path.$file;
1500: } else {
1501: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1502: ': '.$fetchresult);
1503: return '/adm/notfound.html';
1504: }
1505: }
1506:
1507: sub extract_embedded_items {
1508: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1509: my @state = ();
1510: my %javafiles = (
1511: codebase => '',
1512: code => '',
1513: archive => ''
1514: );
1515: my %mediafiles = (
1516: src => '',
1517: movie => '',
1518: );
1519: my $p;
1520: if ($content) {
1521: $p = HTML::LCParser->new($content);
1522: } else {
1523: $p = HTML::LCParser->new($filepath.'/'.$file);
1524: }
1525: while (my $t=$p->get_token()) {
1526: if ($t->[0] eq 'S') {
1527: my ($tagname, $attr) = ($t->[1],$t->[2]);
1528: push (@state, $tagname);
1529: if (lc($tagname) eq 'allow') {
1530: &add_filetype($allfiles,$attr->{'src'},'src');
1531: }
1532: if (lc($tagname) eq 'img') {
1533: &add_filetype($allfiles,$attr->{'src'},'src');
1534: }
1535: if (lc($tagname) eq 'script') {
1536: if ($attr->{'archive'} =~ /\.jar$/i) {
1537: &add_filetype($allfiles,$attr->{'archive'},'archive');
1538: } else {
1539: &add_filetype($allfiles,$attr->{'src'},'src');
1540: }
1541: }
1542: if (lc($tagname) eq 'link') {
1543: if (lc($attr->{'rel'}) eq 'stylesheet') {
1544: &add_filetype($allfiles,$attr->{'href'},'href');
1545: }
1546: }
1547: if (lc($tagname) eq 'object' ||
1548: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1549: foreach my $item (keys(%javafiles)) {
1550: $javafiles{$item} = '';
1551: }
1552: }
1553: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1554: my $name = lc($attr->{'name'});
1555: foreach my $item (keys(%javafiles)) {
1556: if ($name eq $item) {
1557: $javafiles{$item} = $attr->{'value'};
1558: last;
1559: }
1560: }
1561: foreach my $item (keys(%mediafiles)) {
1562: if ($name eq $item) {
1563: &add_filetype($allfiles, $attr->{'value'}, 'value');
1564: last;
1565: }
1566: }
1567: }
1568: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1569: foreach my $item (keys(%javafiles)) {
1570: if ($attr->{$item}) {
1571: $javafiles{$item} = $attr->{$item};
1572: last;
1573: }
1574: }
1575: foreach my $item (keys(%mediafiles)) {
1576: if ($attr->{$item}) {
1577: &add_filetype($allfiles,$attr->{$item},$item);
1578: last;
1579: }
1580: }
1581: }
1582: } elsif ($t->[0] eq 'E') {
1583: my ($tagname) = ($t->[1]);
1584: if ($javafiles{'codebase'} ne '') {
1585: $javafiles{'codebase'} .= '/';
1586: }
1587: if (lc($tagname) eq 'applet' ||
1588: lc($tagname) eq 'object' ||
1589: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1590: ) {
1591: foreach my $item (keys(%javafiles)) {
1592: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1593: my $file=$javafiles{'codebase'}.$javafiles{$item};
1594: &add_filetype($allfiles,$file,$item);
1595: }
1596: }
1597: }
1598: pop @state;
1599: }
1600: }
1601: return 'ok';
1602: }
1603:
1604: sub add_filetype {
1605: my ($allfiles,$file,$type)=@_;
1606: if (exists($allfiles->{$file})) {
1607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1608: push(@{$allfiles->{$file}}, &escape($type));
1609: }
1610: } else {
1611: @{$allfiles->{$file}} = (&escape($type));
1612: }
1613: }
1614:
1615: sub removeuploadedurl {
1616: my ($url)=@_;
1617: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1618: return &removeuserfile($uname,$udom,$fname);
1619: }
1620:
1621: sub removeuserfile {
1622: my ($docuname,$docudom,$fname)=@_;
1623: my $home=&homeserver($docuname,$docudom);
1624: return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1625: }
1626:
1627: sub mkdiruserfile {
1628: my ($docuname,$docudom,$dir)=@_;
1629: my $home=&homeserver($docuname,$docudom);
1630: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1631: }
1632:
1633: sub renameuserfile {
1634: my ($docuname,$docudom,$old,$new)=@_;
1635: my $home=&homeserver($docuname,$docudom);
1636: return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
1637: &escape("$new"),$home);
1638: }
1639:
1640: # ------------------------------------------------------------------------- Log
1641:
1642: sub log {
1643: my ($dom,$nam,$hom,$what)=@_;
1644: return critical("log:$dom:$nam:$what",$hom);
1645: }
1646:
1647: # ------------------------------------------------------------------ Course Log
1648: #
1649: # This routine flushes several buffers of non-mission-critical nature
1650: #
1651:
1652: sub flushcourselogs {
1653: &logthis('Flushing log buffers');
1654: #
1655: # course logs
1656: # This is a log of all transactions in a course, which can be used
1657: # for data mining purposes
1658: #
1659: # It also collects the courseid database, which lists last transaction
1660: # times and course titles for all courseids
1661: #
1662: my %courseidbuffer=();
1663: foreach (keys %courselogs) {
1664: my $crsid=$_;
1665: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1666: &escape($courselogs{$crsid}),
1667: $coursehombuf{$crsid}) eq 'ok') {
1668: delete $courselogs{$crsid};
1669: } else {
1670: &logthis('Failed to flush log buffer for '.$crsid);
1671: if (length($courselogs{$crsid})>40000) {
1672: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1673: " exceeded maximum size, deleting.</font>");
1674: delete $courselogs{$crsid};
1675: }
1676: }
1677: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1678: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1679: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1680: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1681: } else {
1682: $courseidbuffer{$coursehombuf{$crsid}}=
1683: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1684: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1685: }
1686: }
1687: #
1688: # Write course id database (reverse lookup) to homeserver of courses
1689: # Is used in pickcourse
1690: #
1691: foreach (keys %courseidbuffer) {
1692: &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1693: }
1694: #
1695: # File accesses
1696: # Writes to the dynamic metadata of resources to get hit counts, etc.
1697: #
1698: foreach my $entry (keys(%accesshash)) {
1699: if ($entry =~ /___count$/) {
1700: my ($dom,$name);
1701: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
1702: if (! defined($dom) || $dom eq '' ||
1703: ! defined($name) || $name eq '') {
1704: my $cid = $env{'request.course.id'};
1705: $dom = $env{'request.'.$cid.'.domain'};
1706: $name = $env{'request.'.$cid.'.num'};
1707: }
1708: my $value = $accesshash{$entry};
1709: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1710: my %temphash=($url => $value);
1711: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1712: if ($result eq 'ok') {
1713: delete $accesshash{$entry};
1714: } elsif ($result eq 'unknown_cmd') {
1715: # Target server has old code running on it.
1716: my %temphash=($entry => $value);
1717: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1718: delete $accesshash{$entry};
1719: }
1720: }
1721: } else {
1722: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1723: my %temphash=($entry => $accesshash{$entry});
1724: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1725: delete $accesshash{$entry};
1726: }
1727: }
1728: }
1729: #
1730: # Roles
1731: # Reverse lookup of user roles for course faculty/staff and co-authorship
1732: #
1733: foreach (keys %userrolehash) {
1734: my $entry=$_;
1735: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1736: split(/\:/,$entry);
1737: if (&Apache::lonnet::put('nohist_userroles',
1738: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1739: $rudom,$runame) eq 'ok') {
1740: delete $userrolehash{$entry};
1741: }
1742: }
1743: #
1744: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1745: #
1746: my %domrolebuffer = ();
1747: foreach my $entry (keys %domainrolehash) {
1748: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1749: if ($domrolebuffer{$rudom}) {
1750: $domrolebuffer{$rudom}.='&'.&escape($entry).
1751: '='.&escape($domainrolehash{$entry});
1752: } else {
1753: $domrolebuffer{$rudom}.=&escape($entry).
1754: '='.&escape($domainrolehash{$entry});
1755: }
1756: delete $domainrolehash{$entry};
1757: }
1758: foreach my $dom (keys(%domrolebuffer)) {
1759: foreach my $tryserver (keys %libserv) {
1760: if ($hostdom{$tryserver} eq $dom) {
1761: unless (&reply('domroleput:'.$dom.':'.
1762: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1763: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1764: }
1765: }
1766: }
1767: }
1768: $dumpcount++;
1769: }
1770:
1771: sub courselog {
1772: my $what=shift;
1773: $what=time.':'.$what;
1774: unless ($env{'request.course.id'}) { return ''; }
1775: $coursedombuf{$env{'request.course.id'}}=
1776: $env{'course.'.$env{'request.course.id'}.'.domain'};
1777: $coursenumbuf{$env{'request.course.id'}}=
1778: $env{'course.'.$env{'request.course.id'}.'.num'};
1779: $coursehombuf{$env{'request.course.id'}}=
1780: $env{'course.'.$env{'request.course.id'}.'.home'};
1781: $coursedescrbuf{$env{'request.course.id'}}=
1782: $env{'course.'.$env{'request.course.id'}.'.description'};
1783: $courseinstcodebuf{$env{'request.course.id'}}=
1784: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1785: $courseownerbuf{$env{'request.course.id'}}=
1786: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1787: $coursetypebuf{$env{'request.course.id'}}=
1788: $env{'course.'.$env{'request.course.id'}.'.type'};
1789: if (defined $courselogs{$env{'request.course.id'}}) {
1790: $courselogs{$env{'request.course.id'}}.='&'.$what;
1791: } else {
1792: $courselogs{$env{'request.course.id'}}.=$what;
1793: }
1794: if (length($courselogs{$env{'request.course.id'}})>4048) {
1795: &flushcourselogs();
1796: }
1797: }
1798:
1799: sub courseacclog {
1800: my $fnsymb=shift;
1801: unless ($env{'request.course.id'}) { return ''; }
1802: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1803: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1804: $what.=':POST';
1805: # FIXME: Probably ought to escape things....
1806: foreach (keys %env) {
1807: if ($_=~/^form\.(.*)/) {
1808: $what.=':'.$1.'='.$env{$_};
1809: }
1810: }
1811: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1812: # FIXME: We should not be depending on a form parameter that someone
1813: # editing lonsearchcat.pm might change in the future.
1814: if ($env{'form.phase'} eq 'course_search') {
1815: $what.= ':POST';
1816: # FIXME: Probably ought to escape things....
1817: foreach my $element ('courseexp','crsfulltext','crsrelated',
1818: 'crsdiscuss') {
1819: $what.=':'.$element.'='.$env{'form.'.$element};
1820: }
1821: }
1822: }
1823: &courselog($what);
1824: }
1825:
1826: sub countacc {
1827: my $url=&declutter(shift);
1828: return if (! defined($url) || $url eq '');
1829: unless ($env{'request.course.id'}) { return ''; }
1830: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1831: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1832: $accesshash{$key}++;
1833: }
1834:
1835: sub linklog {
1836: my ($from,$to)=@_;
1837: $from=&declutter($from);
1838: $to=&declutter($to);
1839: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1840: $accesshash{$to.'___'.$from.'___goto'}=1;
1841: }
1842:
1843: sub userrolelog {
1844: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1845: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1846: ($trole=~/^in/) || ($trole=~/^cc/) ||
1847: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1848: ($trole=~/^ta/)) {
1849: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1850: $userrolehash
1851: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1852: =$tend.':'.$tstart;
1853: }
1854: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
1855: ($trole=~/^li/) || ($trole=~/^li/) ||
1856: ($trole=~/^au/) || ($trole=~/^dg/) ||
1857: ($trole=~/^sc/)) {
1858: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1859: $domainrolehash
1860: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1861: = $tend.':'.$tstart;
1862: }
1863: }
1864:
1865: sub get_course_adv_roles {
1866: my $cid=shift;
1867: $cid=$env{'request.course.id'} unless (defined($cid));
1868: my %coursehash=&coursedescription($cid);
1869: my %nothide=();
1870: foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1871: $nothide{join(':',split(/[\@\:]/,$_))}=1;
1872: }
1873: my %returnhash=();
1874: my %dumphash=
1875: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1876: my $now=time;
1877: foreach (keys %dumphash) {
1878: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1879: if (($tstart) && ($tstart<0)) { next; }
1880: if (($tend) && ($tend<$now)) { next; }
1881: if (($tstart) && ($now<$tstart)) { next; }
1882: my ($role,$username,$domain,$section)=split(/\:/,$_);
1883: if ($username eq '' || $domain eq '') { next; }
1884: if ((&privileged($username,$domain)) &&
1885: (!$nothide{$username.':'.$domain})) { next; }
1886: if ($role eq 'cr') { next; }
1887: my $key=&plaintext($role);
1888: if ($role =~ /^cr/) {
1889: $key=(split('/',$role))[3];
1890: }
1891: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1892: if ($returnhash{$key}) {
1893: $returnhash{$key}.=','.$username.':'.$domain;
1894: } else {
1895: $returnhash{$key}=$username.':'.$domain;
1896: }
1897: }
1898: return %returnhash;
1899: }
1900:
1901: sub get_my_roles {
1902: my ($uname,$udom)=@_;
1903: unless (defined($uname)) { $uname=$env{'user.name'}; }
1904: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1905: my %dumphash=
1906: &dump('nohist_userroles',$udom,$uname);
1907: my %returnhash=();
1908: my $now=time;
1909: foreach (keys %dumphash) {
1910: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1911: if (($tstart) && ($tstart<0)) { next; }
1912: if (($tend) && ($tend<$now)) { next; }
1913: if (($tstart) && ($now<$tstart)) { next; }
1914: my ($role,$username,$domain,$section)=split(/\:/,$_);
1915: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1916: }
1917: return %returnhash;
1918: }
1919:
1920: # ----------------------------------------------------- Frontpage Announcements
1921: #
1922: #
1923:
1924: sub postannounce {
1925: my ($server,$text)=@_;
1926: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1927: unless ($text=~/\w/) { $text=''; }
1928: return &reply('setannounce:'.&escape($text),$server);
1929: }
1930:
1931: sub getannounce {
1932:
1933: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1934: my $announcement='';
1935: while (<$fh>) { $announcement .=$_; }
1936: close($fh);
1937: if ($announcement=~/\w/) {
1938: return
1939: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1940: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1941: } else {
1942: return '';
1943: }
1944: } else {
1945: return '';
1946: }
1947: }
1948:
1949: # ---------------------------------------------------------- Course ID routines
1950: # Deal with domain's nohist_courseid.db files
1951: #
1952:
1953: sub courseidput {
1954: my ($domain,$what,$coursehome)=@_;
1955: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1956: }
1957:
1958: sub courseiddump {
1959: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1960: my %returnhash=();
1961: unless ($domfilter) { $domfilter=''; }
1962: foreach my $tryserver (keys %libserv) {
1963: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1964: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1965: foreach (
1966: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1967: $sincefilter.':'.&escape($descfilter).':'.
1968: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1969: $tryserver))) {
1970: my ($key,$value)=split(/\=/,$_);
1971: if (($key) && ($value)) {
1972: $returnhash{&unescape($key)}=$value;
1973: }
1974: }
1975: }
1976: }
1977: }
1978: return %returnhash;
1979: }
1980:
1981: # ---------------------------------------------------------- DC e-mail
1982:
1983: sub dcmailput {
1984: my ($domain,$msgid,$message,$server)=@_;
1985: my $status = &Apache::lonnet::critical(
1986: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
1987: &escape($message),$server);
1988: return $status;
1989: }
1990:
1991: sub dcmaildump {
1992: my ($dom,$startdate,$enddate,$senders) = @_;
1993: my %returnhash=();
1994: if (exists($domain_primary{$dom})) {
1995: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
1996: &escape($enddate).':';
1997: my @esc_senders=map { &escape($_)} @$senders;
1998: $cmd.=&escape(join('&',@esc_senders));
1999: foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
2000: my ($key,$value) = split(/\=/,$_);
2001: if (($key) && ($value)) {
2002: $returnhash{&unescape($key)} = &unescape($value);
2003: }
2004: }
2005: }
2006: return %returnhash;
2007: }
2008: # ---------------------------------------------------------- Domain roles
2009:
2010: sub get_domain_roles {
2011: my ($dom,$roles,$startdate,$enddate)=@_;
2012: if (undef($startdate) || $startdate eq '') {
2013: $startdate = '.';
2014: }
2015: if (undef($enddate) || $enddate eq '') {
2016: $enddate = '.';
2017: }
2018: my $rolelist = join(':',@{$roles});
2019: my %personnel = ();
2020: foreach my $tryserver (keys(%libserv)) {
2021: if ($hostdom{$tryserver} eq $dom) {
2022: %{$personnel{$tryserver}}=();
2023: foreach (
2024: split(/\&/,&reply('domrolesdump:'.$dom.':'.
2025: &escape($startdate).':'.&escape($enddate).':'.
2026: &escape($rolelist), $tryserver))) {
2027: my($key,$value) = split(/\=/,$_);
2028: if (($key) && ($value)) {
2029: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2030: }
2031: }
2032: }
2033: }
2034: return %personnel;
2035: }
2036:
2037: # ----------------------------------------------------------- Check out an item
2038:
2039: sub get_first_access {
2040: my ($type,$argsymb)=@_;
2041: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
2042: if ($argsymb) { $symb=$argsymb; }
2043: my ($map,$id,$res)=&decode_symb($symb);
2044: if ($type eq 'map') {
2045: $res=&symbread($map);
2046: } else {
2047: $res=$symb;
2048: }
2049: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2050: return $times{"$courseid\0$res"};
2051: }
2052:
2053: sub set_first_access {
2054: my ($type)=@_;
2055: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
2056: my ($map,$id,$res)=&decode_symb($symb);
2057: if ($type eq 'map') {
2058: $res=&symbread($map);
2059: } else {
2060: $res=$symb;
2061: }
2062: my $firstaccess=&get_first_access($type,$symb);
2063: if (!$firstaccess) {
2064: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2065: }
2066: return 'already_set';
2067: }
2068:
2069: sub checkout {
2070: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2071: my $now=time;
2072: my $lonhost=$perlvar{'lonHostID'};
2073: my $infostr=&escape(
2074: 'CHECKOUTTOKEN&'.
2075: $tuname.'&'.
2076: $tudom.'&'.
2077: $tcrsid.'&'.
2078: $symb.'&'.
2079: $now.'&'.$ENV{'REMOTE_ADDR'});
2080: my $token=&reply('tmpput:'.$infostr,$lonhost);
2081: if ($token=~/^error\:/) {
2082: &logthis("<font color=\"blue\">WARNING: ".
2083: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2084: "</font>");
2085: return '';
2086: }
2087:
2088: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2089: $token=~tr/a-z/A-Z/;
2090:
2091: my %infohash=('resource.0.outtoken' => $token,
2092: 'resource.0.checkouttime' => $now,
2093: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2094:
2095: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2096: return '';
2097: } else {
2098: &logthis("<font color=\"blue\">WARNING: ".
2099: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2100: "</font>");
2101: }
2102:
2103: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2104: &escape('Checkout '.$infostr.' - '.
2105: $token)) ne 'ok') {
2106: return '';
2107: } else {
2108: &logthis("<font color=\"blue\">WARNING: ".
2109: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2110: "</font>");
2111: }
2112: return $token;
2113: }
2114:
2115: # ------------------------------------------------------------ Check in an item
2116:
2117: sub checkin {
2118: my $token=shift;
2119: my $now=time;
2120: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2121: $lonhost=~tr/A-Z/a-z/;
2122: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
2123: $dtoken=~s/\W/\_/g;
2124: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
2125: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2126:
2127: unless (($tuname) && ($tudom)) {
2128: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2129: return '';
2130: }
2131:
2132: unless (&allowed('mgr',$tcrsid)) {
2133: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
2134: $env{'user.name'}.' - '.$env{'user.domain'});
2135: return '';
2136: }
2137:
2138: my %infohash=('resource.0.intoken' => $token,
2139: 'resource.0.checkintime' => $now,
2140: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
2141:
2142: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2143: return '';
2144: }
2145:
2146: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2147: &escape('Checkin - '.$token)) ne 'ok') {
2148: return '';
2149: }
2150:
2151: return ($symb,$tuname,$tudom,$tcrsid);
2152: }
2153:
2154: # --------------------------------------------- Set Expire Date for Spreadsheet
2155:
2156: sub expirespread {
2157: my ($uname,$udom,$stype,$usymb)=@_;
2158: my $cid=$env{'request.course.id'};
2159: if ($cid) {
2160: my $now=time;
2161: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2162: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2163: $env{'course.'.$cid.'.num'}.
2164: ':nohist_expirationdates:'.
2165: &escape($key).'='.$now,
2166: $env{'course.'.$cid.'.home'})
2167: }
2168: return 'ok';
2169: }
2170:
2171: # ----------------------------------------------------- Devalidate Spreadsheets
2172:
2173: sub devalidate {
2174: my ($symb,$uname,$udom)=@_;
2175: my $cid=$env{'request.course.id'};
2176: if ($cid) {
2177: # delete the stored spreadsheets for
2178: # - the student level sheet of this user in course's homespace
2179: # - the assessment level sheet for this resource
2180: # for this user in user's homespace
2181: # - current conditional state info
2182: my $key=$uname.':'.$udom.':';
2183: my $status=
2184: &del('nohist_calculatedsheets',
2185: [$key.'studentcalc:'],
2186: $env{'course.'.$cid.'.domain'},
2187: $env{'course.'.$cid.'.num'})
2188: .' '.
2189: &del('nohist_calculatedsheets_'.$cid,
2190: [$key.'assesscalc:'.$symb],$udom,$uname);
2191: unless ($status eq 'ok ok') {
2192: &logthis('Could not devalidate spreadsheet '.
2193: $uname.' at '.$udom.' for '.
2194: $symb.': '.$status);
2195: }
2196: &delenv('user.state.'.$cid);
2197: }
2198: }
2199:
2200: sub get_scalar {
2201: my ($string,$end) = @_;
2202: my $value;
2203: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2204: $value = $1;
2205: } elsif ($$string =~ s/^([^&]*?)&//) {
2206: $value = $1;
2207: }
2208: return &unescape($value);
2209: }
2210:
2211: sub array2str {
2212: my (@array) = @_;
2213: my $result=&arrayref2str(\@array);
2214: $result=~s/^__ARRAY_REF__//;
2215: $result=~s/__END_ARRAY_REF__$//;
2216: return $result;
2217: }
2218:
2219: sub arrayref2str {
2220: my ($arrayref) = @_;
2221: my $result='__ARRAY_REF__';
2222: foreach my $elem (@$arrayref) {
2223: if(ref($elem) eq 'ARRAY') {
2224: $result.=&arrayref2str($elem).'&';
2225: } elsif(ref($elem) eq 'HASH') {
2226: $result.=&hashref2str($elem).'&';
2227: } elsif(ref($elem)) {
2228: #print("Got a ref of ".(ref($elem))." skipping.");
2229: } else {
2230: $result.=&escape($elem).'&';
2231: }
2232: }
2233: $result=~s/\&$//;
2234: $result .= '__END_ARRAY_REF__';
2235: return $result;
2236: }
2237:
2238: sub hash2str {
2239: my (%hash) = @_;
2240: my $result=&hashref2str(\%hash);
2241: $result=~s/^__HASH_REF__//;
2242: $result=~s/__END_HASH_REF__$//;
2243: return $result;
2244: }
2245:
2246: sub hashref2str {
2247: my ($hashref)=@_;
2248: my $result='__HASH_REF__';
2249: foreach (sort(keys(%$hashref))) {
2250: if (ref($_) eq 'ARRAY') {
2251: $result.=&arrayref2str($_).'=';
2252: } elsif (ref($_) eq 'HASH') {
2253: $result.=&hashref2str($_).'=';
2254: } elsif (ref($_)) {
2255: $result.='=';
2256: #print("Got a ref of ".(ref($_))." skipping.");
2257: } else {
2258: if ($_) {$result.=&escape($_).'=';} else { last; }
2259: }
2260:
2261: if(ref($hashref->{$_}) eq 'ARRAY') {
2262: $result.=&arrayref2str($hashref->{$_}).'&';
2263: } elsif(ref($hashref->{$_}) eq 'HASH') {
2264: $result.=&hashref2str($hashref->{$_}).'&';
2265: } elsif(ref($hashref->{$_})) {
2266: $result.='&';
2267: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
2268: } else {
2269: $result.=&escape($hashref->{$_}).'&';
2270: }
2271: }
2272: $result=~s/\&$//;
2273: $result .= '__END_HASH_REF__';
2274: return $result;
2275: }
2276:
2277: sub str2hash {
2278: my ($string)=@_;
2279: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2280: return %$hash;
2281: }
2282:
2283: sub str2hashref {
2284: my ($string) = @_;
2285:
2286: my %hash;
2287:
2288: if($string !~ /^__HASH_REF__/) {
2289: if (! ($string eq '' || !defined($string))) {
2290: $hash{'error'}='Not hash reference';
2291: }
2292: return (\%hash, $string);
2293: }
2294:
2295: $string =~ s/^__HASH_REF__//;
2296:
2297: while($string !~ /^__END_HASH_REF__/) {
2298: #key
2299: my $key='';
2300: if($string =~ /^__HASH_REF__/) {
2301: ($key, $string)=&str2hashref($string);
2302: if(defined($key->{'error'})) {
2303: $hash{'error'}='Bad data';
2304: return (\%hash, $string);
2305: }
2306: } elsif($string =~ /^__ARRAY_REF__/) {
2307: ($key, $string)=&str2arrayref($string);
2308: if($key->[0] eq 'Array reference error') {
2309: $hash{'error'}='Bad data';
2310: return (\%hash, $string);
2311: }
2312: } else {
2313: $string =~ s/^(.*?)=//;
2314: $key=&unescape($1);
2315: }
2316: $string =~ s/^=//;
2317:
2318: #value
2319: my $value='';
2320: if($string =~ /^__HASH_REF__/) {
2321: ($value, $string)=&str2hashref($string);
2322: if(defined($value->{'error'})) {
2323: $hash{'error'}='Bad data';
2324: return (\%hash, $string);
2325: }
2326: } elsif($string =~ /^__ARRAY_REF__/) {
2327: ($value, $string)=&str2arrayref($string);
2328: if($value->[0] eq 'Array reference error') {
2329: $hash{'error'}='Bad data';
2330: return (\%hash, $string);
2331: }
2332: } else {
2333: $value=&get_scalar(\$string,'__END_HASH_REF__');
2334: }
2335: $string =~ s/^&//;
2336:
2337: $hash{$key}=$value;
2338: }
2339:
2340: $string =~ s/^__END_HASH_REF__//;
2341:
2342: return (\%hash, $string);
2343: }
2344:
2345: sub str2array {
2346: my ($string)=@_;
2347: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2348: return @$array;
2349: }
2350:
2351: sub str2arrayref {
2352: my ($string) = @_;
2353: my @array;
2354:
2355: if($string !~ /^__ARRAY_REF__/) {
2356: if (! ($string eq '' || !defined($string))) {
2357: $array[0]='Array reference error';
2358: }
2359: return (\@array, $string);
2360: }
2361:
2362: $string =~ s/^__ARRAY_REF__//;
2363:
2364: while($string !~ /^__END_ARRAY_REF__/) {
2365: my $value='';
2366: if($string =~ /^__HASH_REF__/) {
2367: ($value, $string)=&str2hashref($string);
2368: if(defined($value->{'error'})) {
2369: $array[0] ='Array reference error';
2370: return (\@array, $string);
2371: }
2372: } elsif($string =~ /^__ARRAY_REF__/) {
2373: ($value, $string)=&str2arrayref($string);
2374: if($value->[0] eq 'Array reference error') {
2375: $array[0] ='Array reference error';
2376: return (\@array, $string);
2377: }
2378: } else {
2379: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2380: }
2381: $string =~ s/^&//;
2382:
2383: push(@array, $value);
2384: }
2385:
2386: $string =~ s/^__END_ARRAY_REF__//;
2387:
2388: return (\@array, $string);
2389: }
2390:
2391: # -------------------------------------------------------------------Temp Store
2392:
2393: sub tmpreset {
2394: my ($symb,$namespace,$domain,$stuname) = @_;
2395: if (!$symb) {
2396: $symb=&symbread();
2397: if (!$symb) { $symb= $env{'request.url'}; }
2398: }
2399: $symb=escape($symb);
2400:
2401: if (!$namespace) { $namespace=$env{'request.state'}; }
2402: $namespace=~s/\//\_/g;
2403: $namespace=~s/\W//g;
2404:
2405: if (!$domain) { $domain=$env{'user.domain'}; }
2406: if (!$stuname) { $stuname=$env{'user.name'}; }
2407: if ($domain eq 'public' && $stuname eq 'public') {
2408: $stuname=$ENV{'REMOTE_ADDR'};
2409: }
2410: my $path=$perlvar{'lonDaemons'}.'/tmp';
2411: my %hash;
2412: if (tie(%hash,'GDBM_File',
2413: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2414: &GDBM_WRCREAT(),0640)) {
2415: foreach my $key (keys %hash) {
2416: if ($key=~ /:$symb/) {
2417: delete($hash{$key});
2418: }
2419: }
2420: }
2421: }
2422:
2423: sub tmpstore {
2424: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2425:
2426: if (!$symb) {
2427: $symb=&symbread();
2428: if (!$symb) { $symb= $env{'request.url'}; }
2429: }
2430: $symb=escape($symb);
2431:
2432: if (!$namespace) {
2433: # I don't think we would ever want to store this for a course.
2434: # it seems this will only be used if we don't have a course.
2435: #$namespace=$env{'request.course.id'};
2436: #if (!$namespace) {
2437: $namespace=$env{'request.state'};
2438: #}
2439: }
2440: $namespace=~s/\//\_/g;
2441: $namespace=~s/\W//g;
2442: if (!$domain) { $domain=$env{'user.domain'}; }
2443: if (!$stuname) { $stuname=$env{'user.name'}; }
2444: if ($domain eq 'public' && $stuname eq 'public') {
2445: $stuname=$ENV{'REMOTE_ADDR'};
2446: }
2447: my $now=time;
2448: my %hash;
2449: my $path=$perlvar{'lonDaemons'}.'/tmp';
2450: if (tie(%hash,'GDBM_File',
2451: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2452: &GDBM_WRCREAT(),0640)) {
2453: $hash{"version:$symb"}++;
2454: my $version=$hash{"version:$symb"};
2455: my $allkeys='';
2456: foreach my $key (keys(%$storehash)) {
2457: $allkeys.=$key.':';
2458: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
2459: }
2460: $hash{"$version:$symb:timestamp"}=$now;
2461: $allkeys.='timestamp';
2462: $hash{"$version:keys:$symb"}=$allkeys;
2463: if (untie(%hash)) {
2464: return 'ok';
2465: } else {
2466: return "error:$!";
2467: }
2468: } else {
2469: return "error:$!";
2470: }
2471: }
2472:
2473: # -----------------------------------------------------------------Temp Restore
2474:
2475: sub tmprestore {
2476: my ($symb,$namespace,$domain,$stuname) = @_;
2477:
2478: if (!$symb) {
2479: $symb=&symbread();
2480: if (!$symb) { $symb= $env{'request.url'}; }
2481: }
2482: $symb=escape($symb);
2483:
2484: if (!$namespace) { $namespace=$env{'request.state'}; }
2485:
2486: if (!$domain) { $domain=$env{'user.domain'}; }
2487: if (!$stuname) { $stuname=$env{'user.name'}; }
2488: if ($domain eq 'public' && $stuname eq 'public') {
2489: $stuname=$ENV{'REMOTE_ADDR'};
2490: }
2491: my %returnhash;
2492: $namespace=~s/\//\_/g;
2493: $namespace=~s/\W//g;
2494: my %hash;
2495: my $path=$perlvar{'lonDaemons'}.'/tmp';
2496: if (tie(%hash,'GDBM_File',
2497: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
2498: &GDBM_READER(),0640)) {
2499: my $version=$hash{"version:$symb"};
2500: $returnhash{'version'}=$version;
2501: my $scope;
2502: for ($scope=1;$scope<=$version;$scope++) {
2503: my $vkeys=$hash{"$scope:keys:$symb"};
2504: my @keys=split(/:/,$vkeys);
2505: my $key;
2506: $returnhash{"$scope:keys"}=$vkeys;
2507: foreach $key (@keys) {
2508: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2509: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2510: }
2511: }
2512: if (!(untie(%hash))) {
2513: return "error:$!";
2514: }
2515: } else {
2516: return "error:$!";
2517: }
2518: return %returnhash;
2519: }
2520:
2521: # ----------------------------------------------------------------------- Store
2522:
2523: sub store {
2524: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2525: my $home='';
2526:
2527: if ($stuname) { $home=&homeserver($stuname,$domain); }
2528:
2529: $symb=&symbclean($symb);
2530: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2531:
2532: if (!$domain) { $domain=$env{'user.domain'}; }
2533: if (!$stuname) { $stuname=$env{'user.name'}; }
2534:
2535: &devalidate($symb,$stuname,$domain);
2536:
2537: $symb=escape($symb);
2538: if (!$namespace) {
2539: unless ($namespace=$env{'request.course.id'}) {
2540: return '';
2541: }
2542: }
2543: if (!$home) { $home=$env{'user.home'}; }
2544:
2545: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2546: $$storehash{'host'}=$perlvar{'lonHostID'};
2547:
2548: my $namevalue='';
2549: foreach (keys %$storehash) {
2550: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
2551: }
2552: $namevalue=~s/\&$//;
2553: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
2554: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2555: }
2556:
2557: # -------------------------------------------------------------- Critical Store
2558:
2559: sub cstore {
2560: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2561: my $home='';
2562:
2563: if ($stuname) { $home=&homeserver($stuname,$domain); }
2564:
2565: $symb=&symbclean($symb);
2566: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
2567:
2568: if (!$domain) { $domain=$env{'user.domain'}; }
2569: if (!$stuname) { $stuname=$env{'user.name'}; }
2570:
2571: &devalidate($symb,$stuname,$domain);
2572:
2573: $symb=escape($symb);
2574: if (!$namespace) {
2575: unless ($namespace=$env{'request.course.id'}) {
2576: return '';
2577: }
2578: }
2579: if (!$home) { $home=$env{'user.home'}; }
2580:
2581: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2582: $$storehash{'host'}=$perlvar{'lonHostID'};
2583:
2584: my $namevalue='';
2585: foreach (keys %$storehash) {
2586: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
2587: }
2588: $namevalue=~s/\&$//;
2589: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
2590: return critical
2591: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
2592: }
2593:
2594: # --------------------------------------------------------------------- Restore
2595:
2596: sub restore {
2597: my ($symb,$namespace,$domain,$stuname) = @_;
2598: my $home='';
2599:
2600: if ($stuname) { $home=&homeserver($stuname,$domain); }
2601:
2602: if (!$symb) {
2603: unless ($symb=escape(&symbread())) { return ''; }
2604: } else {
2605: $symb=&escape(&symbclean($symb));
2606: }
2607: if (!$namespace) {
2608: unless ($namespace=$env{'request.course.id'}) {
2609: return '';
2610: }
2611: }
2612: if (!$domain) { $domain=$env{'user.domain'}; }
2613: if (!$stuname) { $stuname=$env{'user.name'}; }
2614: if (!$home) { $home=$env{'user.home'}; }
2615: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2616:
2617: my %returnhash=();
2618: foreach (split(/\&/,$answer)) {
2619: my ($name,$value)=split(/\=/,$_);
2620: $returnhash{&unescape($name)}=&thaw_unescape($value);
2621: }
2622: my $version;
2623: for ($version=1;$version<=$returnhash{'version'};$version++) {
2624: foreach (split(/\:/,$returnhash{$version.':keys'})) {
2625: $returnhash{$_}=$returnhash{$version.':'.$_};
2626: }
2627: }
2628: return %returnhash;
2629: }
2630:
2631: # ---------------------------------------------------------- Course Description
2632:
2633: sub coursedescription {
2634: my ($courseid,$args)=@_;
2635: $courseid=~s/^\///;
2636: $courseid=~s/\_/\//g;
2637: my ($cdomain,$cnum)=split(/\//,$courseid);
2638: my $chome=&homeserver($cnum,$cdomain);
2639: my $normalid=$cdomain.'_'.$cnum;
2640: # need to always cache even if we get errors otherwise we keep
2641: # trying and trying and trying to get the course description.
2642: my %envhash=();
2643: my %returnhash=();
2644:
2645: my $expiretime=600;
2646: if ($env{'request.course.id'} eq $normalid) {
2647: $expiretime=120;
2648: }
2649:
2650: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2651: if (!$args->{'freshen_cache'}
2652: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2653: foreach my $key (keys(%env)) {
2654: next if ($key !~ /^\Q$prefix\E(.*)/);
2655: my ($setting) = $1;
2656: $returnhash{$setting} = $env{$key};
2657: }
2658: return %returnhash;
2659: }
2660:
2661: # get the data agin
2662: if (!$args->{'one_time'}) {
2663: $envhash{'course.'.$normalid.'.last_cache'}=time;
2664: }
2665: if ($chome ne 'no_host') {
2666: %returnhash=&dump('environment',$cdomain,$cnum);
2667: if (!exists($returnhash{'con_lost'})) {
2668: $returnhash{'home'}= $chome;
2669: $returnhash{'domain'} = $cdomain;
2670: $returnhash{'num'} = $cnum;
2671: if (!defined($returnhash{'type'})) {
2672: $returnhash{'type'} = 'Course';
2673: }
2674: while (my ($name,$value) = each %returnhash) {
2675: $envhash{'course.'.$normalid.'.'.$name}=$value;
2676: }
2677: $returnhash{'url'}=&clutter($returnhash{'url'});
2678: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
2679: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
2680: $envhash{'course.'.$normalid.'.home'}=$chome;
2681: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2682: $envhash{'course.'.$normalid.'.num'}=$cnum;
2683: }
2684: }
2685: if (!$args->{'one_time'}) {
2686: &appenv(%envhash);
2687: }
2688: return %returnhash;
2689: }
2690:
2691: # -------------------------------------------------See if a user is privileged
2692:
2693: sub privileged {
2694: my ($username,$domain)=@_;
2695: my $rolesdump=&reply("dump:$domain:$username:roles",
2696: &homeserver($username,$domain));
2697: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2698: my $now=time;
2699: if ($rolesdump ne '') {
2700: foreach (split(/&/,$rolesdump)) {
2701: if ($_!~/^rolesdef_/) {
2702: my ($area,$role)=split(/=/,$_);
2703: $area=~s/\_\w\w$//;
2704: my ($trole,$tend,$tstart)=split(/_/,$role);
2705: if (($trole eq 'dc') || ($trole eq 'su')) {
2706: my $active=1;
2707: if ($tend) {
2708: if ($tend<$now) { $active=0; }
2709: }
2710: if ($tstart) {
2711: if ($tstart>$now) { $active=0; }
2712: }
2713: if ($active) { return 1; }
2714: }
2715: }
2716: }
2717: }
2718: return 0;
2719: }
2720:
2721: # -------------------------------------------------------- Get user privileges
2722:
2723: sub rolesinit {
2724: my ($domain,$username,$authhost)=@_;
2725: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
2726: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
2727: my %allroles=();
2728: my %allgroups=();
2729: my $now=time;
2730: my %userroles = ('user.login.time' => $now);
2731: my $group_privs;
2732:
2733: if ($rolesdump ne '') {
2734: foreach (split(/&/,$rolesdump)) {
2735: if ($_!~/^rolesdef_/) {
2736: my ($area,$role)=split(/=/,$_);
2737: $area=~s/\_\w\w$//;
2738: my ($trole,$tend,$tstart,$group_privs);
2739: if ($role=~/^cr/) {
2740: if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
2741: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
2742: ($tend,$tstart)=split('_',$trest);
2743: } else {
2744: $trole=$role;
2745: }
2746: } elsif ($role =~ m|^gr/|) {
2747: ($trole,$tend,$tstart) = split(/_/,$role);
2748: ($trole,$group_privs) = split(/\//,$trole);
2749: $group_privs = &unescape($group_privs);
2750: } else {
2751: ($trole,$tend,$tstart)=split(/_/,$role);
2752: }
2753: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2754: $username);
2755: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
2756: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2757: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
2758: if (($area ne '') && ($trole ne '')) {
2759: my $spec=$trole.'.'.$area;
2760: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2761: if ($trole =~ /^cr\//) {
2762: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
2763: } elsif ($trole eq 'gr') {
2764: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
2765: } else {
2766: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
2767: }
2768: }
2769: }
2770: }
2771: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2772: $userroles{'user.adv'} = $adv;
2773: $userroles{'user.author'} = $author;
2774: $env{'user.adv'}=$adv;
2775: }
2776: return \%userroles;
2777: }
2778:
2779: sub set_arearole {
2780: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2781: # log the associated role with the area
2782: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2783: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
2784: }
2785:
2786: sub custom_roleprivs {
2787: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2788: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2789: my $homsvr=homeserver($rauthor,$rdomain);
2790: if ($hostname{$homsvr} ne '') {
2791: my ($rdummy,$roledef)=
2792: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2793: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2794: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2795: if (defined($syspriv)) {
2796: $$allroles{'cm./'}.=':'.$syspriv;
2797: $$allroles{$spec.'./'}.=':'.$syspriv;
2798: }
2799: if ($tdomain ne '') {
2800: if (defined($dompriv)) {
2801: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2802: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2803: }
2804: if (($trest ne '') && (defined($coursepriv))) {
2805: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2806: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2807: }
2808: }
2809: }
2810: }
2811: }
2812:
2813: sub group_roleprivs {
2814: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
2815: my $access = 1;
2816: my $now = time;
2817: if (($tend!=0) && ($tend<$now)) { $access = 0; }
2818: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
2819: if ($access) {
2820: my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
2821: $$allgroups{$course}{$group} .=':'.$group_privs;
2822: }
2823: }
2824:
2825: sub standard_roleprivs {
2826: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2827: if (defined($pr{$trole.':s'})) {
2828: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2829: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2830: }
2831: if ($tdomain ne '') {
2832: if (defined($pr{$trole.':d'})) {
2833: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2834: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2835: }
2836: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2837: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2838: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2839: }
2840: }
2841: }
2842:
2843: sub set_userprivs {
2844: my ($userroles,$allroles,$allgroups) = @_;
2845: my $author=0;
2846: my $adv=0;
2847: my %grouproles = ();
2848: if (keys(%{$allgroups}) > 0) {
2849: foreach my $role (keys %{$allroles}) {
2850: my ($trole,$area,$sec,$extendedarea);
2851: if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
2852: $trole = $1;
2853: $area = $2;
2854: $sec = $3;
2855: $extendedarea = $area.$sec;
2856: if (exists($$allgroups{$area})) {
2857: foreach my $group (keys(%{$$allgroups{$area}})) {
2858: my $spec = $trole.'.'.$extendedarea;
2859: $grouproles{$spec.'.'.$area.'/'.$group} =
2860: $$allgroups{$area}{$group};
2861: }
2862: }
2863: }
2864: }
2865: }
2866: foreach (keys(%grouproles)) {
2867: $$allroles{$_} = $grouproles{$_};
2868: }
2869: foreach (keys %{$allroles}) {
2870: my %thesepriv=();
2871: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
2872: foreach (split(/:/,$$allroles{$_})) {
2873: if ($_ ne '') {
2874: my ($privilege,$restrictions)=split(/&/,$_);
2875: if ($restrictions eq '') {
2876: $thesepriv{$privilege}='F';
2877: } elsif ($thesepriv{$privilege} ne 'F') {
2878: $thesepriv{$privilege}.=$restrictions;
2879: }
2880: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2881: }
2882: }
2883: my $thesestr='';
2884: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
2885: $userroles->{'user.priv.'.$_} = $thesestr;
2886: }
2887: return ($author,$adv);
2888: }
2889:
2890: # --------------------------------------------------------------- get interface
2891:
2892: sub get {
2893: my ($namespace,$storearr,$udomain,$uname)=@_;
2894: my $items='';
2895: foreach (@$storearr) {
2896: $items.=escape($_).'&';
2897: }
2898: $items=~s/\&$//;
2899: if (!$udomain) { $udomain=$env{'user.domain'}; }
2900: if (!$uname) { $uname=$env{'user.name'}; }
2901: my $uhome=&homeserver($uname,$udomain);
2902:
2903: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
2904: my @pairs=split(/\&/,$rep);
2905: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2906: return @pairs;
2907: }
2908: my %returnhash=();
2909: my $i=0;
2910: foreach (@$storearr) {
2911: $returnhash{$_}=&thaw_unescape($pairs[$i]);
2912: $i++;
2913: }
2914: return %returnhash;
2915: }
2916:
2917: # --------------------------------------------------------------- del interface
2918:
2919: sub del {
2920: my ($namespace,$storearr,$udomain,$uname)=@_;
2921: my $items='';
2922: foreach (@$storearr) {
2923: $items.=escape($_).'&';
2924: }
2925: $items=~s/\&$//;
2926: if (!$udomain) { $udomain=$env{'user.domain'}; }
2927: if (!$uname) { $uname=$env{'user.name'}; }
2928: my $uhome=&homeserver($uname,$udomain);
2929:
2930: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
2931: }
2932:
2933: # -------------------------------------------------------------- dump interface
2934:
2935: sub dump {
2936: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2937: if (!$udomain) { $udomain=$env{'user.domain'}; }
2938: if (!$uname) { $uname=$env{'user.name'}; }
2939: my $uhome=&homeserver($uname,$udomain);
2940: if ($regexp) {
2941: $regexp=&escape($regexp);
2942: } else {
2943: $regexp='.';
2944: }
2945: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
2946: my @pairs=split(/\&/,$rep);
2947: my %returnhash=();
2948: foreach my $item (@pairs) {
2949: my ($key,$value)=split(/=/,$item,2);
2950: $key = &unescape($key);
2951: next if ($key =~ /^error: 2 /);
2952: $returnhash{$key}=&thaw_unescape($value);
2953: }
2954: return %returnhash;
2955: }
2956:
2957: # --------------------------------------------------------- dumpstore interface
2958:
2959: sub dumpstore {
2960: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2961: return &dump($namespace,$udomain,$uname,$regexp,$range);
2962: }
2963:
2964: # -------------------------------------------------------------- keys interface
2965:
2966: sub getkeys {
2967: my ($namespace,$udomain,$uname)=@_;
2968: if (!$udomain) { $udomain=$env{'user.domain'}; }
2969: if (!$uname) { $uname=$env{'user.name'}; }
2970: my $uhome=&homeserver($uname,$udomain);
2971: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2972: my @keyarray=();
2973: foreach (split(/\&/,$rep)) {
2974: push (@keyarray,&unescape($_));
2975: }
2976: return @keyarray;
2977: }
2978:
2979: # --------------------------------------------------------------- currentdump
2980: sub currentdump {
2981: my ($courseid,$sdom,$sname)=@_;
2982: $courseid = $env{'request.course.id'} if (! defined($courseid));
2983: $sdom = $env{'user.domain'} if (! defined($sdom));
2984: $sname = $env{'user.name'} if (! defined($sname));
2985: my $uhome = &homeserver($sname,$sdom);
2986: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
2987: return if ($rep =~ /^(error:|no_such_host)/);
2988: #
2989: my %returnhash=();
2990: #
2991: if ($rep eq "unknown_cmd") {
2992: # an old lond will not know currentdump
2993: # Do a dump and make it look like a currentdump
2994: my @tmp = &dump($courseid,$sdom,$sname,'.');
2995: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2996: my %hash = @tmp;
2997: @tmp=();
2998: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
2999: } else {
3000: my @pairs=split(/\&/,$rep);
3001: foreach (@pairs) {
3002: my ($key,$value)=split(/=/,$_);
3003: my ($symb,$param) = split(/:/,$key);
3004: $returnhash{&unescape($symb)}->{&unescape($param)} =
3005: &thaw_unescape($value);
3006: }
3007: }
3008: return %returnhash;
3009: }
3010:
3011: sub convert_dump_to_currentdump{
3012: my %hash = %{shift()};
3013: my %returnhash;
3014: # Code ripped from lond, essentially. The only difference
3015: # here is the unescaping done by lonnet::dump(). Conceivably
3016: # we might run in to problems with parameter names =~ /^v\./
3017: while (my ($key,$value) = each(%hash)) {
3018: my ($v,$symb,$param) = split(/:/,$key);
3019: next if ($v eq 'version' || $symb eq 'keys');
3020: next if (exists($returnhash{$symb}) &&
3021: exists($returnhash{$symb}->{$param}) &&
3022: $returnhash{$symb}->{'v.'.$param} > $v);
3023: $returnhash{$symb}->{$param}=$value;
3024: $returnhash{$symb}->{'v.'.$param}=$v;
3025: }
3026: #
3027: # Remove all of the keys in the hashes which keep track of
3028: # the version of the parameter.
3029: while (my ($symb,$param_hash) = each(%returnhash)) {
3030: # use a foreach because we are going to delete from the hash.
3031: foreach my $key (keys(%$param_hash)) {
3032: delete($param_hash->{$key}) if ($key =~ /^v\./);
3033: }
3034: }
3035: return \%returnhash;
3036: }
3037:
3038: # ------------------------------------------------------ critical inc interface
3039:
3040: sub cinc {
3041: return &inc(@_,'critical');
3042: }
3043:
3044: # --------------------------------------------------------------- inc interface
3045:
3046: sub inc {
3047: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3048: if (!$udomain) { $udomain=$env{'user.domain'}; }
3049: if (!$uname) { $uname=$env{'user.name'}; }
3050: my $uhome=&homeserver($uname,$udomain);
3051: my $items='';
3052: if (! ref($store)) {
3053: # got a single value, so use that instead
3054: $items = &escape($store).'=&';
3055: } elsif (ref($store) eq 'SCALAR') {
3056: $items = &escape($$store).'=&';
3057: } elsif (ref($store) eq 'ARRAY') {
3058: $items = join('=&',map {&escape($_);} @{$store});
3059: } elsif (ref($store) eq 'HASH') {
3060: while (my($key,$value) = each(%{$store})) {
3061: $items.= &escape($key).'='.&escape($value).'&';
3062: }
3063: }
3064: $items=~s/\&$//;
3065: if ($critical) {
3066: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3067: } else {
3068: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3069: }
3070: }
3071:
3072: # --------------------------------------------------------------- put interface
3073:
3074: sub put {
3075: my ($namespace,$storehash,$udomain,$uname)=@_;
3076: if (!$udomain) { $udomain=$env{'user.domain'}; }
3077: if (!$uname) { $uname=$env{'user.name'}; }
3078: my $uhome=&homeserver($uname,$udomain);
3079: my $items='';
3080: foreach (keys %$storehash) {
3081: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
3082: }
3083: $items=~s/\&$//;
3084: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3085: }
3086:
3087: # ------------------------------------------------------------ newput interface
3088:
3089: sub newput {
3090: my ($namespace,$storehash,$udomain,$uname)=@_;
3091: if (!$udomain) { $udomain=$env{'user.domain'}; }
3092: if (!$uname) { $uname=$env{'user.name'}; }
3093: my $uhome=&homeserver($uname,$udomain);
3094: my $items='';
3095: foreach my $key (keys(%$storehash)) {
3096: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3097: }
3098: $items=~s/\&$//;
3099: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3100: }
3101:
3102: # --------------------------------------------------------- putstore interface
3103:
3104: sub putstore {
3105: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3106: if (!$udomain) { $udomain=$env{'user.domain'}; }
3107: if (!$uname) { $uname=$env{'user.name'}; }
3108: my $uhome=&homeserver($uname,$udomain);
3109: my $items='';
3110: foreach my $key (keys(%$storehash)) {
3111: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
3112: }
3113: $items=~s/\&$//;
3114: my $esc_symb=&escape($symb);
3115: my $esc_v=&escape($version);
3116: my $reply =
3117: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
3118: $uhome);
3119: if ($reply eq 'unknown_cmd') {
3120: # gfall back to way things use to be done
3121: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3122: $uname);
3123: }
3124: return $reply;
3125: }
3126:
3127: sub old_putstore {
3128: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3129: if (!$udomain) { $udomain=$env{'user.domain'}; }
3130: if (!$uname) { $uname=$env{'user.name'}; }
3131: my $uhome=&homeserver($uname,$udomain);
3132: my %newstorehash;
3133: foreach (keys %$storehash) {
3134: my $key = $version.':'.&escape($symb).':'.$_;
3135: $newstorehash{$key} = $storehash->{$_};
3136: }
3137: my $items='';
3138: my %allitems = ();
3139: foreach (keys %newstorehash) {
3140: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3141: my $key = $1.':keys:'.$2;
3142: $allitems{$key} .= $3.':';
3143: }
3144: $items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
3145: }
3146: foreach (keys %allitems) {
3147: $allitems{$_} =~ s/\:$//;
3148: $items.= $_.'='.$allitems{$_}.'&';
3149: }
3150: $items=~s/\&$//;
3151: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3152: }
3153:
3154: # ------------------------------------------------------ critical put interface
3155:
3156: sub cput {
3157: my ($namespace,$storehash,$udomain,$uname)=@_;
3158: if (!$udomain) { $udomain=$env{'user.domain'}; }
3159: if (!$uname) { $uname=$env{'user.name'}; }
3160: my $uhome=&homeserver($uname,$udomain);
3161: my $items='';
3162: foreach (keys %$storehash) {
3163: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
3164: }
3165: $items=~s/\&$//;
3166: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
3167: }
3168:
3169: # -------------------------------------------------------------- eget interface
3170:
3171: sub eget {
3172: my ($namespace,$storearr,$udomain,$uname)=@_;
3173: my $items='';
3174: foreach (@$storearr) {
3175: $items.=escape($_).'&';
3176: }
3177: $items=~s/\&$//;
3178: if (!$udomain) { $udomain=$env{'user.domain'}; }
3179: if (!$uname) { $uname=$env{'user.name'}; }
3180: my $uhome=&homeserver($uname,$udomain);
3181: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
3182: my @pairs=split(/\&/,$rep);
3183: my %returnhash=();
3184: my $i=0;
3185: foreach (@$storearr) {
3186: $returnhash{$_}=&thaw_unescape($pairs[$i]);
3187: $i++;
3188: }
3189: return %returnhash;
3190: }
3191:
3192: # ------------------------------------------------------------ tmpput interface
3193: sub tmpput {
3194: my ($storehash,$server)=@_;
3195: my $items='';
3196: foreach (keys(%$storehash)) {
3197: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
3198: }
3199: $items=~s/\&$//;
3200: return &reply("tmpput:$items",$server);
3201: }
3202:
3203: # ------------------------------------------------------------ tmpget interface
3204: sub tmpget {
3205: my ($token,$server)=@_;
3206: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3207: my $rep=&reply("tmpget:$token",$server);
3208: my %returnhash;
3209: foreach my $item (split(/\&/,$rep)) {
3210: my ($key,$value)=split(/=/,$item);
3211: $returnhash{&unescape($key)}=&thaw_unescape($value);
3212: }
3213: return %returnhash;
3214: }
3215:
3216: # ------------------------------------------------------------ tmpget interface
3217: sub tmpdel {
3218: my ($token,$server)=@_;
3219: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3220: return &reply("tmpdel:$token",$server);
3221: }
3222:
3223: # ---------------------------------------------- Custom access rule evaluation
3224:
3225: sub customaccess {
3226: my ($priv,$uri)=@_;
3227: my ($urole,$urealm)=split(/\./,$env{'request.role'});
3228: $urealm=~s/^\W//;
3229: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
3230: my $access=0;
3231: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3232: my ($effect,$realm,$role)=split(/\:/,$_);
3233: if ($role) {
3234: if ($role ne $urole) { next; }
3235: }
3236: foreach (split(/\s*\,\s*/,$realm)) {
3237: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
3238: if ($tdom) {
3239: if ($tdom ne $udom) { next; }
3240: }
3241: if ($tcrs) {
3242: if ($tcrs ne $ucrs) { next; }
3243: }
3244: if ($tsec) {
3245: if ($tsec ne $usec) { next; }
3246: }
3247: $access=($effect eq 'allow');
3248: last;
3249: }
3250: if ($realm eq '' && $role eq '') {
3251: $access=($effect eq 'allow');
3252: }
3253: }
3254: return $access;
3255: }
3256:
3257: # ------------------------------------------------- Check for a user privilege
3258:
3259: sub allowed {
3260: my ($priv,$uri,$symb)=@_;
3261: my $ver_orguri=$uri;
3262: $uri=&deversion($uri);
3263: my $orguri=$uri;
3264: $uri=&declutter($uri);
3265:
3266: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
3267: # Free bre access to adm and meta resources
3268: if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|))
3269: || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
3270: return 'F';
3271: }
3272:
3273: # Free bre access to user's own portfolio contents
3274: my ($space,$domain,$name,@dir)=split('/',$uri);
3275: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
3276: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
3277: return 'F';
3278: }
3279:
3280: # bre access to group if user has rgf priv for this group and course.
3281: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3282: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3283: if (exists($env{'request.course.id'})) {
3284: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3285: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3286: if (($domain eq $cdom) && ($name eq $cnum)) {
3287: my $courseprivid=$env{'request.course.id'};
3288: $courseprivid=~s/\_/\//;
3289: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3290: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3291: return $1;
3292: }
3293: }
3294: }
3295: }
3296:
3297: # Free bre to public access
3298:
3299: if ($priv eq 'bre') {
3300: my $copyright=&metadata($uri,'copyright');
3301: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
3302: return 'F';
3303: }
3304: if ($copyright eq 'priv') {
3305: $uri=~/([^\/]+)\/([^\/]+)\//;
3306: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
3307: return '';
3308: }
3309: }
3310: if ($copyright eq 'domain') {
3311: $uri=~/([^\/]+)\/([^\/]+)\//;
3312: unless (($env{'user.domain'} eq $1) ||
3313: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
3314: return '';
3315: }
3316: }
3317: if ($env{'request.role'}=~ /li\.\//) {
3318: # Library role, so allow browsing of resources in this domain.
3319: return 'F';
3320: }
3321: if ($copyright eq 'custom') {
3322: unless (&customaccess($priv,$uri)) { return ''; }
3323: }
3324: }
3325: # Domain coordinator is trying to create a course
3326: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
3327: # uri is the requested domain in this case.
3328: # comparison to 'request.role.domain' shows if the user has selected
3329: # a role of dc for the domain in question.
3330: return 'F' if ($uri eq $env{'request.role.domain'});
3331: }
3332:
3333: my $thisallowed='';
3334: my $statecond=0;
3335: my $courseprivid='';
3336:
3337: # Course
3338:
3339: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
3340: $thisallowed.=$1;
3341: }
3342:
3343: # Domain
3344:
3345: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
3346: =~/\Q$priv\E\&([^\:]*)/) {
3347: $thisallowed.=$1;
3348: }
3349:
3350: # Course: uri itself is a course
3351: my $courseuri=$uri;
3352: $courseuri=~s/\_(\d)/\/$1/;
3353: $courseuri=~s/^([^\/])/\/$1/;
3354:
3355: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
3356: =~/\Q$priv\E\&([^\:]*)/) {
3357: $thisallowed.=$1;
3358: }
3359:
3360: # Group: uri itself is a group
3361: my $groupuri=$uri;
3362: $groupuri=~s/^([^\/])/\/$1/;
3363: if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
3364: =~/\Q$priv\E\&([^\:]*)/) {
3365: $thisallowed.=$1;
3366: }
3367:
3368: # URI is an uploaded document for this course, default permissions don't matter
3369: # not allowing 'edit' access (editupload) to uploaded course docs
3370: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
3371: $thisallowed='';
3372: my ($match)=&is_on_map($uri);
3373: if ($match) {
3374: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3375: =~/\Q$priv\E\&([^\:]*)/) {
3376: $thisallowed.=$1;
3377: }
3378: } else {
3379: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
3380: if ($refuri) {
3381: if ($refuri =~ m|^/adm/|) {
3382: $thisallowed='F';
3383: } else {
3384: $refuri=&declutter($refuri);
3385: my ($match) = &is_on_map($refuri);
3386: if ($match) {
3387: $thisallowed='F';
3388: }
3389: }
3390: }
3391: }
3392: }
3393:
3394: # Full access at system, domain or course-wide level? Exit.
3395:
3396: if ($thisallowed=~/F/) {
3397: return 'F';
3398: }
3399:
3400: # If this is generating or modifying users, exit with special codes
3401:
3402: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3403: if (($priv eq 'cca') || ($priv eq 'caa')) {
3404: my ($audom,$auname)=split('/',$uri);
3405: # no author name given, so this just checks on the general right to make a co-author in this domain
3406: unless ($auname) { return $thisallowed; }
3407: # an author name is given, so we are about to actually make a co-author for a certain account
3408: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3409: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3410: ($audom ne $env{'request.role.domain'}))) { return ''; }
3411: }
3412: return $thisallowed;
3413: }
3414: #
3415: # Gathered so far: system, domain and course wide privileges
3416: #
3417: # Course: See if uri or referer is an individual resource that is part of
3418: # the course
3419:
3420: if ($env{'request.course.id'}) {
3421:
3422: $courseprivid=$env{'request.course.id'};
3423: if ($env{'request.course.sec'}) {
3424: $courseprivid.='/'.$env{'request.course.sec'};
3425: }
3426: $courseprivid=~s/\_/\//;
3427: my $checkreferer=1;
3428: my ($match,$cond)=&is_on_map($uri);
3429: if ($match) {
3430: $statecond=$cond;
3431: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3432: =~/\Q$priv\E\&([^\:]*)/) {
3433: $thisallowed.=$1;
3434: $checkreferer=0;
3435: }
3436: }
3437:
3438: if ($checkreferer) {
3439: my $refuri=$env{'httpref.'.$orguri};
3440: unless ($refuri) {
3441: foreach (keys %env) {
3442: if ($_=~/^httpref\..*\*/) {
3443: my $pattern=$_;
3444: $pattern=~s/^httpref\.\/res\///;
3445: $pattern=~s/\*/\[\^\/\]\+/g;
3446: $pattern=~s/\//\\\//g;
3447: if ($orguri=~/$pattern/) {
3448: $refuri=$env{$_};
3449: }
3450: }
3451: }
3452: }
3453:
3454: if ($refuri) {
3455: $refuri=&declutter($refuri);
3456: my ($match,$cond)=&is_on_map($refuri);
3457: if ($match) {
3458: my $refstatecond=$cond;
3459: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
3460: =~/\Q$priv\E\&([^\:]*)/) {
3461: $thisallowed.=$1;
3462: $uri=$refuri;
3463: $statecond=$refstatecond;
3464: }
3465: }
3466: }
3467: }
3468: }
3469:
3470: #
3471: # Gathered now: all privileges that could apply, and condition number
3472: #
3473: #
3474: # Full or no access?
3475: #
3476:
3477: if ($thisallowed=~/F/) {
3478: return 'F';
3479: }
3480:
3481: unless ($thisallowed) {
3482: return '';
3483: }
3484:
3485: # Restrictions exist, deal with them
3486: #
3487: # C:according to course preferences
3488: # R:according to resource settings
3489: # L:unless locked
3490: # X:according to user session state
3491: #
3492:
3493: # Possibly locked functionality, check all courses
3494: # Locks might take effect only after 10 minutes cache expiration for other
3495: # courses, and 2 minutes for current course
3496:
3497: my $envkey;
3498: if ($thisallowed=~/L/) {
3499: foreach $envkey (keys %env) {
3500: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3501: my $courseid=$2;
3502: my $roleid=$1.'.'.$2;
3503: $courseid=~s/^\///;
3504: my $expiretime=600;
3505: if ($env{'request.role'} eq $roleid) {
3506: $expiretime=120;
3507: }
3508: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3509: my $prefix='course.'.$cdom.'_'.$cnum.'.';
3510: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
3511: &coursedescription($courseid,{'freshen_cache' => 1});
3512: }
3513: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3514: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3515: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3516: &log($env{'user.domain'},$env{'user.name'},
3517: $env{'user.home'},
3518: 'Locked by res: '.$priv.' for '.$uri.' due to '.
3519: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3520: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3521: return '';
3522: }
3523: }
3524: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3525: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3526: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3527: &log($env{'user.domain'},$env{'user.name'},
3528: $env{'user.home'},
3529: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
3530: $cdom.'/'.$cnum.'/'.$csec.' expire '.
3531: $env{$prefix.'priv.'.$priv.'.lock.expire'});
3532: return '';
3533: }
3534: }
3535: }
3536: }
3537: }
3538:
3539: #
3540: # Rest of the restrictions depend on selected course
3541: #
3542:
3543: unless ($env{'request.course.id'}) {
3544: return '1';
3545: }
3546:
3547: #
3548: # Now user is definitely in a course
3549: #
3550:
3551:
3552: # Course preferences
3553:
3554: if ($thisallowed=~/C/) {
3555: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3556: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3557: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
3558: =~/\Q$rolecode\E/) {
3559: if ($priv ne 'pch') {
3560: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3561: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3562: $env{'request.course.id'});
3563: }
3564: return '';
3565: }
3566:
3567: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
3568: =~/\Q$unamedom\E/) {
3569: if ($priv ne 'pch') {
3570: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3571: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3572: $env{'request.course.id'});
3573: }
3574: return '';
3575: }
3576: }
3577:
3578: # Resource preferences
3579:
3580: if ($thisallowed=~/R/) {
3581: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3582: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
3583: if ($priv ne 'pch') {
3584: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3585: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3586: }
3587: return '';
3588: }
3589: }
3590:
3591: # Restricted by state or randomout?
3592:
3593: if ($thisallowed=~/X/) {
3594: if ($env{'acc.randomout'}) {
3595: if (!$symb) { $symb=&symbread($uri,1); }
3596: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
3597: return '';
3598: }
3599: }
3600: if (&condval($statecond)) {
3601: return '2';
3602: } else {
3603: return '';
3604: }
3605: }
3606:
3607: return 'F';
3608: }
3609:
3610: sub split_uri_for_cond {
3611: my $uri=&deversion(&declutter(shift));
3612: my @uriparts=split(/\//,$uri);
3613: my $filename=pop(@uriparts);
3614: my $pathname=join('/',@uriparts);
3615: return ($pathname,$filename);
3616: }
3617: # --------------------------------------------------- Is a resource on the map?
3618:
3619: sub is_on_map {
3620: my ($pathname,$filename) = &split_uri_for_cond(shift);
3621: #Trying to find the conditional for the file
3622: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
3623: /\&\Q$filename\E\:([\d\|]+)\&/);
3624: if ($match) {
3625: return (1,$1);
3626: } else {
3627: return (0,0);
3628: }
3629: }
3630:
3631: # --------------------------------------------------------- Get symb from alias
3632:
3633: sub get_symb_from_alias {
3634: my $symb=shift;
3635: my ($map,$resid,$url)=&decode_symb($symb);
3636: # Already is a symb
3637: if ($url) { return $symb; }
3638: # Must be an alias
3639: my $aliassymb='';
3640: my %bighash;
3641: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
3642: &GDBM_READER(),0640)) {
3643: my $rid=$bighash{'mapalias_'.$symb};
3644: if ($rid) {
3645: my ($mapid,$resid)=split(/\./,$rid);
3646: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3647: $resid,$bighash{'src_'.$rid});
3648: }
3649: untie %bighash;
3650: }
3651: return $aliassymb;
3652: }
3653:
3654: # ----------------------------------------------------------------- Define Role
3655:
3656: sub definerole {
3657: if (allowed('mcr','/')) {
3658: my ($rolename,$sysrole,$domrole,$courole)=@_;
3659: foreach (split(':',$sysrole)) {
3660: my ($crole,$cqual)=split(/\&/,$_);
3661: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3662: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3663: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
3664: return "refused:s:$crole&$cqual";
3665: }
3666: }
3667: }
3668: foreach (split(':',$domrole)) {
3669: my ($crole,$cqual)=split(/\&/,$_);
3670: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3671: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3672: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
3673: return "refused:d:$crole&$cqual";
3674: }
3675: }
3676: }
3677: foreach (split(':',$courole)) {
3678: my ($crole,$cqual)=split(/\&/,$_);
3679: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3680: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3681: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
3682: return "refused:c:$crole&$cqual";
3683: }
3684: }
3685: }
3686: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3687: "$env{'user.domain'}:$env{'user.name'}:".
3688: "rolesdef_$rolename=".
3689: escape($sysrole.'_'.$domrole.'_'.$courole);
3690: return reply($command,$env{'user.home'});
3691: } else {
3692: return 'refused';
3693: }
3694: }
3695:
3696: # ---------------- Make a metadata query against the network of library servers
3697:
3698: sub metadata_query {
3699: my ($query,$custom,$customshow,$server_array)=@_;
3700: my %rhash;
3701: my @server_list = (defined($server_array) ? @$server_array
3702: : keys(%libserv) );
3703: for my $server (@server_list) {
3704: unless ($custom or $customshow) {
3705: my $reply=&reply("querysend:".&escape($query),$server);
3706: $rhash{$server}=$reply;
3707: }
3708: else {
3709: my $reply=&reply("querysend:".&escape($query).':'.
3710: &escape($custom).':'.&escape($customshow),
3711: $server);
3712: $rhash{$server}=$reply;
3713: }
3714: }
3715: return \%rhash;
3716: }
3717:
3718: # ----------------------------------------- Send log queries and wait for reply
3719:
3720: sub log_query {
3721: my ($uname,$udom,$query,%filters)=@_;
3722: my $uhome=&homeserver($uname,$udom);
3723: if ($uhome eq 'no_host') { return 'error: no_host'; }
3724: my $uhost=$hostname{$uhome};
3725: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
3726: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3727: $uhome);
3728: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
3729: return get_query_reply($queryid);
3730: }
3731:
3732: # ------- Request retrieval of institutional classlists for course(s)
3733:
3734: sub fetch_enrollment_query {
3735: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
3736: my $homeserver;
3737: my $maxtries = 1;
3738: if ($context eq 'automated') {
3739: $homeserver = $perlvar{'lonHostID'};
3740: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
3741: } else {
3742: $homeserver = &homeserver($cnum,$dom);
3743: }
3744: my $host=$hostname{$homeserver};
3745: my $cmd = '';
3746: foreach (keys %{$affiliatesref}) {
3747: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
3748: }
3749: $cmd =~ s/%%$//;
3750: $cmd = &escape($cmd);
3751: my $query = 'fetchenrollment';
3752: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
3753: unless ($queryid=~/^\Q$host\E\_/) {
3754: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
3755: return 'error: '.$queryid;
3756: }
3757: my $reply = &get_query_reply($queryid);
3758: my $tries = 1;
3759: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3760: $reply = &get_query_reply($queryid);
3761: $tries ++;
3762: }
3763: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
3764: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
3765: } else {
3766: my @responses = split/:/,$reply;
3767: if ($homeserver eq $perlvar{'lonHostID'}) {
3768: foreach (@responses) {
3769: my ($key,$value) = split/=/,$_;
3770: $$replyref{$key} = $value;
3771: }
3772: } else {
3773: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3774: foreach (@responses) {
3775: my ($key,$value) = split/=/,$_;
3776: $$replyref{$key} = $value;
3777: if ($value > 0) {
3778: foreach (@{$$affiliatesref{$key}}) {
3779: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
3780: my $destname = $pathname.'/'.$filename;
3781: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
3782: if ($xml_classlist =~ /^error/) {
3783: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
3784: } else {
3785: if ( open(FILE,">$destname") ) {
3786: print FILE &unescape($xml_classlist);
3787: close(FILE);
3788: } else {
3789: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
3790: }
3791: }
3792: }
3793: }
3794: }
3795: }
3796: return 'ok';
3797: }
3798: return 'error';
3799: }
3800:
3801: sub get_query_reply {
3802: my $queryid=shift;
3803: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
3804: my $reply='';
3805: for (1..100) {
3806: sleep 2;
3807: if (-e $replyfile.'.end') {
3808: if (open(my $fh,$replyfile)) {
3809: $reply.=<$fh>;
3810: close($fh);
3811: } else { return 'error: reply_file_error'; }
3812: return &unescape($reply);
3813: }
3814: }
3815: return 'timeout:'.$queryid;
3816: }
3817:
3818: sub courselog_query {
3819: #
3820: # possible filters:
3821: # url: url or symb
3822: # username
3823: # domain
3824: # action: view, submit, grade
3825: # start: timestamp
3826: # end: timestamp
3827: #
3828: my (%filters)=@_;
3829: unless ($env{'request.course.id'}) { return 'no_course'; }
3830: if ($filters{'url'}) {
3831: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
3832: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
3833: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
3834: }
3835: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
3836: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3837: return &log_query($cname,$cdom,'courselog',%filters);
3838: }
3839:
3840: sub userlog_query {
3841: my ($uname,$udom,%filters)=@_;
3842: return &log_query($uname,$udom,'userlog',%filters);
3843: }
3844:
3845: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
3846:
3847: sub auto_run {
3848: my ($cnum,$cdom) = @_;
3849: my $homeserver = &homeserver($cnum,$cdom);
3850: my $response = &reply('autorun:'.$cdom,$homeserver);
3851: return $response;
3852: }
3853:
3854: sub auto_get_sections {
3855: my ($cnum,$cdom,$inst_coursecode) = @_;
3856: my $homeserver = &homeserver($cnum,$cdom);
3857: my @secs = ();
3858: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
3859: unless ($response eq 'refused') {
3860: @secs = split/:/,$response;
3861: }
3862: return @secs;
3863: }
3864:
3865: sub auto_new_course {
3866: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
3867: my $homeserver = &homeserver($cnum,$cdom);
3868: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
3869: return $response;
3870: }
3871:
3872: sub auto_validate_courseID {
3873: my ($cnum,$cdom,$inst_course_id) = @_;
3874: my $homeserver = &homeserver($cnum,$cdom);
3875: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
3876: return $response;
3877: }
3878:
3879: sub auto_create_password {
3880: my ($cnum,$cdom,$authparam) = @_;
3881: my $homeserver = &homeserver($cnum,$cdom);
3882: my $create_passwd = 0;
3883: my $authchk = '';
3884: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
3885: if ($response eq 'refused') {
3886: $authchk = 'refused';
3887: } else {
3888: ($authparam,$create_passwd,$authchk) = split/:/,$response;
3889: }
3890: return ($authparam,$create_passwd,$authchk);
3891: }
3892:
3893: sub auto_photo_permission {
3894: my ($cnum,$cdom,$students) = @_;
3895: my $homeserver = &homeserver($cnum,$cdom);
3896: my ($outcome,$perm_reqd,$conditions) =
3897: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
3898: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
3899: return (undef,undef);
3900: }
3901: return ($outcome,$perm_reqd,$conditions);
3902: }
3903:
3904: sub auto_checkphotos {
3905: my ($uname,$udom,$pid) = @_;
3906: my $homeserver = &homeserver($uname,$udom);
3907: my ($result,$resulttype);
3908: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
3909: &escape($uname).':'.&escape($pid),
3910: $homeserver));
3911: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
3912: return (undef,undef);
3913: }
3914: if ($outcome) {
3915: ($result,$resulttype) = split(/:/,$outcome);
3916: }
3917: return ($result,$resulttype);
3918: }
3919:
3920: sub auto_photochoice {
3921: my ($cnum,$cdom) = @_;
3922: my $homeserver = &homeserver($cnum,$cdom);
3923: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
3924: &escape($cdom),
3925: $homeserver)));
3926: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
3927: return (undef,undef);
3928: }
3929: return ($update,$comment);
3930: }
3931:
3932: sub auto_photoupdate {
3933: my ($affiliatesref,$dom,$cnum,$photo) = @_;
3934: my $homeserver = &homeserver($cnum,$dom);
3935: my $host=$hostname{$homeserver};
3936: my $cmd = '';
3937: my $maxtries = 1;
3938: foreach (keys %{$affiliatesref}) {
3939: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
3940: }
3941: $cmd =~ s/%%$//;
3942: $cmd = &escape($cmd);
3943: my $query = 'institutionalphotos';
3944: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
3945: unless ($queryid=~/^\Q$host\E\_/) {
3946: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
3947: return 'error: '.$queryid;
3948: }
3949: my $reply = &get_query_reply($queryid);
3950: my $tries = 1;
3951: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3952: $reply = &get_query_reply($queryid);
3953: $tries ++;
3954: }
3955: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
3956: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
3957: } else {
3958: my @responses = split(/:/,$reply);
3959: my $outcome = shift(@responses);
3960: foreach my $item (@responses) {
3961: my ($key,$value) = split(/=/,$item);
3962: $$photo{$key} = $value;
3963: }
3964: return $outcome;
3965: }
3966: return 'error';
3967: }
3968:
3969: sub auto_instcode_format {
3970: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
3971: my $courses = '';
3972: my $homeserver;
3973: if ($caller eq 'global') {
3974: foreach my $tryserver (keys %libserv) {
3975: if ($hostdom{$tryserver} eq $codedom) {
3976: $homeserver = $tryserver;
3977: last;
3978: }
3979: }
3980: if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
3981: $homeserver = &homeserver($env{'user.name'},$codedom);
3982: }
3983: } else {
3984: $homeserver = &homeserver($caller,$codedom);
3985: }
3986: foreach (keys %{$instcodes}) {
3987: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
3988: }
3989: chop($courses);
3990: my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
3991: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
3992: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
3993: %{$codes} = &str2hash($codes_str);
3994: @{$codetitles} = &str2array($codetitles_str);
3995: %{$cat_titles} = &str2hash($cat_titles_str);
3996: %{$cat_order} = &str2hash($cat_order_str);
3997: return 'ok';
3998: }
3999: return $response;
4000: }
4001:
4002: # ------------------------------------------------------- Course Group routines
4003:
4004: sub get_coursegroups {
4005: my ($cdom,$cnum,$group) = @_;
4006: return(&dump('coursegroups',$cdom,$cnum,$group));
4007: }
4008:
4009: sub modify_coursegroup {
4010: my ($cdom,$cnum,$groupsettings) = @_;
4011: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4012: }
4013:
4014: sub modify_group_roles {
4015: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4016: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4017: my $role = 'gr/'.&escape($userprivs);
4018: my ($uname,$udom) = split(/:/,$user);
4019: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
4020: if ($result eq 'ok') {
4021: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4022: }
4023: return $result;
4024: }
4025:
4026: sub modify_coursegroup_membership {
4027: my ($cdom,$cnum,$membership) = @_;
4028: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4029: return $result;
4030: }
4031:
4032: sub get_active_groups {
4033: my ($udom,$uname,$cdom,$cnum) = @_;
4034: my $now = time;
4035: my %groups = ();
4036: foreach my $key (keys(%env)) {
4037: if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
4038: my ($start,$end) = split(/\./,$env{$key});
4039: if (($end!=0) && ($end<$now)) { next; }
4040: if (($start!=0) && ($start>$now)) { next; }
4041: if ($1 eq $cdom && $2 eq $cnum) {
4042: $groups{$3} = $env{$key} ;
4043: }
4044: }
4045: }
4046: return %groups;
4047: }
4048:
4049: sub get_group_membership {
4050: my ($cdom,$cnum,$group) = @_;
4051: return(&dump('groupmembership',$cdom,$cnum,$group));
4052: }
4053:
4054: sub get_users_groups {
4055: my ($udom,$uname,$courseid) = @_;
4056: my @usersgroups;
4057: my $cachetime=1800;
4058: $courseid=~s/\_/\//g;
4059: $courseid=~s/^(\w)/\/$1/;
4060:
4061: my $hashid="$udom:$uname:$courseid";
4062: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4063: if (defined($cached)) {
4064: @usersgroups = split(/:/,$grouplist);
4065: } else {
4066: $grouplist = '';
4067: my %roleshash = &dump('roles',$udom,$uname,$courseid);
4068: my ($tmp) = keys(%roleshash);
4069: if ($tmp=~/^error:/) {
4070: &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
4071: } else {
4072: my $access_end = $env{'course.'.$courseid.
4073: '.default_enrollment_end_date'};
4074: my $now = time;
4075: foreach my $key (keys(%roleshash)) {
4076: if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
4077: my $group = $1;
4078: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4079: my $start = $2;
4080: my $end = $1;
4081: if ($start == -1) { next; } # deleted from group
4082: if (($start!=0) && ($start>$now)) { next; }
4083: if (($end!=0) && ($end<$now)) {
4084: if ($access_end && $access_end < $now) {
4085: if ($access_end - $end < 86400) {
4086: push(@usersgroups,$group);
4087: }
4088: }
4089: next;
4090: }
4091: push(@usersgroups,$group);
4092: }
4093: }
4094: }
4095: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4096: $grouplist = join(':',@usersgroups);
4097: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
4098: }
4099: }
4100: return @usersgroups;
4101: }
4102:
4103: sub devalidate_getgroups_cache {
4104: my ($udom,$uname,$cdom,$cnum)=@_;
4105: my $courseid = $cdom.'_'.$cnum;
4106: $courseid=~s/\_/\//g;
4107: $courseid=~s/^(\w)/\/$1/;
4108: my $hashid="$udom:$uname:$courseid";
4109: &devalidate_cache_new('getgroups',$hashid);
4110: }
4111:
4112: # ------------------------------------------------------------------ Plain Text
4113:
4114: sub plaintext {
4115: my ($short,$type,$cid) = @_;
4116: if (!defined($cid)) {
4117: $cid = $env{'request.course.id'};
4118: }
4119: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4120: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4121: '.plaintext'});
4122: }
4123: my %rolenames = (
4124: Course => 'std',
4125: Group => 'alt1',
4126: );
4127: if (defined($type) &&
4128: defined($rolenames{$type}) &&
4129: defined($prp{$short}{$rolenames{$type}})) {
4130: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4131: } else {
4132: return &Apache::lonlocal::mt($prp{$short}{'std'});
4133: }
4134: }
4135:
4136: # ----------------------------------------------------------------- Assign Role
4137:
4138: sub assignrole {
4139: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
4140: my $mrole;
4141: if ($role =~ /^cr\//) {
4142: my $cwosec=$url;
4143: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4144: unless (&allowed('ccr',$cwosec)) {
4145: &logthis('Refused custom assignrole: '.
4146: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4147: $env{'user.name'}.' at '.$env{'user.domain'});
4148: return 'refused';
4149: }
4150: $mrole='cr';
4151: } elsif ($role =~ /^gr\//) {
4152: my $cwogrp=$url;
4153: $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4154: unless (&allowed('mdg',$cwogrp)) {
4155: &logthis('Refused group assignrole: '.
4156: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4157: $env{'user.name'}.' at '.$env{'user.domain'});
4158: return 'refused';
4159: }
4160: $mrole='gr';
4161: } else {
4162: my $cwosec=$url;
4163: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4164: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
4165: &logthis('Refused assignrole: '.
4166: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4167: $env{'user.name'}.' at '.$env{'user.domain'});
4168: return 'refused';
4169: }
4170: $mrole=$role;
4171: }
4172: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4173: "$udom:$uname:$url".'_'."$mrole=$role";
4174: if ($end) { $command.='_'.$end; }
4175: if ($start) {
4176: if ($end) {
4177: $command.='_'.$start;
4178: } else {
4179: $command.='_0_'.$start;
4180: }
4181: }
4182: my $origstart = $start;
4183: my $origend = $end;
4184: # actually delete
4185: if ($deleteflag) {
4186: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
4187: # modify command to delete the role
4188: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
4189: "$udom:$uname:$url".'_'."$mrole";
4190: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
4191: # set start and finish to negative values for userrolelog
4192: $start=-1;
4193: $end=-1;
4194: }
4195: }
4196: # send command
4197: my $answer=&reply($command,&homeserver($uname,$udom));
4198: # log new user role if status is ok
4199: if ($answer eq 'ok') {
4200: &userrolelog($role,$uname,$udom,$url,$start,$end);
4201: # for course roles, perform group memberships changes triggered by role change.
4202: unless ($role =~ /^gr/) {
4203: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4204: $origstart);
4205: }
4206: }
4207: return $answer;
4208: }
4209:
4210: # -------------------------------------------------- Modify user authentication
4211: # Overrides without validation
4212:
4213: sub modifyuserauth {
4214: my ($udom,$uname,$umode,$upass)=@_;
4215: my $uhome=&homeserver($uname,$udom);
4216: unless (&allowed('mau',$udom)) { return 'refused'; }
4217: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
4218: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4219: ' in domain '.$env{'request.role.domain'});
4220: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4221: &escape($upass),$uhome);
4222: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
4223: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4224: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4225: &log($udom,,$uname,$uhome,
4226: 'Authentication changed by '.$env{'user.domain'}.', '.
4227: $env{'user.name'}.', '.$umode.
4228: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4229: unless ($reply eq 'ok') {
4230: &logthis('Authentication mode error: '.$reply);
4231: return 'error: '.$reply;
4232: }
4233: return 'ok';
4234: }
4235:
4236: # --------------------------------------------------------------- Modify a user
4237:
4238: sub modifyuser {
4239: my ($udom, $uname, $uid,
4240: $umode, $upass, $first,
4241: $middle, $last, $gene,
4242: $forceid, $desiredhome, $email)=@_;
4243: $udom=~s/\W//g;
4244: $uname=~s/\W//g;
4245: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
4246: $umode.', '.$first.', '.$middle.', '.
4247: $last.', '.$gene.'(forceid: '.$forceid.')'.
4248: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4249: ' desiredhome not specified').
4250: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4251: ' in domain '.$env{'request.role.domain'});
4252: my $uhome=&homeserver($uname,$udom,'true');
4253: # ----------------------------------------------------------------- Create User
4254: if (($uhome eq 'no_host') &&
4255: (($umode && $upass) || ($umode eq 'localauth'))) {
4256: my $unhome='';
4257: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
4258: $unhome = $desiredhome;
4259: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4260: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
4261: } else { # load balancing routine for determining $unhome
4262: my $tryserver;
4263: my $loadm=10000000;
4264: foreach $tryserver (keys %libserv) {
4265: if ($hostdom{$tryserver} eq $udom) {
4266: my $answer=reply('load',$tryserver);
4267: if (($answer=~/\d+/) && ($answer<$loadm)) {
4268: $loadm=$answer;
4269: $unhome=$tryserver;
4270: }
4271: }
4272: }
4273: }
4274: if (($unhome eq '') || ($unhome eq 'no_host')) {
4275: return 'error: unable to find a home server for '.$uname.
4276: ' in domain '.$udom;
4277: }
4278: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4279: &escape($upass),$unhome);
4280: unless ($reply eq 'ok') {
4281: return 'error: '.$reply;
4282: }
4283: $uhome=&homeserver($uname,$udom,'true');
4284: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
4285: return 'error: unable verify users home machine.';
4286: }
4287: } # End of creation of new user
4288: # ---------------------------------------------------------------------- Add ID
4289: if ($uid) {
4290: $uid=~tr/A-Z/a-z/;
4291: my %uidhash=&idrget($udom,$uname);
4292: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4293: && (!$forceid)) {
4294: unless ($uid eq $uidhash{$uname}) {
4295: return 'error: user id "'.$uid.'" does not match '.
4296: 'current user id "'.$uidhash{$uname}.'".';
4297: }
4298: } else {
4299: &idput($udom,($uname => $uid));
4300: }
4301: }
4302: # -------------------------------------------------------------- Add names, etc
4303: my @tmp=&get('environment',
4304: ['firstname','middlename','lastname','generation'],
4305: $udom,$uname);
4306: my %names;
4307: if ($tmp[0] =~ m/^error:.*/) {
4308: %names=();
4309: } else {
4310: %names = @tmp;
4311: }
4312: #
4313: # Make sure to not trash student environment if instructor does not bother
4314: # to supply name and email information
4315: #
4316: if ($first) { $names{'firstname'} = $first; }
4317: if (defined($middle)) { $names{'middlename'} = $middle; }
4318: if ($last) { $names{'lastname'} = $last; }
4319: if (defined($gene)) { $names{'generation'} = $gene; }
4320: if ($email) {
4321: $email=~s/[^\w\@\.\-\,]//gs;
4322: if ($email=~/\@/) { $names{'notification'} = $email;
4323: $names{'critnotification'} = $email;
4324: $names{'permanentemail'} = $email; }
4325: }
4326: my $reply = &put('environment', \%names, $udom,$uname);
4327: if ($reply ne 'ok') { return 'error: '.$reply; }
4328: &devalidate_cache_new('namescache',$uname.':'.$udom);
4329: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
4330: $umode.', '.$first.', '.$middle.', '.
4331: $last.', '.$gene.' by '.
4332: $env{'user.name'}.' at '.$env{'user.domain'});
4333: return 'ok';
4334: }
4335:
4336: # -------------------------------------------------------------- Modify student
4337:
4338: sub modifystudent {
4339: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
4340: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
4341: if (!$cid) {
4342: unless ($cid=$env{'request.course.id'}) {
4343: return 'not_in_class';
4344: }
4345: }
4346: # --------------------------------------------------------------- Make the user
4347: my $reply=&modifyuser
4348: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
4349: $desiredhome,$email);
4350: unless ($reply eq 'ok') { return $reply; }
4351: # This will cause &modify_student_enrollment to get the uid from the
4352: # students environment
4353: $uid = undef if (!$forceid);
4354: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
4355: $gene,$usec,$end,$start,$type,$locktype,$cid);
4356: return $reply;
4357: }
4358:
4359: sub modify_student_enrollment {
4360: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
4361: my ($cdom,$cnum,$chome);
4362: if (!$cid) {
4363: unless ($cid=$env{'request.course.id'}) {
4364: return 'not_in_class';
4365: }
4366: $cdom=$env{'course.'.$cid.'.domain'};
4367: $cnum=$env{'course.'.$cid.'.num'};
4368: } else {
4369: ($cdom,$cnum)=split(/_/,$cid);
4370: }
4371: $chome=$env{'course.'.$cid.'.home'};
4372: if (!$chome) {
4373: $chome=&homeserver($cnum,$cdom);
4374: }
4375: if (!$chome) { return 'unknown_course'; }
4376: # Make sure the user exists
4377: my $uhome=&homeserver($uname,$udom);
4378: if (($uhome eq '') || ($uhome eq 'no_host')) {
4379: return 'error: no such user';
4380: }
4381: # Get student data if we were not given enough information
4382: if (!defined($first) || $first eq '' ||
4383: !defined($last) || $last eq '' ||
4384: !defined($uid) || $uid eq '' ||
4385: !defined($middle) || $middle eq '' ||
4386: !defined($gene) || $gene eq '') {
4387: # They did not supply us with enough data to enroll the student, so
4388: # we need to pick up more information.
4389: my %tmp = &get('environment',
4390: ['firstname','middlename','lastname', 'generation','id']
4391: ,$udom,$uname);
4392:
4393: #foreach (keys(%tmp)) {
4394: # &logthis("key $_ = ".$tmp{$_});
4395: #}
4396: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4397: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4398: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
4399: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
4400: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4401: }
4402: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
4403: my $reply=cput('classlist',
4404: {"$uname:$udom" =>
4405: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
4406: $cdom,$cnum);
4407: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4408: return 'error: '.$reply;
4409: } else {
4410: &devalidate_getsection_cache($udom,$uname,$cid);
4411: }
4412: # Add student role to user
4413: my $uurl='/'.$cid;
4414: $uurl=~s/\_/\//g;
4415: if ($usec) {
4416: $uurl.='/'.$usec;
4417: }
4418: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
4419: }
4420:
4421: sub format_name {
4422: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
4423: my $name;
4424: if ($first ne 'lastname') {
4425: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
4426: } else {
4427: if ($lastname=~/\S/) {
4428: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
4429: $name=~s/\s+,/,/;
4430: } else {
4431: $name.= $firstname.' '.$middlename.' '.$generation;
4432: }
4433: }
4434: $name=~s/^\s+//;
4435: $name=~s/\s+$//;
4436: $name=~s/\s+/ /g;
4437: return $name;
4438: }
4439:
4440: # ------------------------------------------------- Write to course preferences
4441:
4442: sub writecoursepref {
4443: my ($courseid,%prefs)=@_;
4444: $courseid=~s/^\///;
4445: $courseid=~s/\_/\//g;
4446: my ($cdomain,$cnum)=split(/\//,$courseid);
4447: my $chome=homeserver($cnum,$cdomain);
4448: if (($chome eq '') || ($chome eq 'no_host')) {
4449: return 'error: no such course';
4450: }
4451: my $cstring='';
4452: foreach (keys %prefs) {
4453: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
4454: }
4455: $cstring=~s/\&$//;
4456: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
4457: }
4458:
4459: # ---------------------------------------------------------- Make/modify course
4460:
4461: sub createcourse {
4462: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
4463: $course_owner,$crstype)=@_;
4464: $url=&declutter($url);
4465: my $cid='';
4466: unless (&allowed('ccc',$udom)) {
4467: return 'refused';
4468: }
4469: # ------------------------------------------------------------------- Create ID
4470: my $uname=int(1+rand(9)).
4471: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
4472: substr($$.time,0,5).unpack("H8",pack("I32",time)).
4473: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4474: # ----------------------------------------------- Make sure that does not exist
4475: my $uhome=&homeserver($uname,$udom,'true');
4476: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4477: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
4478: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4479: $uhome=&homeserver($uname,$udom,'true');
4480: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4481: return 'error: unable to generate unique course-ID';
4482: }
4483: }
4484: # ------------------------------------------------ Check supplied server name
4485: $course_server = $env{'user.homeserver'} if (! defined($course_server));
4486: if (! exists($libserv{$course_server})) {
4487: return 'error:bad server name '.$course_server;
4488: }
4489: # ------------------------------------------------------------- Make the course
4490: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
4491: $course_server);
4492: unless ($reply eq 'ok') { return 'error: '.$reply; }
4493: $uhome=&homeserver($uname,$udom,'true');
4494: if (($uhome eq '') || ($uhome eq 'no_host')) {
4495: return 'error: no such course';
4496: }
4497: # ----------------------------------------------------------------- Course made
4498: # log existence
4499: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
4500: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
4501: &escape($crstype),$uhome);
4502: &flushcourselogs();
4503: # set toplevel url
4504: my $topurl=$url;
4505: unless ($nonstandard) {
4506: # ------------------------------------------ For standard courses, make top url
4507: my $mapurl=&clutter($url);
4508: if ($mapurl eq '/res/') { $mapurl=''; }
4509: $env{'form.initmap'}=(<<ENDINITMAP);
4510: <map>
4511: <resource id="1" type="start"></resource>
4512: <resource id="2" src="$mapurl"></resource>
4513: <resource id="3" type="finish"></resource>
4514: <link index="1" from="1" to="2"></link>
4515: <link index="2" from="2" to="3"></link>
4516: </map>
4517: ENDINITMAP
4518: $topurl=&declutter(
4519: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
4520: );
4521: }
4522: # ----------------------------------------------------------- Write preferences
4523: &writecoursepref($udom.'_'.$uname,
4524: ('description' => $description,
4525: 'url' => $topurl));
4526: return '/'.$udom.'/'.$uname;
4527: }
4528:
4529: # ---------------------------------------------------------- Assign Custom Role
4530:
4531: sub assigncustomrole {
4532: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
4533: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
4534: $end,$start,$deleteflag);
4535: }
4536:
4537: # ----------------------------------------------------------------- Revoke Role
4538:
4539: sub revokerole {
4540: my ($udom,$uname,$url,$role,$deleteflag)=@_;
4541: my $now=time;
4542: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
4543: }
4544:
4545: # ---------------------------------------------------------- Revoke Custom Role
4546:
4547: sub revokecustomrole {
4548: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
4549: my $now=time;
4550: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
4551: $deleteflag);
4552: }
4553:
4554: # ------------------------------------------------------------ Disk usage
4555: sub diskusage {
4556: my ($udom,$uname,$directoryRoot)=@_;
4557: $directoryRoot =~ s/\/$//;
4558: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
4559: return $listing;
4560: }
4561:
4562: sub is_locked {
4563: my ($file_name, $domain, $user) = @_;
4564: my @check;
4565: my $is_locked;
4566: push @check, $file_name;
4567: my %locked = &get('file_permissions',\@check,
4568: $env{'user.domain'},$env{'user.name'});
4569: my ($tmp)=keys(%locked);
4570: if ($tmp=~/^error:/) { undef(%locked); }
4571:
4572: if (ref($locked{$file_name}) eq 'ARRAY') {
4573: $is_locked = 'false';
4574: foreach my $entry (@{$locked{$file_name}}) {
4575: if (ref($entry) eq 'ARRAY') {
4576: $is_locked = 'true';
4577: last;
4578: }
4579: }
4580: } else {
4581: $is_locked = 'false';
4582: }
4583: }
4584:
4585: # ------------------------------------------------------------- Mark as Read Only
4586:
4587: sub mark_as_readonly {
4588: my ($domain,$user,$files,$what) = @_;
4589: my %current_permissions = &dump('file_permissions',$domain,$user);
4590: my ($tmp)=keys(%current_permissions);
4591: if ($tmp=~/^error:/) { undef(%current_permissions); }
4592: foreach my $file (@{$files}) {
4593: push(@{$current_permissions{$file}},$what);
4594: }
4595: &put('file_permissions',\%current_permissions,$domain,$user);
4596: return;
4597: }
4598:
4599: # ------------------------------------------------------------Save Selected Files
4600:
4601: sub save_selected_files {
4602: my ($user, $path, @files) = @_;
4603: my $filename = $user."savedfiles";
4604: my @other_files = &files_not_in_path($user, $path);
4605: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4606: foreach my $file (@files) {
4607: print (OUT $env{'form.currentpath'}.$file."\n");
4608: }
4609: foreach my $file (@other_files) {
4610: print (OUT $file."\n");
4611: }
4612: close (OUT);
4613: return 'ok';
4614: }
4615:
4616: sub clear_selected_files {
4617: my ($user) = @_;
4618: my $filename = $user."savedfiles";
4619: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4620: print (OUT undef);
4621: close (OUT);
4622: return ("ok");
4623: }
4624:
4625: sub files_in_path {
4626: my ($user, $path) = @_;
4627: my $filename = $user."savedfiles";
4628: my %return_files;
4629: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4630: while (my $line_in = <IN>) {
4631: chomp ($line_in);
4632: my @paths_and_file = split (m!/!, $line_in);
4633: my $file_part = pop (@paths_and_file);
4634: my $path_part = join ('/', @paths_and_file);
4635: $path_part.='/';
4636: my $path_and_file = $path_part.$file_part;
4637: if ($path_part eq $path) {
4638: $return_files{$file_part}= 'selected';
4639: }
4640: }
4641: close (IN);
4642: return (\%return_files);
4643: }
4644:
4645: # called in portfolio select mode, to show files selected NOT in current directory
4646: sub files_not_in_path {
4647: my ($user, $path) = @_;
4648: my $filename = $user."savedfiles";
4649: my @return_files;
4650: my $path_part;
4651: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4652: while (<IN>) {
4653: #ok, I know it's clunky, but I want it to work
4654: my @paths_and_file = split m!/!, $_;
4655: my $file_part = pop (@paths_and_file);
4656: chomp ($file_part);
4657: my $path_part = join ('/', @paths_and_file);
4658: $path_part .= '/';
4659: my $path_and_file = $path_part.$file_part;
4660: if ($path_part ne $path) {
4661: push (@return_files, ($path_and_file));
4662: }
4663: }
4664: close (OUT);
4665: return (@return_files);
4666: }
4667:
4668: #----------------------------------------------Get portfolio file permissions
4669:
4670: sub get_portfile_permissions {
4671: my ($domain,$user) = @_;
4672: my %current_permissions = &dump('file_permissions',$domain,$user);
4673: my ($tmp)=keys(%current_permissions);
4674: if ($tmp=~/^error:/) { undef(%current_permissions); }
4675: return \%current_permissions;
4676: }
4677:
4678: #---------------------------------------------Get portfolio file access controls
4679:
4680: sub get_access_controls {
4681: my ($current_permissions,$group,$file) = @_;
4682: my %access;
4683: if (defined($file)) {
4684: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
4685: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
4686: $access{$file}{$control} = $$current_permissions{$file."\0".$control};
4687: }
4688: }
4689: } else {
4690: foreach my $key (keys(%{$current_permissions})) {
4691: if ($key =~ /\0accesscontrol$/) {
4692: if (defined($group)) {
4693: if ($key !~ m-^\Q$group\E/-) {
4694: next;
4695: }
4696: }
4697: my ($fullpath) = split(/\0/,$key);
4698: if (ref($$current_permissions{$key}) eq 'HASH') {
4699: foreach my $control (keys(%{$$current_permissions{$key}})) {
4700: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
4701: }
4702: }
4703: }
4704: }
4705: }
4706: return %access;
4707: }
4708:
4709: sub parse_access_controls {
4710: my ($access_item) = @_;
4711: my %content;
4712: my $role_id;
4713: my $user;
4714: my $usercount;
4715: my $token;
4716: my $parser=HTML::TokeParser->new(\$access_item);
4717: while ($token=$parser->get_token) {
4718: if ($token->[0] eq 'S') {
4719: my $entry=$token->[1];
4720: if ($entry eq 'scope') {
4721: my $type = $token->[2]{'type'};
4722: if (($type eq 'course') || ($type eq 'group')) {
4723: $content{'roles'} = {};
4724: }
4725: } elsif ($entry eq 'roles') {
4726: $role_id = $token->[2]{id};
4727: $content{$entry}{$role_id} = {
4728: role => [],
4729: access => [],
4730: section => [],
4731: group => [],
4732: };
4733: } elsif ($entry eq 'users') {
4734: $content{'users'} = {};
4735: $usercount = 0;
4736: } elsif ($entry eq 'user') {
4737: $user = '';
4738: } else {
4739: my $value=$parser->get_text('/'.$entry);
4740: if ($entry eq 'uname') {
4741: $user = $value;
4742: } elsif ($entry eq 'udom') {
4743: $user .= ':'.$value;
4744: $content{'users'}{$user} = $usercount;
4745: } elsif ($entry eq 'role' ||
4746: $entry eq 'access' ||
4747: $entry eq 'section' ||
4748: $entry eq 'group') {
4749: if ($role_id ne '') {
4750: push(@{$content{'roles'}{$role_id}{$entry}},$value);
4751: }
4752: } elsif ($entry eq 'dom') {
4753: push(@{$content{$entry}},$value);
4754: } else {
4755: $content{$entry}=$value;
4756: }
4757: }
4758: } elsif ($token->[0] eq 'E') {
4759: if ($token->[1] eq 'user') {
4760: $user = '';
4761: $usercount ++;
4762: } elsif ($token->[1] eq 'roles') {
4763: $role_id = '';
4764: }
4765: }
4766: }
4767: return %content;
4768: }
4769:
4770: sub modify_access_controls {
4771: my ($file_name,$changes,$domain,$user)=@_;
4772: my ($outcome,$deloutcome);
4773: my %store_permissions;
4774: my %new_values;
4775: my %new_control;
4776: my %translation;
4777: my @deletions = ();
4778: my $now = time;
4779: if (exists($$changes{'activate'})) {
4780: if (ref($$changes{'activate'}) eq 'HASH') {
4781: my @newitems = sort(keys(%{$$changes{'activate'}}));
4782: my $numnew = scalar(@newitems);
4783: for (my $i=0; $i<$numnew; $i++) {
4784: my $newkey = $newitems[$i];
4785: my $newid = &Apache::loncommon::get_cgi_id();
4786: $newkey =~ s/^(\d+)/$newid/;
4787: $translation{$1} = $newid;
4788: $new_values{$file_name."\0".$newkey} =
4789: $$changes{'activate'}{$newitems[$i]};
4790: $new_control{$newkey} = $now;
4791: }
4792: }
4793: }
4794: my %todelete;
4795: my %changed_items;
4796: foreach my $action ('delete','update') {
4797: if (exists($$changes{$action})) {
4798: if (ref($$changes{$action}) eq 'HASH') {
4799: foreach my $key (keys(%{$$changes{$action}})) {
4800: my ($itemnum) = ($key =~ /^([^:]+):/);
4801: if ($action eq 'delete') {
4802: $todelete{$itemnum} = 1;
4803: } else {
4804: $changed_items{$itemnum} = $key;
4805: }
4806: }
4807: }
4808: }
4809: }
4810: # get lock on access controls for file.
4811: my $lockhash = {
4812: $file_name."\0".'locked_access_records' => $env{'user.name'}.
4813: ':'.$env{'user.domain'},
4814: };
4815: my $tries = 0;
4816: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
4817:
4818: while (($gotlock ne 'ok') && $tries <3) {
4819: $tries ++;
4820: sleep 1;
4821: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
4822: }
4823: if ($gotlock eq 'ok') {
4824: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
4825: my ($tmp)=keys(%curr_permissions);
4826: if ($tmp=~/^error:/) { undef(%curr_permissions); }
4827: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
4828: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
4829: if (ref($curr_controls) eq 'HASH') {
4830: foreach my $control_item (keys(%{$curr_controls})) {
4831: my ($itemnum) = ($control_item =~ /^([^:]+):/);
4832: if (defined($todelete{$itemnum})) {
4833: push(@deletions,$file_name."\0".$control_item);
4834: } else {
4835: if (defined($changed_items{$itemnum})) {
4836: $new_control{$changed_items{$itemnum}} = $now;
4837: push(@deletions,$file_name."\0".$control_item);
4838: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
4839: } else {
4840: $new_control{$control_item} = $$curr_controls{$control_item};
4841: }
4842: }
4843: }
4844: }
4845: }
4846: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
4847: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
4848: $outcome = &put('file_permissions',\%new_values,$domain,$user);
4849: # remove lock
4850: my @del_lock = ($file_name."\0".'locked_access_records');
4851: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
4852: } else {
4853: $outcome = "error: could not obtain lockfile\n";
4854: }
4855: return ($outcome,$deloutcome,\%new_values,\%translation);
4856: }
4857:
4858: #------------------------------------------------------Get Marked as Read Only
4859:
4860: sub get_marked_as_readonly {
4861: my ($domain,$user,$what,$group) = @_;
4862: my $current_permissions = &get_portfile_permissions($domain,$user);
4863: my @readonly_files;
4864: my $cmp1=$what;
4865: if (ref($what)) { $cmp1=join('',@{$what}) };
4866: while (my ($file_name,$value) = each(%{$current_permissions})) {
4867: if (defined($group)) {
4868: if ($file_name !~ m-^\Q$group\E/-) {
4869: next;
4870: }
4871: }
4872: if (ref($value) eq "ARRAY"){
4873: foreach my $stored_what (@{$value}) {
4874: my $cmp2=$stored_what;
4875: if (ref($stored_what eq 'ARRAY')) {
4876: $cmp2=join('',@{$stored_what});
4877: }
4878: if ($cmp1 eq $cmp2) {
4879: push(@readonly_files, $file_name);
4880: last;
4881: } elsif (!defined($what)) {
4882: push(@readonly_files, $file_name);
4883: last;
4884: }
4885: }
4886: }
4887: }
4888: return @readonly_files;
4889: }
4890: #-----------------------------------------------------------Get Marked as Read Only Hash
4891:
4892: sub get_marked_as_readonly_hash {
4893: my ($current_permissions,$group,$what) = @_;
4894: my %readonly_files;
4895: while (my ($file_name,$value) = each(%{$current_permissions})) {
4896: if (defined($group)) {
4897: if ($file_name !~ m-^\Q$group\E/-) {
4898: next;
4899: }
4900: }
4901: if (ref($value) eq "ARRAY"){
4902: foreach my $stored_what (@{$value}) {
4903: if (ref($stored_what) eq 'ARRAY') {
4904: foreach my $lock_descriptor(@{$stored_what}) {
4905: if ($lock_descriptor eq 'graded') {
4906: $readonly_files{$file_name} = 'graded';
4907: } elsif ($lock_descriptor eq 'handback') {
4908: $readonly_files{$file_name} = 'handback';
4909: } else {
4910: if (!exists($readonly_files{$file_name})) {
4911: $readonly_files{$file_name} = 'locked';
4912: }
4913: }
4914: }
4915: }
4916: }
4917: }
4918: }
4919: return %readonly_files;
4920: }
4921: # ------------------------------------------------------------ Unmark as Read Only
4922:
4923: sub unmark_as_readonly {
4924: # unmarks $file_name (if $file_name is defined), or all files locked by $what
4925: # for portfolio submissions, $what contains [$symb,$crsid]
4926: my ($domain,$user,$what,$file_name,$group) = @_;
4927: my $symb_crs = $what;
4928: if (ref($what)) { $symb_crs=join('',@$what); }
4929: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
4930: my ($tmp)=keys(%current_permissions);
4931: if ($tmp=~/^error:/) { undef(%current_permissions); }
4932: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
4933: foreach my $file (@readonly_files) {
4934: if (defined($file_name) && ($file_name ne $file)) { next; }
4935: my $current_locks = $current_permissions{$file};
4936: my @new_locks;
4937: my @del_keys;
4938: if (ref($current_locks) eq "ARRAY"){
4939: foreach my $locker (@{$current_locks}) {
4940: my $compare=$locker;
4941: if (ref($locker) eq 'ARRAY') {
4942: $compare=join('',@{$locker});
4943: if ($compare ne $symb_crs) {
4944: push(@new_locks, $locker);
4945: }
4946: }
4947: }
4948: if (scalar(@new_locks) > 0) {
4949: $current_permissions{$file} = \@new_locks;
4950: } else {
4951: push(@del_keys, $file);
4952: &del('file_permissions',\@del_keys, $domain, $user);
4953: delete($current_permissions{$file});
4954: }
4955: }
4956: }
4957: &put('file_permissions',\%current_permissions,$domain,$user);
4958: return;
4959: }
4960:
4961: # ------------------------------------------------------------ Directory lister
4962:
4963: sub dirlist {
4964: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
4965:
4966: $uri=~s/^\///;
4967: $uri=~s/\/$//;
4968: my ($udom, $uname);
4969: (undef,$udom,$uname)=split(/\//,$uri);
4970: if(defined($userdomain)) {
4971: $udom = $userdomain;
4972: }
4973: if(defined($username)) {
4974: $uname = $username;
4975: }
4976:
4977: my $dirRoot = $perlvar{'lonDocRoot'};
4978: if(defined($alternateDirectoryRoot)) {
4979: $dirRoot = $alternateDirectoryRoot;
4980: $dirRoot =~ s/\/$//;
4981: }
4982:
4983: if($udom) {
4984: if($uname) {
4985: my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
4986: homeserver($uname,$udom));
4987: my @listing_results;
4988: if ($listing eq 'unknown_cmd') {
4989: $listing=reply('ls:'.$dirRoot.'/'.$uri,
4990: homeserver($uname,$udom));
4991: @listing_results = split(/:/,$listing);
4992: } else {
4993: @listing_results = map { &unescape($_); } split(/:/,$listing);
4994: }
4995: return @listing_results;
4996: } elsif(!defined($alternateDirectoryRoot)) {
4997: my $tryserver;
4998: my %allusers=();
4999: foreach $tryserver (keys %libserv) {
5000: if($hostdom{$tryserver} eq $udom) {
5001: my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5002: $udom, $tryserver);
5003: my @listing_results;
5004: if ($listing eq 'unknown_cmd') {
5005: $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5006: $udom, $tryserver);
5007: @listing_results = split(/:/,$listing);
5008: } else {
5009: @listing_results =
5010: map { &unescape($_); } split(/:/,$listing);
5011: }
5012: if ($listing_results[0] ne 'no_such_dir' &&
5013: $listing_results[0] ne 'empty' &&
5014: $listing_results[0] ne 'con_lost') {
5015: foreach (@listing_results) {
5016: my ($entry,@stat)=split(/&/,$_);
5017: $allusers{$entry}=1;
5018: }
5019: }
5020: }
5021: }
5022: my $alluserstr='';
5023: foreach (sort keys %allusers) {
5024: $alluserstr.=$_.'&user:';
5025: }
5026: $alluserstr=~s/:$//;
5027: return split(/:/,$alluserstr);
5028: } else {
5029: my @emptyResults = ();
5030: push(@emptyResults, 'missing user name');
5031: return split(':',@emptyResults);
5032: }
5033: } elsif(!defined($alternateDirectoryRoot)) {
5034: my $tryserver;
5035: my %alldom=();
5036: foreach $tryserver (keys %libserv) {
5037: $alldom{$hostdom{$tryserver}}=1;
5038: }
5039: my $alldomstr='';
5040: foreach (sort keys %alldom) {
5041: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
5042: }
5043: $alldomstr=~s/:$//;
5044: return split(/:/,$alldomstr);
5045: } else {
5046: my @emptyResults = ();
5047: push(@emptyResults, 'missing domain');
5048: return split(':',@emptyResults);
5049: }
5050: }
5051:
5052: # --------------------------------------------- GetFileTimestamp
5053: # This function utilizes dirlist and returns the date stamp for
5054: # when it was last modified. It will also return an error of -1
5055: # if an error occurs
5056:
5057: ##
5058: ## FIXME: This subroutine assumes its caller knows something about the
5059: ## directory structure of the home server for the student ($root).
5060: ## Not a good assumption to make. Since this is for looking up files
5061: ## in user directories, the full path should be constructed by lond, not
5062: ## whatever machine we request data from.
5063: ##
5064: sub GetFileTimestamp {
5065: my ($studentDomain,$studentName,$filename,$root)=@_;
5066: $studentDomain=~s/\W//g;
5067: $studentName=~s/\W//g;
5068: my $subdir=$studentName.'__';
5069: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5070: my $proname="$studentDomain/$subdir/$studentName";
5071: $proname .= '/'.$filename;
5072: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5073: $studentName, $root);
5074: my @stats = split('&', $fileStat);
5075: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5076: # @stats contains first the filename, then the stat output
5077: return $stats[10]; # so this is 10 instead of 9.
5078: } else {
5079: return -1;
5080: }
5081: }
5082:
5083: sub stat_file {
5084: my ($uri) = @_;
5085: $uri = &clutter($uri);
5086:
5087: # we want just the url part without the unneeded accessor url bits
5088: if ($uri =~ m-^/adm/-) {
5089: $uri=~s-^/adm/wrapper/-/-;
5090: $uri=~s-^/adm/coursedocs/showdoc/-/-;
5091: }
5092: my ($udom,$uname,$file,$dir);
5093: if ($uri =~ m-^/(uploaded|editupload)/-) {
5094: ($udom,$uname,$file) =
5095: ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
5096: $file = 'userfiles/'.$file;
5097: $dir = &propath($udom,$uname);
5098: }
5099: if ($uri =~ m-^/res/-) {
5100: ($udom,$uname) =
5101: ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
5102: $file = $uri;
5103: }
5104:
5105: if (!$udom || !$uname || !$file) {
5106: # unable to handle the uri
5107: return ();
5108: }
5109:
5110: my ($result) = &dirlist($file,$udom,$uname,$dir);
5111: my @stats = split('&', $result);
5112:
5113: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5114: shift(@stats); #filename is first
5115: return @stats;
5116: }
5117: return ();
5118: }
5119:
5120: # -------------------------------------------------------- Value of a Condition
5121:
5122: # gets the value of a specific preevaluated condition
5123: # stored in the string $env{user.state.<cid>}
5124: # or looks up a condition reference in the bighash and if if hasn't
5125: # already been evaluated recurses into docondval to get the value of
5126: # the condition, then memoizing it to
5127: # $env{user.state.<cid>.<condition>}
5128: sub directcondval {
5129: my $number=shift;
5130: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
5131: &Apache::lonuserstate::evalstate();
5132: }
5133: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5134: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5135: } elsif ($number =~ /^_/) {
5136: my $sub_condition;
5137: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5138: &GDBM_READER(),0640)) {
5139: $sub_condition=$bighash{'conditions'.$number};
5140: untie(%bighash);
5141: }
5142: my $value = &docondval($sub_condition);
5143: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5144: return $value;
5145: }
5146: if ($env{'user.state.'.$env{'request.course.id'}}) {
5147: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
5148: } else {
5149: return 2;
5150: }
5151: }
5152:
5153: # get the collection of conditions for this resource
5154: sub condval {
5155: my $condidx=shift;
5156: my $allpathcond='';
5157: foreach my $cond (split(/\|/,$condidx)) {
5158: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5159: $allpathcond.=
5160: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5161: }
5162: }
5163: $allpathcond=~s/\|$//;
5164: return &docondval($allpathcond);
5165: }
5166:
5167: #evaluates an expression of conditions
5168: sub docondval {
5169: my ($allpathcond) = @_;
5170: my $result=0;
5171: if ($env{'request.course.id'}
5172: && defined($allpathcond)) {
5173: my $operand='|';
5174: my @stack;
5175: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5176: if ($chunk eq '(') {
5177: push @stack,($operand,$result);
5178: } elsif ($chunk eq ')') {
5179: my $before=pop @stack;
5180: if (pop @stack eq '&') {
5181: $result=$result>$before?$before:$result;
5182: } else {
5183: $result=$result>$before?$result:$before;
5184: }
5185: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5186: $operand=$chunk;
5187: } else {
5188: my $new=directcondval($chunk);
5189: if ($operand eq '&') {
5190: $result=$result>$new?$new:$result;
5191: } else {
5192: $result=$result>$new?$result:$new;
5193: }
5194: }
5195: }
5196: }
5197: return $result;
5198: }
5199:
5200: # ---------------------------------------------------- Devalidate courseresdata
5201:
5202: sub devalidatecourseresdata {
5203: my ($coursenum,$coursedomain)=@_;
5204: my $hashid=$coursenum.':'.$coursedomain;
5205: &devalidate_cache_new('courseres',$hashid);
5206: }
5207:
5208: # --------------------------------------------------- Course Resourcedata Query
5209:
5210: sub get_courseresdata {
5211: my ($coursenum,$coursedomain)=@_;
5212: my $coursehom=&homeserver($coursenum,$coursedomain);
5213: my $hashid=$coursenum.':'.$coursedomain;
5214: my ($result,$cached)=&is_cached_new('courseres',$hashid);
5215: my %dumpreply;
5216: unless (defined($cached)) {
5217: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
5218: $result=\%dumpreply;
5219: my ($tmp) = keys(%dumpreply);
5220: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5221: &do_cache_new('courseres',$hashid,$result,600);
5222: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5223: return $tmp;
5224: } elsif ($tmp =~ /^(error)/) {
5225: $result=undef;
5226: &do_cache_new('courseres',$hashid,$result,600);
5227: }
5228: }
5229: return $result;
5230: }
5231:
5232: sub devalidateuserresdata {
5233: my ($uname,$udom)=@_;
5234: my $hashid="$udom:$uname";
5235: &devalidate_cache_new('userres',$hashid);
5236: }
5237:
5238: sub get_userresdata {
5239: my ($uname,$udom)=@_;
5240: #most student don\'t have any data set, check if there is some data
5241: if (&EXT_cache_status($udom,$uname)) { return undef; }
5242:
5243: my $hashid="$udom:$uname";
5244: my ($result,$cached)=&is_cached_new('userres',$hashid);
5245: if (!defined($cached)) {
5246: my %resourcedata=&dump('resourcedata',$udom,$uname);
5247: $result=\%resourcedata;
5248: &do_cache_new('userres',$hashid,$result,600);
5249: }
5250: my ($tmp)=keys(%$result);
5251: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5252: return $result;
5253: }
5254: #error 2 occurs when the .db doesn't exist
5255: if ($tmp!~/error: 2 /) {
5256: &logthis("<font color=\"blue\">WARNING:".
5257: " Trying to get resource data for ".
5258: $uname." at ".$udom.": ".
5259: $tmp."</font>");
5260: } elsif ($tmp=~/error: 2 /) {
5261: #&EXT_cache_set($udom,$uname);
5262: &do_cache_new('userres',$hashid,undef,600);
5263: undef($tmp); # not really an error so don't send it back
5264: }
5265: return $tmp;
5266: }
5267:
5268: sub resdata {
5269: my ($name,$domain,$type,@which)=@_;
5270: my $result;
5271: if ($type eq 'course') {
5272: $result=&get_courseresdata($name,$domain);
5273: } elsif ($type eq 'user') {
5274: $result=&get_userresdata($name,$domain);
5275: }
5276: if (!ref($result)) { return $result; }
5277: foreach my $item (@which) {
5278: if (defined($result->{$item})) {
5279: return $result->{$item};
5280: }
5281: }
5282: return undef;
5283: }
5284:
5285: #
5286: # EXT resource caching routines
5287: #
5288:
5289: sub clear_EXT_cache_status {
5290: &delenv('cache.EXT.');
5291: }
5292:
5293: sub EXT_cache_status {
5294: my ($target_domain,$target_user) = @_;
5295: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5296: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
5297: # We know already the user has no data
5298: return 1;
5299: } else {
5300: return 0;
5301: }
5302: }
5303:
5304: sub EXT_cache_set {
5305: my ($target_domain,$target_user) = @_;
5306: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
5307: #&appenv($cachename => time);
5308: }
5309:
5310: # --------------------------------------------------------- Value of a Variable
5311: sub EXT {
5312:
5313: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
5314: unless ($varname) { return ''; }
5315: #get real user name/domain, courseid and symb
5316: my $courseid;
5317: my $publicuser;
5318: if ($symbparm) {
5319: $symbparm=&get_symb_from_alias($symbparm);
5320: }
5321: if (!($uname && $udom)) {
5322: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
5323: &Apache::lonxml::whichuser($symbparm);
5324: if (!$symbparm) { $symbparm=$cursymb; }
5325: } else {
5326: $courseid=$env{'request.course.id'};
5327: }
5328: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5329: my $rest;
5330: if (defined($therest[0])) {
5331: $rest=join('.',@therest);
5332: } else {
5333: $rest='';
5334: }
5335:
5336: my $qualifierrest=$qualifier;
5337: if ($rest) { $qualifierrest.='.'.$rest; }
5338: my $spacequalifierrest=$space;
5339: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
5340: if ($realm eq 'user') {
5341: # --------------------------------------------------------------- user.resource
5342: if ($space eq 'resource') {
5343: if ( (defined($Apache::lonhomework::parsing_a_problem)
5344: || defined($Apache::lonhomework::parsing_a_task))
5345: &&
5346: ($symbparm eq &symbread()) ) {
5347: # if we are in the middle of processing the resource the
5348: # get the value we are planning on committing
5349: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5350: return $Apache::lonhomework::results{$qualifierrest};
5351: } else {
5352: return $Apache::lonhomework::history{$qualifierrest};
5353: }
5354: } else {
5355: my %restored;
5356: if ($publicuser || $env{'request.state'} eq 'construct') {
5357: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5358: } else {
5359: %restored=&restore($symbparm,$courseid,$udom,$uname);
5360: }
5361: return $restored{$qualifierrest};
5362: }
5363: # ----------------------------------------------------------------- user.access
5364: } elsif ($space eq 'access') {
5365: # FIXME - not supporting calls for a specific user
5366: return &allowed($qualifier,$rest);
5367: # ------------------------------------------ user.preferences, user.environment
5368: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
5369: if (($uname eq $env{'user.name'}) &&
5370: ($udom eq $env{'user.domain'})) {
5371: return $env{join('.',('environment',$qualifierrest))};
5372: } else {
5373: my %returnhash;
5374: if (!$publicuser) {
5375: %returnhash=&userenvironment($udom,$uname,
5376: $qualifierrest);
5377: }
5378: return $returnhash{$qualifierrest};
5379: }
5380: # ----------------------------------------------------------------- user.course
5381: } elsif ($space eq 'course') {
5382: # FIXME - not supporting calls for a specific user
5383: return $env{join('.',('request.course',$qualifier))};
5384: # ------------------------------------------------------------------- user.role
5385: } elsif ($space eq 'role') {
5386: # FIXME - not supporting calls for a specific user
5387: my ($role,$where)=split(/\./,$env{'request.role'});
5388: if ($qualifier eq 'value') {
5389: return $role;
5390: } elsif ($qualifier eq 'extent') {
5391: return $where;
5392: }
5393: # ----------------------------------------------------------------- user.domain
5394: } elsif ($space eq 'domain') {
5395: return $udom;
5396: # ------------------------------------------------------------------- user.name
5397: } elsif ($space eq 'name') {
5398: return $uname;
5399: # ---------------------------------------------------- Any other user namespace
5400: } else {
5401: my %reply;
5402: if (!$publicuser) {
5403: %reply=&get($space,[$qualifierrest],$udom,$uname);
5404: }
5405: return $reply{$qualifierrest};
5406: }
5407: } elsif ($realm eq 'query') {
5408: # ---------------------------------------------- pull stuff out of query string
5409: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5410: [$spacequalifierrest]);
5411: return $env{'form.'.$spacequalifierrest};
5412: } elsif ($realm eq 'request') {
5413: # ------------------------------------------------------------- request.browser
5414: if ($space eq 'browser') {
5415: if ($qualifier eq 'textremote') {
5416: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
5417: return 1;
5418: } else {
5419: return 0;
5420: }
5421: } else {
5422: return $env{'browser.'.$qualifier};
5423: }
5424: # ------------------------------------------------------------ request.filename
5425: } else {
5426: return $env{'request.'.$spacequalifierrest};
5427: }
5428: } elsif ($realm eq 'course') {
5429: # ---------------------------------------------------------- course.description
5430: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
5431: } elsif ($realm eq 'resource') {
5432:
5433: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
5434: if (!$symbparm) { $symbparm=&symbread(); }
5435: }
5436:
5437: if ($space eq 'title') {
5438: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
5439: return &gettitle($symbparm);
5440: }
5441:
5442: if ($space eq 'map') {
5443: my ($map) = &decode_symb($symbparm);
5444: return &symbread($map);
5445: }
5446:
5447: my ($section, $group, @groups);
5448: my ($courselevelm,$courselevel);
5449: if ($symbparm && defined($courseid) &&
5450: $courseid eq $env{'request.course.id'}) {
5451:
5452: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
5453:
5454: # ----------------------------------------------------- Cascading lookup scheme
5455: my $symbp=$symbparm;
5456: my $mapp=&deversion((&decode_symb($symbp))[0]);
5457:
5458: my $symbparm=$symbp.'.'.$spacequalifierrest;
5459: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
5460:
5461: if (($env{'user.name'} eq $uname) &&
5462: ($env{'user.domain'} eq $udom)) {
5463: $section=$env{'request.course.sec'};
5464: @groups = split(/:/,$env{'request.course.groups'});
5465: @groups=&sort_course_groups($courseid,@groups);
5466: } else {
5467: if (! defined($usection)) {
5468: $section=&getsection($udom,$uname,$courseid);
5469: } else {
5470: $section = $usection;
5471: }
5472: @groups = &get_users_groups($udom,$uname,$courseid);
5473: }
5474:
5475: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
5476: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
5477: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
5478:
5479: $courselevel=$courseid.'.'.$spacequalifierrest;
5480: my $courselevelr=$courseid.'.'.$symbparm;
5481: $courselevelm=$courseid.'.'.$mapparm;
5482:
5483: # ----------------------------------------------------------- first, check user
5484:
5485: my $userreply=&resdata($uname,$udom,'user',
5486: ($courselevelr,$courselevelm,
5487: $courselevel));
5488: if (defined($userreply)) { return $userreply; }
5489:
5490: # ------------------------------------------------ second, check some of course
5491: my $coursereply;
5492: if (@groups > 0) {
5493: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
5494: $mapparm,$spacequalifierrest);
5495: if (defined($coursereply)) { return $coursereply; }
5496: }
5497:
5498: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5499: $env{'course.'.$courseid.'.domain'},
5500: 'course',
5501: ($seclevelr,$seclevelm,$seclevel,
5502: $courselevelr));
5503: if (defined($coursereply)) { return $coursereply; }
5504:
5505: # ------------------------------------------------------ third, check map parms
5506: my %parmhash=();
5507: my $thisparm='';
5508: if (tie(%parmhash,'GDBM_File',
5509: $env{'request.course.fn'}.'_parms.db',
5510: &GDBM_READER(),0640)) {
5511: $thisparm=$parmhash{$symbparm};
5512: untie(%parmhash);
5513: }
5514: if ($thisparm) { return $thisparm; }
5515: }
5516: # ------------------------------------------ fourth, look in resource metadata
5517:
5518: $spacequalifierrest=~s/\./\_/;
5519: my $filename;
5520: if (!$symbparm) { $symbparm=&symbread(); }
5521: if ($symbparm) {
5522: $filename=(&decode_symb($symbparm))[2];
5523: } else {
5524: $filename=$env{'request.filename'};
5525: }
5526: my $metadata=&metadata($filename,$spacequalifierrest);
5527: if (defined($metadata)) { return $metadata; }
5528: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
5529: if (defined($metadata)) { return $metadata; }
5530:
5531: # ---------------------------------------------- fourth, look in rest pf course
5532: if ($symbparm && defined($courseid) &&
5533: $courseid eq $env{'request.course.id'}) {
5534: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5535: $env{'course.'.$courseid.'.domain'},
5536: 'course',
5537: ($courselevelm,$courselevel));
5538: if (defined($coursereply)) { return $coursereply; }
5539: }
5540: # ------------------------------------------------------------------ Cascade up
5541: unless ($space eq '0') {
5542: my @parts=split(/_/,$space);
5543: my $id=pop(@parts);
5544: my $part=join('_',@parts);
5545: if ($part eq '') { $part='0'; }
5546: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
5547: $symbparm,$udom,$uname,$section,1);
5548: if (defined($partgeneral)) { return $partgeneral; }
5549: }
5550: if ($recurse) { return undef; }
5551: my $pack_def=&packages_tab_default($filename,$varname);
5552: if (defined($pack_def)) { return $pack_def; }
5553:
5554: # ---------------------------------------------------- Any other user namespace
5555: } elsif ($realm eq 'environment') {
5556: # ----------------------------------------------------------------- environment
5557: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
5558: return $env{'environment.'.$spacequalifierrest};
5559: } else {
5560: my %returnhash=&userenvironment($udom,$uname,
5561: $spacequalifierrest);
5562: return $returnhash{$spacequalifierrest};
5563: }
5564: } elsif ($realm eq 'system') {
5565: # ----------------------------------------------------------------- system.time
5566: if ($space eq 'time') {
5567: return time;
5568: }
5569: } elsif ($realm eq 'server') {
5570: # ----------------------------------------------------------------- system.time
5571: if ($space eq 'name') {
5572: return $ENV{'SERVER_NAME'};
5573: }
5574: }
5575: return '';
5576: }
5577:
5578: sub check_group_parms {
5579: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
5580: my @groupitems = ();
5581: my $resultitem;
5582: my @levels = ($symbparm,$mapparm,$what);
5583: foreach my $group (@{$groups}) {
5584: foreach my $level (@levels) {
5585: my $item = $courseid.'.['.$group.'].'.$level;
5586: push(@groupitems,$item);
5587: }
5588: }
5589: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
5590: $env{'course.'.$courseid.'.domain'},
5591: 'course',@groupitems);
5592: return $coursereply;
5593: }
5594:
5595: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
5596: my ($courseid,@groups) = @_;
5597: @groups = sort(@groups);
5598: return @groups;
5599: }
5600:
5601: sub packages_tab_default {
5602: my ($uri,$varname)=@_;
5603: my (undef,$part,$name)=split(/\./,$varname);
5604:
5605: my (@extension,@specifics,$do_default);
5606: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
5607: my ($pack_type,$pack_part)=split(/_/,$package,2);
5608: if ($pack_type eq 'default') {
5609: $do_default=1;
5610: } elsif ($pack_type eq 'extension') {
5611: push(@extension,[$package,$pack_type,$pack_part]);
5612: } else {
5613: push(@specifics,[$package,$pack_type,$pack_part]);
5614: }
5615: }
5616: # first look for a package that matches the requested part id
5617: foreach my $package (@specifics) {
5618: my (undef,$pack_type,$pack_part)=@{$package};
5619: next if ($pack_part ne $part);
5620: if (defined($packagetab{"$pack_type&$name&default"})) {
5621: return $packagetab{"$pack_type&$name&default"};
5622: }
5623: }
5624: # look for any possible matching non extension_ package
5625: foreach my $package (@specifics) {
5626: my (undef,$pack_type,$pack_part)=@{$package};
5627: if (defined($packagetab{"$pack_type&$name&default"})) {
5628: return $packagetab{"$pack_type&$name&default"};
5629: }
5630: if ($pack_type eq 'part') { $pack_part='0'; }
5631: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
5632: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
5633: }
5634: }
5635: # look for any posible extension_ match
5636: foreach my $package (@extension) {
5637: my ($package,$pack_type)=@{$package};
5638: if (defined($packagetab{"$pack_type&$name&default"})) {
5639: return $packagetab{"$pack_type&$name&default"};
5640: }
5641: if (defined($packagetab{$package."&$name&default"})) {
5642: return $packagetab{$package."&$name&default"};
5643: }
5644: }
5645: # look for a global default setting
5646: if ($do_default && defined($packagetab{"default&$name&default"})) {
5647: return $packagetab{"default&$name&default"};
5648: }
5649: return undef;
5650: }
5651:
5652: sub add_prefix_and_part {
5653: my ($prefix,$part)=@_;
5654: my $keyroot;
5655: if (defined($prefix) && $prefix !~ /^__/) {
5656: # prefix that has a part already
5657: $keyroot=$prefix;
5658: } elsif (defined($prefix)) {
5659: # prefix that is missing a part
5660: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
5661: } else {
5662: # no prefix at all
5663: if (defined($part)) { $keyroot='_'.$part; }
5664: }
5665: return $keyroot;
5666: }
5667:
5668: # ---------------------------------------------------------------- Get metadata
5669:
5670: my %metaentry;
5671: sub metadata {
5672: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
5673: $uri=&declutter($uri);
5674: # if it is a non metadata possible uri return quickly
5675: if (($uri eq '') ||
5676: (($uri =~ m|^/*adm/|) &&
5677: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
5678: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
5679: ($uri =~ m|home/[^/]+/public_html/|)) {
5680: return undef;
5681: }
5682: my $filename=$uri;
5683: $uri=~s/\.meta$//;
5684: #
5685: # Is the metadata already cached?
5686: # Look at timestamp of caching
5687: # Everything is cached by the main uri, libraries are never directly cached
5688: #
5689: if (!defined($liburi)) {
5690: my ($result,$cached)=&is_cached_new('meta',$uri);
5691: if (defined($cached)) { return $result->{':'.$what}; }
5692: }
5693: {
5694: #
5695: # Is this a recursive call for a library?
5696: #
5697: # if (! exists($metacache{$uri})) {
5698: # $metacache{$uri}={};
5699: # }
5700: if ($liburi) {
5701: $liburi=&declutter($liburi);
5702: $filename=$liburi;
5703: } else {
5704: &devalidate_cache_new('meta',$uri);
5705: undef(%metaentry);
5706: }
5707: my %metathesekeys=();
5708: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
5709: my $metastring;
5710: if ($uri !~ m -^(uploaded|editupload)/-) {
5711: my $file=&filelocation('',&clutter($filename));
5712: #push(@{$metaentry{$uri.'.file'}},$file);
5713: $metastring=&getfile($file);
5714: }
5715: my $parser=HTML::LCParser->new(\$metastring);
5716: my $token;
5717: undef %metathesekeys;
5718: while ($token=$parser->get_token) {
5719: if ($token->[0] eq 'S') {
5720: if (defined($token->[2]->{'package'})) {
5721: #
5722: # This is a package - get package info
5723: #
5724: my $package=$token->[2]->{'package'};
5725: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
5726: if (defined($token->[2]->{'id'})) {
5727: $keyroot.='_'.$token->[2]->{'id'};
5728: }
5729: if ($metaentry{':packages'}) {
5730: $metaentry{':packages'}.=','.$package.$keyroot;
5731: } else {
5732: $metaentry{':packages'}=$package.$keyroot;
5733: }
5734: foreach my $pack_entry (keys(%packagetab)) {
5735: my $part=$keyroot;
5736: $part=~s/^\_//;
5737: if ($pack_entry=~/^\Q$package\E\&/ ||
5738: $pack_entry=~/^\Q$package\E_0\&/) {
5739: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
5740: # ignore package.tab specified default values
5741: # here &package_tab_default() will fetch those
5742: if ($subp eq 'default') { next; }
5743: my $value=$packagetab{$pack_entry};
5744: my $unikey;
5745: if ($pack =~ /_0$/) {
5746: $unikey='parameter_0_'.$name;
5747: $part=0;
5748: } else {
5749: $unikey='parameter'.$keyroot.'_'.$name;
5750: }
5751: if ($subp eq 'display') {
5752: $value.=' [Part: '.$part.']';
5753: }
5754: $metaentry{':'.$unikey.'.part'}=$part;
5755: $metathesekeys{$unikey}=1;
5756: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
5757: $metaentry{':'.$unikey.'.'.$subp}=$value;
5758: }
5759: if (defined($metaentry{':'.$unikey.'.default'})) {
5760: $metaentry{':'.$unikey}=
5761: $metaentry{':'.$unikey.'.default'};
5762: }
5763: }
5764: }
5765: } else {
5766: #
5767: # This is not a package - some other kind of start tag
5768: #
5769: my $entry=$token->[1];
5770: my $unikey;
5771: if ($entry eq 'import') {
5772: $unikey='';
5773: } else {
5774: $unikey=$entry;
5775: }
5776: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
5777:
5778: if (defined($token->[2]->{'id'})) {
5779: $unikey.='_'.$token->[2]->{'id'};
5780: }
5781:
5782: if ($entry eq 'import') {
5783: #
5784: # Importing a library here
5785: #
5786: if ($depthcount<20) {
5787: my $location=$parser->get_text('/import');
5788: my $dir=$filename;
5789: $dir=~s|[^/]*$||;
5790: $location=&filelocation($dir,$location);
5791: my $metadata =
5792: &metadata($uri,'keys', $location,$unikey,
5793: $depthcount+1);
5794: foreach my $meta (split(',',$metadata)) {
5795: $metaentry{':'.$meta}=$metaentry{':'.$meta};
5796: $metathesekeys{$meta}=1;
5797: }
5798: }
5799: } else {
5800:
5801: if (defined($token->[2]->{'name'})) {
5802: $unikey.='_'.$token->[2]->{'name'};
5803: }
5804: $metathesekeys{$unikey}=1;
5805: foreach my $param (@{$token->[3]}) {
5806: $metaentry{':'.$unikey.'.'.$param} =
5807: $token->[2]->{$param};
5808: }
5809: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
5810: my $default=$metaentry{':'.$unikey.'.default'};
5811: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
5812: # only ws inside the tag, and not in default, so use default
5813: # as value
5814: $metaentry{':'.$unikey}=$default;
5815: } else {
5816: # either something interesting inside the tag or default
5817: # uninteresting
5818: $metaentry{':'.$unikey}=$internaltext;
5819: }
5820: # end of not-a-package not-a-library import
5821: }
5822: # end of not-a-package start tag
5823: }
5824: # the next is the end of "start tag"
5825: }
5826: }
5827: my ($extension) = ($uri =~ /\.(\w+)$/);
5828: foreach my $key (keys(%packagetab)) {
5829: #no specific packages #how's our extension
5830: if ($key!~/^extension_\Q$extension\E&/) { next; }
5831: &metadata_create_package_def($uri,$key,'extension_'.$extension,
5832: \%metathesekeys);
5833: }
5834: if (!exists($metaentry{':packages'})) {
5835: foreach my $key (keys(%packagetab)) {
5836: #no specific packages well let's get default then
5837: if ($key!~/^default&/) { next; }
5838: &metadata_create_package_def($uri,$key,'default',
5839: \%metathesekeys);
5840: }
5841: }
5842: # are there custom rights to evaluate
5843: if ($metaentry{':copyright'} eq 'custom') {
5844:
5845: #
5846: # Importing a rights file here
5847: #
5848: unless ($depthcount) {
5849: my $location=$metaentry{':customdistributionfile'};
5850: my $dir=$filename;
5851: $dir=~s|[^/]*$||;
5852: $location=&filelocation($dir,$location);
5853: my $rights_metadata =
5854: &metadata($uri,'keys',$location,'_rights',
5855: $depthcount+1);
5856: foreach my $rights (split(',',$rights_metadata)) {
5857: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
5858: $metathesekeys{$rights}=1;
5859: }
5860: }
5861: }
5862: # uniqifiy package listing
5863: my %seen;
5864: my @uniq_packages =
5865: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
5866: $metaentry{':packages'} = join(',',@uniq_packages);
5867:
5868: $metaentry{':keys'} = join(',',keys(%metathesekeys));
5869: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
5870: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
5871: &do_cache_new('meta',$uri,\%metaentry,60*60);
5872: # this is the end of "was not already recently cached
5873: }
5874: return $metaentry{':'.$what};
5875: }
5876:
5877: sub metadata_create_package_def {
5878: my ($uri,$key,$package,$metathesekeys)=@_;
5879: my ($pack,$name,$subp)=split(/\&/,$key);
5880: if ($subp eq 'default') { next; }
5881:
5882: if (defined($metaentry{':packages'})) {
5883: $metaentry{':packages'}.=','.$package;
5884: } else {
5885: $metaentry{':packages'}=$package;
5886: }
5887: my $value=$packagetab{$key};
5888: my $unikey;
5889: $unikey='parameter_0_'.$name;
5890: $metaentry{':'.$unikey.'.part'}=0;
5891: $$metathesekeys{$unikey}=1;
5892: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
5893: $metaentry{':'.$unikey.'.'.$subp}=$value;
5894: }
5895: if (defined($metaentry{':'.$unikey.'.default'})) {
5896: $metaentry{':'.$unikey}=
5897: $metaentry{':'.$unikey.'.default'};
5898: }
5899: }
5900:
5901: sub metadata_generate_part0 {
5902: my ($metadata,$metacache,$uri) = @_;
5903: my %allnames;
5904: foreach my $metakey (keys(%$metadata)) {
5905: if ($metakey=~/^parameter\_(.*)/) {
5906: my $part=$$metacache{':'.$metakey.'.part'};
5907: my $name=$$metacache{':'.$metakey.'.name'};
5908: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
5909: $allnames{$name}=$part;
5910: }
5911: }
5912: }
5913: foreach my $name (keys(%allnames)) {
5914: $$metadata{"parameter_0_$name"}=1;
5915: my $key=":parameter_0_$name";
5916: $$metacache{"$key.part"}='0';
5917: $$metacache{"$key.name"}=$name;
5918: $$metacache{"$key.type"}=$$metacache{':parameter_'.
5919: $allnames{$name}.'_'.$name.
5920: '.type'};
5921: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
5922: '.display'};
5923: my $expr='[Part: '.$allnames{$name}.']';
5924: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
5925: $$metacache{"$key.display"}=$olddis;
5926: }
5927: }
5928:
5929: # ------------------------------------------------- Get the title of a resource
5930:
5931: sub gettitle {
5932: my $urlsymb=shift;
5933: my $symb=&symbread($urlsymb);
5934: if ($symb) {
5935: my $key=$env{'request.course.id'}."\0".$symb;
5936: my ($result,$cached)=&is_cached_new('title',$key);
5937: if (defined($cached)) {
5938: return $result;
5939: }
5940: my ($map,$resid,$url)=&decode_symb($symb);
5941: my $title='';
5942: my %bighash;
5943: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5944: &GDBM_READER(),0640)) {
5945: my $mapid=$bighash{'map_pc_'.&clutter($map)};
5946: $title=$bighash{'title_'.$mapid.'.'.$resid};
5947: untie %bighash;
5948: }
5949: $title=~s/\&colon\;/\:/gs;
5950: if ($title) {
5951: return &do_cache_new('title',$key,$title,600);
5952: }
5953: $urlsymb=$url;
5954: }
5955: my $title=&metadata($urlsymb,'title');
5956: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
5957: return $title;
5958: }
5959:
5960: sub get_slot {
5961: my ($which,$cnum,$cdom)=@_;
5962: if (!$cnum || !$cdom) {
5963: (undef,my $courseid)=&Apache::lonxml::whichuser();
5964: $cdom=$env{'course.'.$courseid.'.domain'};
5965: $cnum=$env{'course.'.$courseid.'.num'};
5966: }
5967: my $key=join("\0",'slots',$cdom,$cnum,$which);
5968: my %slotinfo;
5969: if (exists($remembered{$key})) {
5970: $slotinfo{$which} = $remembered{$key};
5971: } else {
5972: %slotinfo=&get('slots',[$which],$cdom,$cnum);
5973: &Apache::lonhomework::showhash(%slotinfo);
5974: my ($tmp)=keys(%slotinfo);
5975: if ($tmp=~/^error:/) { return (); }
5976: $remembered{$key} = $slotinfo{$which};
5977: }
5978: if (ref($slotinfo{$which}) eq 'HASH') {
5979: return %{$slotinfo{$which}};
5980: }
5981: return $slotinfo{$which};
5982: }
5983: # ------------------------------------------------- Update symbolic store links
5984:
5985: sub symblist {
5986: my ($mapname,%newhash)=@_;
5987: $mapname=&deversion(&declutter($mapname));
5988: my %hash;
5989: if (($env{'request.course.fn'}) && (%newhash)) {
5990: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
5991: &GDBM_WRCREAT(),0640)) {
5992: foreach my $url (keys %newhash) {
5993: next if ($url eq 'last_known'
5994: && $env{'form.no_update_last_known'});
5995: $hash{declutter($url)}=&encode_symb($mapname,
5996: $newhash{$url}->[1],
5997: $newhash{$url}->[0]);
5998: }
5999: if (untie(%hash)) {
6000: return 'ok';
6001: }
6002: }
6003: }
6004: return 'error';
6005: }
6006:
6007: # --------------------------------------------------------------- Verify a symb
6008:
6009: sub symbverify {
6010: my ($symb,$thisurl)=@_;
6011: my $thisfn=$thisurl;
6012: # wrapper not part of symbs
6013: $thisfn=~s/^\/adm\/wrapper//;
6014: $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
6015: $thisfn=&declutter($thisfn);
6016: # direct jump to resource in page or to a sequence - will construct own symbs
6017: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6018: # check URL part
6019: my ($map,$resid,$url)=&decode_symb($symb);
6020:
6021: unless ($url eq $thisfn) { return 0; }
6022:
6023: $symb=&symbclean($symb);
6024: $thisurl=&deversion($thisurl);
6025: $thisfn=&deversion($thisfn);
6026:
6027: my %bighash;
6028: my $okay=0;
6029:
6030: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6031: &GDBM_READER(),0640)) {
6032: my $ids=$bighash{'ids_'.&clutter($thisurl)};
6033: unless ($ids) {
6034: $ids=$bighash{'ids_/'.$thisurl};
6035: }
6036: if ($ids) {
6037: # ------------------------------------------------------------------- Has ID(s)
6038: foreach (split(/\,/,$ids)) {
6039: my ($mapid,$resid)=split(/\./,$_);
6040: if (
6041: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6042: eq $symb) {
6043: if (($env{'request.role.adv'}) ||
6044: $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
6045: $okay=1;
6046: }
6047: }
6048: }
6049: }
6050: untie(%bighash);
6051: }
6052: return $okay;
6053: }
6054:
6055: # --------------------------------------------------------------- Clean-up symb
6056:
6057: sub symbclean {
6058: my $symb=shift;
6059: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6060: # remove version from map
6061: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
6062:
6063: # remove version from URL
6064: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
6065:
6066: # remove wrapper
6067:
6068: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
6069: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
6070: return $symb;
6071: }
6072:
6073: # ---------------------------------------------- Split symb to find map and url
6074:
6075: sub encode_symb {
6076: my ($map,$resid,$url)=@_;
6077: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6078: }
6079:
6080: sub decode_symb {
6081: my $symb=shift;
6082: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6083: my ($map,$resid,$url)=split(/___/,$symb);
6084: return (&fixversion($map),$resid,&fixversion($url));
6085: }
6086:
6087: sub fixversion {
6088: my $fn=shift;
6089: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
6090: my %bighash;
6091: my $uri=&clutter($fn);
6092: my $key=$env{'request.course.id'}.'_'.$uri;
6093: # is this cached?
6094: my ($result,$cached)=&is_cached_new('courseresversion',$key);
6095: if (defined($cached)) { return $result; }
6096: # unfortunately not cached, or expired
6097: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6098: &GDBM_READER(),0640)) {
6099: if ($bighash{'version_'.$uri}) {
6100: my $version=$bighash{'version_'.$uri};
6101: unless (($version eq 'mostrecent') ||
6102: ($version==&getversion($uri))) {
6103: $uri=~s/\.(\w+)$/\.$version\.$1/;
6104: }
6105: }
6106: untie %bighash;
6107: }
6108: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
6109: }
6110:
6111: sub deversion {
6112: my $url=shift;
6113: $url=~s/\.\d+\.(\w+)$/\.$1/;
6114: return $url;
6115: }
6116:
6117: # ------------------------------------------------------ Return symb list entry
6118:
6119: sub symbread {
6120: my ($thisfn,$donotrecurse)=@_;
6121: my $cache_str='request.symbread.cached.'.$thisfn;
6122: if (defined($env{$cache_str})) { return $env{$cache_str}; }
6123: # no filename provided? try from environment
6124: unless ($thisfn) {
6125: if ($env{'request.symb'}) {
6126: return $env{$cache_str}=&symbclean($env{'request.symb'});
6127: }
6128: $thisfn=$env{'request.filename'};
6129: }
6130: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6131: # is that filename actually a symb? Verify, clean, and return
6132: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
6133: if (&symbverify($thisfn,$1)) {
6134: return $env{$cache_str}=&symbclean($thisfn);
6135: }
6136: }
6137: $thisfn=declutter($thisfn);
6138: my %hash;
6139: my %bighash;
6140: my $syval='';
6141: if (($env{'request.course.fn'}) && ($thisfn)) {
6142: my $targetfn = $thisfn;
6143: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
6144: $targetfn = 'adm/wrapper/'.$thisfn;
6145: }
6146: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6147: $targetfn=$1;
6148: }
6149: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
6150: &GDBM_READER(),0640)) {
6151: $syval=$hash{$targetfn};
6152: untie(%hash);
6153: }
6154: # ---------------------------------------------------------- There was an entry
6155: if ($syval) {
6156: #unless ($syval=~/\_\d+$/) {
6157: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
6158: #&appenv('request.ambiguous' => $thisfn);
6159: #return $env{$cache_str}='';
6160: #}
6161: #$syval.=$1;
6162: #}
6163: } else {
6164: # ------------------------------------------------------- Was not in symb table
6165: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6166: &GDBM_READER(),0640)) {
6167: # ---------------------------------------------- Get ID(s) for current resource
6168: my $ids=$bighash{'ids_'.&clutter($thisfn)};
6169: unless ($ids) {
6170: $ids=$bighash{'ids_/'.$thisfn};
6171: }
6172: unless ($ids) {
6173: # alias?
6174: $ids=$bighash{'mapalias_'.$thisfn};
6175: }
6176: if ($ids) {
6177: # ------------------------------------------------------------------- Has ID(s)
6178: my @possibilities=split(/\,/,$ids);
6179: if ($#possibilities==0) {
6180: # ----------------------------------------------- There is only one possibility
6181: my ($mapid,$resid)=split(/\./,$ids);
6182: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6183: $resid,$thisfn);
6184: } elsif (!$donotrecurse) {
6185: # ------------------------------------------ There is more than one possibility
6186: my $realpossible=0;
6187: foreach (@possibilities) {
6188: my $file=$bighash{'src_'.$_};
6189: if (&allowed('bre',$file)) {
6190: my ($mapid,$resid)=split(/\./,$_);
6191: if ($bighash{'map_type_'.$mapid} ne 'page') {
6192: $realpossible++;
6193: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6194: $resid,$thisfn);
6195: }
6196: }
6197: }
6198: if ($realpossible!=1) { $syval=''; }
6199: } else {
6200: $syval='';
6201: }
6202: }
6203: untie(%bighash)
6204: }
6205: }
6206: if ($syval) {
6207: return $env{$cache_str}=$syval;
6208: }
6209: }
6210: &appenv('request.ambiguous' => $thisfn);
6211: return $env{$cache_str}='';
6212: }
6213:
6214: # ---------------------------------------------------------- Return random seed
6215:
6216: sub numval {
6217: my $txt=shift;
6218: $txt=~tr/A-J/0-9/;
6219: $txt=~tr/a-j/0-9/;
6220: $txt=~tr/K-T/0-9/;
6221: $txt=~tr/k-t/0-9/;
6222: $txt=~tr/U-Z/0-5/;
6223: $txt=~tr/u-z/0-5/;
6224: $txt=~s/\D//g;
6225: if ($_64bit) { if ($txt > 2**32) { return -1; } }
6226: return int($txt);
6227: }
6228:
6229: sub numval2 {
6230: my $txt=shift;
6231: $txt=~tr/A-J/0-9/;
6232: $txt=~tr/a-j/0-9/;
6233: $txt=~tr/K-T/0-9/;
6234: $txt=~tr/k-t/0-9/;
6235: $txt=~tr/U-Z/0-5/;
6236: $txt=~tr/u-z/0-5/;
6237: $txt=~s/\D//g;
6238: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6239: my $total;
6240: foreach my $val (@txts) { $total+=$val; }
6241: if ($_64bit) { if ($total > 2**32) { return -1; } }
6242: return int($total);
6243: }
6244:
6245: sub numval3 {
6246: use integer;
6247: my $txt=shift;
6248: $txt=~tr/A-J/0-9/;
6249: $txt=~tr/a-j/0-9/;
6250: $txt=~tr/K-T/0-9/;
6251: $txt=~tr/k-t/0-9/;
6252: $txt=~tr/U-Z/0-5/;
6253: $txt=~tr/u-z/0-5/;
6254: $txt=~s/\D//g;
6255: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6256: my $total;
6257: foreach my $val (@txts) { $total+=$val; }
6258: if ($_64bit) { $total=(($total<<32)>>32); }
6259: return $total;
6260: }
6261:
6262: sub digest {
6263: my ($data)=@_;
6264: my $digest=&Digest::MD5::md5($data);
6265: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6266: my ($e,$f);
6267: {
6268: use integer;
6269: $e=($a+$b);
6270: $f=($c+$d);
6271: if ($_64bit) {
6272: $e=(($e<<32)>>32);
6273: $f=(($f<<32)>>32);
6274: }
6275: }
6276: if (wantarray) {
6277: return ($e,$f);
6278: } else {
6279: my $g;
6280: {
6281: use integer;
6282: $g=($e+$f);
6283: if ($_64bit) {
6284: $g=(($g<<32)>>32);
6285: }
6286: }
6287: return $g;
6288: }
6289: }
6290:
6291: sub latest_rnd_algorithm_id {
6292: return '64bit5';
6293: }
6294:
6295: sub get_rand_alg {
6296: my ($courseid)=@_;
6297: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
6298: if ($courseid) {
6299: return $env{"course.$courseid.rndseed"};
6300: }
6301: return &latest_rnd_algorithm_id();
6302: }
6303:
6304: sub validCODE {
6305: my ($CODE)=@_;
6306: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6307: return 0;
6308: }
6309:
6310: sub getCODE {
6311: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
6312: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6313: defined($Apache::lonhomework::parsing_a_task) ) &&
6314: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
6315: return $Apache::lonhomework::history{'resource.CODE'};
6316: }
6317: return undef;
6318: }
6319:
6320: sub rndseed {
6321: my ($symb,$courseid,$domain,$username)=@_;
6322:
6323: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
6324: if (!$symb) {
6325: unless ($symb=$wsymb) { return time; }
6326: }
6327: if (!$courseid) { $courseid=$wcourseid; }
6328: if (!$domain) { $domain=$wdomain; }
6329: if (!$username) { $username=$wusername }
6330: my $which=&get_rand_alg();
6331: if (defined(&getCODE())) {
6332: if ($which eq '64bit5') {
6333: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6334: } elsif ($which eq '64bit4') {
6335: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6336: } else {
6337: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6338: }
6339: } elsif ($which eq '64bit5') {
6340: return &rndseed_64bit5($symb,$courseid,$domain,$username);
6341: } elsif ($which eq '64bit4') {
6342: return &rndseed_64bit4($symb,$courseid,$domain,$username);
6343: } elsif ($which eq '64bit3') {
6344: return &rndseed_64bit3($symb,$courseid,$domain,$username);
6345: } elsif ($which eq '64bit2') {
6346: return &rndseed_64bit2($symb,$courseid,$domain,$username);
6347: } elsif ($which eq '64bit') {
6348: return &rndseed_64bit($symb,$courseid,$domain,$username);
6349: }
6350: return &rndseed_32bit($symb,$courseid,$domain,$username);
6351: }
6352:
6353: sub rndseed_32bit {
6354: my ($symb,$courseid,$domain,$username)=@_;
6355: {
6356: use integer;
6357: my $symbchck=unpack("%32C*",$symb) << 27;
6358: my $symbseed=numval($symb) << 22;
6359: my $namechck=unpack("%32C*",$username) << 17;
6360: my $nameseed=numval($username) << 12;
6361: my $domainseed=unpack("%32C*",$domain) << 7;
6362: my $courseseed=unpack("%32C*",$courseid);
6363: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6364: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6365: #&Apache::lonxml::debug("rndseed :$num:$symb");
6366: if ($_64bit) { $num=(($num<<32)>>32); }
6367: return $num;
6368: }
6369: }
6370:
6371: sub rndseed_64bit {
6372: my ($symb,$courseid,$domain,$username)=@_;
6373: {
6374: use integer;
6375: my $symbchck=unpack("%32S*",$symb) << 21;
6376: my $symbseed=numval($symb) << 10;
6377: my $namechck=unpack("%32S*",$username);
6378:
6379: my $nameseed=numval($username) << 21;
6380: my $domainseed=unpack("%32S*",$domain) << 10;
6381: my $courseseed=unpack("%32S*",$courseid);
6382:
6383: my $num1=$symbchck+$symbseed+$namechck;
6384: my $num2=$nameseed+$domainseed+$courseseed;
6385: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6386: #&Apache::lonxml::debug("rndseed :$num:$symb");
6387: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6388: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6389: return "$num1,$num2";
6390: }
6391: }
6392:
6393: sub rndseed_64bit2 {
6394: my ($symb,$courseid,$domain,$username)=@_;
6395: {
6396: use integer;
6397: # strings need to be an even # of cahracters long, it it is odd the
6398: # last characters gets thrown away
6399: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6400: my $symbseed=numval($symb) << 10;
6401: my $namechck=unpack("%32S*",$username.' ');
6402:
6403: my $nameseed=numval($username) << 21;
6404: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6405: my $courseseed=unpack("%32S*",$courseid.' ');
6406:
6407: my $num1=$symbchck+$symbseed+$namechck;
6408: my $num2=$nameseed+$domainseed+$courseseed;
6409: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6410: #&Apache::lonxml::debug("rndseed :$num:$symb");
6411: return "$num1,$num2";
6412: }
6413: }
6414:
6415: sub rndseed_64bit3 {
6416: my ($symb,$courseid,$domain,$username)=@_;
6417: {
6418: use integer;
6419: # strings need to be an even # of cahracters long, it it is odd the
6420: # last characters gets thrown away
6421: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6422: my $symbseed=numval2($symb) << 10;
6423: my $namechck=unpack("%32S*",$username.' ');
6424:
6425: my $nameseed=numval2($username) << 21;
6426: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6427: my $courseseed=unpack("%32S*",$courseid.' ');
6428:
6429: my $num1=$symbchck+$symbseed+$namechck;
6430: my $num2=$nameseed+$domainseed+$courseseed;
6431: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6432: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
6433: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6434:
6435: return "$num1:$num2";
6436: }
6437: }
6438:
6439: sub rndseed_64bit4 {
6440: my ($symb,$courseid,$domain,$username)=@_;
6441: {
6442: use integer;
6443: # strings need to be an even # of cahracters long, it it is odd the
6444: # last characters gets thrown away
6445: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6446: my $symbseed=numval3($symb) << 10;
6447: my $namechck=unpack("%32S*",$username.' ');
6448:
6449: my $nameseed=numval3($username) << 21;
6450: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6451: my $courseseed=unpack("%32S*",$courseid.' ');
6452:
6453: my $num1=$symbchck+$symbseed+$namechck;
6454: my $num2=$nameseed+$domainseed+$courseseed;
6455: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6456: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
6457: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6458:
6459: return "$num1:$num2";
6460: }
6461: }
6462:
6463: sub rndseed_64bit5 {
6464: my ($symb,$courseid,$domain,$username)=@_;
6465: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
6466: return "$num1:$num2";
6467: }
6468:
6469: sub rndseed_CODE_64bit {
6470: my ($symb,$courseid,$domain,$username)=@_;
6471: {
6472: use integer;
6473: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6474: my $symbseed=numval2($symb);
6475: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6476: my $CODEseed=numval(&getCODE());
6477: my $courseseed=unpack("%32S*",$courseid.' ');
6478: my $num1=$symbseed+$CODEchck;
6479: my $num2=$CODEseed+$courseseed+$symbchck;
6480: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6481: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
6482: if ($_64bit) { $num1=(($num1<<32)>>32); }
6483: if ($_64bit) { $num2=(($num2<<32)>>32); }
6484: return "$num1:$num2";
6485: }
6486: }
6487:
6488: sub rndseed_CODE_64bit4 {
6489: my ($symb,$courseid,$domain,$username)=@_;
6490: {
6491: use integer;
6492: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6493: my $symbseed=numval3($symb);
6494: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6495: my $CODEseed=numval3(&getCODE());
6496: my $courseseed=unpack("%32S*",$courseid.' ');
6497: my $num1=$symbseed+$CODEchck;
6498: my $num2=$CODEseed+$courseseed+$symbchck;
6499: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6500: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
6501: if ($_64bit) { $num1=(($num1<<32)>>32); }
6502: if ($_64bit) { $num2=(($num2<<32)>>32); }
6503: return "$num1:$num2";
6504: }
6505: }
6506:
6507: sub rndseed_CODE_64bit5 {
6508: my ($symb,$courseid,$domain,$username)=@_;
6509: my $code = &getCODE();
6510: my ($num1,$num2)=&digest("$symb,$courseid,$code");
6511: return "$num1:$num2";
6512: }
6513:
6514: sub setup_random_from_rndseed {
6515: my ($rndseed)=@_;
6516: if ($rndseed =~/([,:])/) {
6517: my ($num1,$num2)=split(/[,:]/,$rndseed);
6518: &Math::Random::random_set_seed(abs($num1),abs($num2));
6519: } else {
6520: &Math::Random::random_set_seed_from_phrase($rndseed);
6521: }
6522: }
6523:
6524: sub latest_receipt_algorithm_id {
6525: return 'receipt2';
6526: }
6527:
6528: sub recunique {
6529: my $fucourseid=shift;
6530: my $unique;
6531: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6532: $unique=$env{"course.$fucourseid.internal.encseed"};
6533: } else {
6534: $unique=$perlvar{'lonReceipt'};
6535: }
6536: return unpack("%32C*",$unique);
6537: }
6538:
6539: sub recprefix {
6540: my $fucourseid=shift;
6541: my $prefix;
6542: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6543: $prefix=$env{"course.$fucourseid.internal.encpref"};
6544: } else {
6545: $prefix=$perlvar{'lonHostID'};
6546: }
6547: return unpack("%32C*",$prefix);
6548: }
6549:
6550: sub ireceipt {
6551: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
6552: my $cuname=unpack("%32C*",$funame);
6553: my $cudom=unpack("%32C*",$fudom);
6554: my $cucourseid=unpack("%32C*",$fucourseid);
6555: my $cusymb=unpack("%32C*",$fusymb);
6556: my $cunique=&recunique($fucourseid);
6557: my $cpart=unpack("%32S*",$part);
6558: my $return =&recprefix($fucourseid).'-';
6559: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
6560: $env{'request.state'} eq 'construct') {
6561: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
6562: " and ".($cpart%$cudom));
6563:
6564: $return.= ($cunique%$cuname+
6565: $cunique%$cudom+
6566: $cusymb%$cuname+
6567: $cusymb%$cudom+
6568: $cucourseid%$cuname+
6569: $cucourseid%$cudom+
6570: $cpart%$cuname+
6571: $cpart%$cudom);
6572: } else {
6573: $return.= ($cunique%$cuname+
6574: $cunique%$cudom+
6575: $cusymb%$cuname+
6576: $cusymb%$cudom+
6577: $cucourseid%$cuname+
6578: $cucourseid%$cudom);
6579: }
6580: return $return;
6581: }
6582:
6583: sub receipt {
6584: my ($part)=@_;
6585: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
6586: return &ireceipt($name,$domain,$courseid,$symb,$part);
6587: }
6588:
6589: # ------------------------------------------------------------ Serves up a file
6590: # returns either the contents of the file or
6591: # -1 if the file doesn't exist
6592: #
6593: # if the target is a file that was uploaded via DOCS,
6594: # a check will be made to see if a current copy exists on the local server,
6595: # if it does this will be served, otherwise a copy will be retrieved from
6596: # the home server for the course and stored in /home/httpd/html/userfiles on
6597: # the local server.
6598:
6599: sub getfile {
6600: my ($file) = @_;
6601: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
6602: &repcopy($file);
6603: return &readfile($file);
6604: }
6605:
6606: sub repcopy_userfile {
6607: my ($file)=@_;
6608: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
6609: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
6610: my ($cdom,$cnum,$filename) =
6611: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
6612: my ($info,$rtncode);
6613: my $uri="/uploaded/$cdom/$cnum/$filename";
6614: if (-e "$file") {
6615: my @fileinfo = stat($file);
6616: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
6617: if ($lwpresp ne 'ok') {
6618: if ($rtncode eq '404') {
6619: unlink($file);
6620: }
6621: #my $ua=new LWP::UserAgent;
6622: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
6623: #my $response=$ua->request($request);
6624: #if ($response->is_success()) {
6625: # return $response->content;
6626: # } else {
6627: # return -1;
6628: # }
6629: return -1;
6630: }
6631: if ($info < $fileinfo[9]) {
6632: return 'ok';
6633: }
6634: $info = '';
6635: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
6636: if ($lwpresp ne 'ok') {
6637: return -1;
6638: }
6639: } else {
6640: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
6641: if ($lwpresp ne 'ok') {
6642: my $ua=new LWP::UserAgent;
6643: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
6644: my $response=$ua->request($request);
6645: if ($response->is_success()) {
6646: $info=$response->content;
6647: } else {
6648: return -1;
6649: }
6650: }
6651: my @parts = ($cdom,$cnum);
6652: if ($filename =~ m|^(.+)/[^/]+$|) {
6653: push @parts, split(/\//,$1);
6654: }
6655: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
6656: foreach my $part (@parts) {
6657: $path .= '/'.$part;
6658: if (!-e $path) {
6659: mkdir($path,0770);
6660: }
6661: }
6662: }
6663: open(FILE,">$file");
6664: print FILE $info;
6665: close(FILE);
6666: return 'ok';
6667: }
6668:
6669: sub tokenwrapper {
6670: my $uri=shift;
6671: $uri=~s|^http\://([^/]+)||;
6672: $uri=~s|^/||;
6673: $env{'user.environment'}=~/\/([^\/]+)\.id/;
6674: my $token=$1;
6675: my (undef,$udom,$uname,$file)=split('/',$uri,4);
6676: if ($udom && $uname && $file) {
6677: $file=~s|(\?\.*)*$||;
6678: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
6679: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
6680: (($uri=~/\?/)?'&':'?').'token='.$token.
6681: '&tokenissued='.$perlvar{'lonHostID'};
6682: } else {
6683: return '/adm/notfound.html';
6684: }
6685: }
6686:
6687: sub getuploaded {
6688: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
6689: $uri=~s/^\///;
6690: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
6691: my $ua=new LWP::UserAgent;
6692: my $request=new HTTP::Request($reqtype,$uri);
6693: my $response=$ua->request($request);
6694: $$rtncode = $response->code;
6695: if (! $response->is_success()) {
6696: return 'failed';
6697: }
6698: if ($reqtype eq 'HEAD') {
6699: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
6700: } elsif ($reqtype eq 'GET') {
6701: $$info = $response->content;
6702: }
6703: return 'ok';
6704: }
6705:
6706: sub readfile {
6707: my $file = shift;
6708: if ( (! -e $file ) || ($file eq '') ) { return -1; };
6709: my $fh;
6710: open($fh,"<$file");
6711: my $a='';
6712: while (<$fh>) { $a .=$_; }
6713: return $a;
6714: }
6715:
6716: sub filelocation {
6717: my ($dir,$file) = @_;
6718: my $location;
6719: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
6720:
6721: if ($file =~ m-^/adm/-) {
6722: $file=~s-^/adm/wrapper/-/-;
6723: $file=~s-^/adm/coursedocs/showdoc/-/-;
6724: }
6725: if ($file=~m:^/~:) { # is a contruction space reference
6726: $location = $file;
6727: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
6728: } elsif ($file=~m:^/home/[^/]*/public_html/:) {
6729: # is a correct contruction space reference
6730: $location = $file;
6731: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
6732: my ($udom,$uname,$filename)=
6733: ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
6734: my $home=&homeserver($uname,$udom);
6735: my $is_me=0;
6736: my @ids=¤t_machine_ids();
6737: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
6738: if ($is_me) {
6739: $location=&propath($udom,$uname).
6740: '/userfiles/'.$filename;
6741: } else {
6742: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
6743: $udom.'/'.$uname.'/'.$filename;
6744: }
6745: } else {
6746: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
6747: $file=~s:^/res/:/:;
6748: if ( !( $file =~ m:^/:) ) {
6749: $location = $dir. '/'.$file;
6750: } else {
6751: $location = '/home/httpd/html/res'.$file;
6752: }
6753: }
6754: $location=~s://+:/:g; # remove duplicate /
6755: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
6756: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
6757: return $location;
6758: }
6759:
6760: sub hreflocation {
6761: my ($dir,$file)=@_;
6762: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
6763: $file=filelocation($dir,$file);
6764: } elsif ($file=~m-^/adm/-) {
6765: $file=~s-^/adm/wrapper/-/-;
6766: $file=~s-^/adm/coursedocs/showdoc/-/-;
6767: }
6768: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
6769: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
6770: } elsif ($file=~m-/home/(\w+)/public_html/-) {
6771: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
6772: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
6773: $file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
6774: -/uploaded/$1/$2/-x;
6775: }
6776: return $file;
6777: }
6778:
6779: sub current_machine_domains {
6780: my $hostname=$hostname{$perlvar{'lonHostID'}};
6781: my @domains;
6782: while( my($id, $name) = each(%hostname)) {
6783: # &logthis("-$id-$name-$hostname-");
6784: if ($hostname eq $name) {
6785: push(@domains,$hostdom{$id});
6786: }
6787: }
6788: return @domains;
6789: }
6790:
6791: sub current_machine_ids {
6792: my $hostname=$hostname{$perlvar{'lonHostID'}};
6793: my @ids;
6794: while( my($id, $name) = each(%hostname)) {
6795: # &logthis("-$id-$name-$hostname-");
6796: if ($hostname eq $name) {
6797: push(@ids,$id);
6798: }
6799: }
6800: return @ids;
6801: }
6802:
6803: # ------------------------------------------------------------- Declutters URLs
6804:
6805: sub declutter {
6806: my $thisfn=shift;
6807: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
6808: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
6809: $thisfn=~s/^\///;
6810: $thisfn=~s|^adm/wrapper/||;
6811: $thisfn=~s|^adm/coursedocs/showdoc/||;
6812: $thisfn=~s/^res\///;
6813: $thisfn=~s/\?.+$//;
6814: return $thisfn;
6815: }
6816:
6817: # ------------------------------------------------------------- Clutter up URLs
6818:
6819: sub clutter {
6820: my $thisfn='/'.&declutter(shift);
6821: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
6822: $thisfn='/res'.$thisfn;
6823: }
6824: if ($thisfn !~m|/adm|) {
6825: if ($thisfn =~ m|/ext/|) {
6826: $thisfn='/adm/wrapper'.$thisfn;
6827: } else {
6828: my ($ext) = ($thisfn =~ /\.(\w+)$/);
6829: my $embstyle=&Apache::loncommon::fileembstyle($ext);
6830: if ($embstyle eq 'ssi'
6831: || ($embstyle eq 'hdn')
6832: || ($embstyle eq 'rat')
6833: || ($embstyle eq 'prv')
6834: || ($embstyle eq 'ign')) {
6835: #do nothing with these
6836: } elsif (($embstyle eq 'img')
6837: || ($embstyle eq 'emb')
6838: || ($embstyle eq 'wrp')) {
6839: $thisfn='/adm/wrapper'.$thisfn;
6840: } elsif ($embstyle eq 'unk'
6841: && $thisfn!~/\.(sequence|page)$/) {
6842: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
6843: } else {
6844: # &logthis("Got a blank emb style");
6845: }
6846: }
6847: }
6848: return $thisfn;
6849: }
6850:
6851: sub freeze_escape {
6852: my ($value)=@_;
6853: if (ref($value)) {
6854: $value=&nfreeze($value);
6855: return '__FROZEN__'.&escape($value);
6856: }
6857: return &escape($value);
6858: }
6859:
6860:
6861: sub thaw_unescape {
6862: my ($value)=@_;
6863: if ($value =~ /^__FROZEN__/) {
6864: substr($value,0,10,undef);
6865: $value=&unescape($value);
6866: return &thaw($value);
6867: }
6868: return &unescape($value);
6869: }
6870:
6871: sub correct_line_ends {
6872: my ($result)=@_;
6873: $$result =~s/\r\n/\n/mg;
6874: $$result =~s/\r/\n/mg;
6875: }
6876: # ================================================================ Main Program
6877:
6878: sub goodbye {
6879: &logthis("Starting Shut down");
6880: #not converted to using infrastruture and probably shouldn't be
6881: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
6882: #converted
6883: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
6884: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
6885: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
6886: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
6887: #1.1 only
6888: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
6889: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
6890: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
6891: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
6892: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
6893: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
6894: &logthis(sprintf("%-20s is %s",'hits',$hits));
6895: &flushcourselogs();
6896: &logthis("Shutting down");
6897: }
6898:
6899: BEGIN {
6900: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
6901: unless ($readit) {
6902: {
6903: # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
6904: open(my $config,"</etc/httpd/conf/loncapa.conf");
6905:
6906: while (my $configline=<$config>) {
6907: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
6908: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
6909: chomp($varvalue);
6910: $perlvar{$varname}=$varvalue;
6911: }
6912: }
6913: close($config);
6914: }
6915: {
6916: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
6917:
6918: while (my $configline=<$config>) {
6919: if ($configline =~ /^[^\#]*PerlSetVar/) {
6920: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
6921: chomp($varvalue);
6922: $perlvar{$varname}=$varvalue;
6923: }
6924: }
6925: close($config);
6926: }
6927:
6928: # ------------------------------------------------------------ Read domain file
6929: {
6930: %domaindescription = ();
6931: %domain_auth_def = ();
6932: %domain_auth_arg_def = ();
6933: my $fh;
6934: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
6935: while (<$fh>) {
6936: next if (/^(\#|\s*$)/);
6937: # next if /^\#/;
6938: chomp;
6939: my ($domain, $domain_description, $def_auth, $def_auth_arg,
6940: $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
6941: $domain_auth_def{$domain}=$def_auth;
6942: $domain_auth_arg_def{$domain}=$def_auth_arg;
6943: $domaindescription{$domain}=$domain_description;
6944: $domain_lang_def{$domain}=$def_lang;
6945: $domain_city{$domain}=$city;
6946: $domain_longi{$domain}=$longi;
6947: $domain_lati{$domain}=$lati;
6948: $domain_primary{$domain}=$primary;
6949:
6950: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
6951: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
6952: }
6953: }
6954: close ($fh);
6955: }
6956:
6957:
6958: # ------------------------------------------------------------- Read hosts file
6959: {
6960: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
6961:
6962: while (my $configline=<$config>) {
6963: next if ($configline =~ /^(\#|\s*$)/);
6964: chomp($configline);
6965: my ($id,$domain,$role,$name)=split(/:/,$configline);
6966: $name=~s/\s//g;
6967: if ($id && $domain && $role && $name) {
6968: $hostname{$id}=$name;
6969: $hostdom{$id}=$domain;
6970: if ($role eq 'library') { $libserv{$id}=$name; }
6971: }
6972: }
6973: close($config);
6974: # FIXME: dev server don't want this, production servers _do_ want this
6975: #&get_iphost();
6976: }
6977:
6978: sub get_iphost {
6979: if (%iphost) { return %iphost; }
6980: my %name_to_ip;
6981: foreach my $id (keys(%hostname)) {
6982: my $name=$hostname{$id};
6983: my $ip;
6984: if (!exists($name_to_ip{$name})) {
6985: $ip = gethostbyname($name);
6986: if (!$ip || length($ip) ne 4) {
6987: &logthis("Skipping host $id name $name no IP found\n");
6988: next;
6989: }
6990: $ip=inet_ntoa($ip);
6991: $name_to_ip{$name} = $ip;
6992: } else {
6993: $ip = $name_to_ip{$name};
6994: }
6995: push(@{$iphost{$ip}},$id);
6996: }
6997: return %iphost;
6998: }
6999:
7000: # ------------------------------------------------------ Read spare server file
7001: {
7002: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
7003:
7004: while (my $configline=<$config>) {
7005: chomp($configline);
7006: if ($configline) {
7007: $spareid{$configline}=1;
7008: }
7009: }
7010: close($config);
7011: }
7012: # ------------------------------------------------------------ Read permissions
7013: {
7014: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
7015:
7016: while (my $configline=<$config>) {
7017: chomp($configline);
7018: if ($configline) {
7019: my ($role,$perm)=split(/ /,$configline);
7020: if ($perm ne '') { $pr{$role}=$perm; }
7021: }
7022: }
7023: close($config);
7024: }
7025:
7026: # -------------------------------------------- Read plain texts for permissions
7027: {
7028: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
7029:
7030: while (my $configline=<$config>) {
7031: chomp($configline);
7032: if ($configline) {
7033: my ($short,@plain)=split(/:/,$configline);
7034: %{$prp{$short}} = ();
7035: if (@plain > 0) {
7036: $prp{$short}{'std'} = $plain[0];
7037: for (my $i=1; $i<@plain; $i++) {
7038: $prp{$short}{'alt'.$i} = $plain[$i];
7039: }
7040: }
7041: }
7042: }
7043: close($config);
7044: }
7045:
7046: # ---------------------------------------------------------- Read package table
7047: {
7048: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
7049:
7050: while (my $configline=<$config>) {
7051: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
7052: chomp($configline);
7053: my ($short,$plain)=split(/:/,$configline);
7054: my ($pack,$name)=split(/\&/,$short);
7055: if ($plain ne '') {
7056: $packagetab{$pack.'&'.$name.'&name'}=$name;
7057: $packagetab{$short}=$plain;
7058: }
7059: }
7060: close($config);
7061: }
7062:
7063: # ------------- set up temporary directory
7064: {
7065: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7066:
7067: }
7068:
7069: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
7070:
7071: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
7072: $dumpcount=0;
7073:
7074: &logtouch();
7075: &logthis('<font color="yellow">INFO: Read configuration</font>');
7076: $readit=1;
7077: {
7078: use integer;
7079: my $test=(2**32)+1;
7080: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
7081: &logthis(" Detected 64bit platform ($_64bit)");
7082: }
7083: }
7084: }
7085:
7086: 1;
7087: __END__
7088:
7089: =pod
7090:
7091: =head1 NAME
7092:
7093: Apache::lonnet - Subroutines to ask questions about things in the network.
7094:
7095: =head1 SYNOPSIS
7096:
7097: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
7098:
7099: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7100:
7101: Common parameters:
7102:
7103: =over 4
7104:
7105: =item *
7106:
7107: $uname : an internal username (if $cname expecting a course Id specifically)
7108:
7109: =item *
7110:
7111: $udom : a domain (if $cdom expecting a course's domain specifically)
7112:
7113: =item *
7114:
7115: $symb : a resource instance identifier
7116:
7117: =item *
7118:
7119: $namespace : the name of a .db file that contains the data needed or
7120: being set.
7121:
7122: =back
7123:
7124: =head1 OVERVIEW
7125:
7126: lonnet provides subroutines which interact with the
7127: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7128: about classes, users, and resources.
7129:
7130: For many of these objects you can also use this to store data about
7131: them or modify them in various ways.
7132:
7133: =head2 Symbs
7134:
7135: To identify a specific instance of a resource, LON-CAPA uses symbols
7136: or "symbs"X<symb>. These identifiers are built from the URL of the
7137: map, the resource number of the resource in the map, and the URL of
7138: the resource itself. The latter is somewhat redundant, but might help
7139: if maps change.
7140:
7141: An example is
7142:
7143: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7144:
7145: The respective map entry is
7146:
7147: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7148: title="Problem 2">
7149: </resource>
7150:
7151: Symbs are used by the random number generator, as well as to store and
7152: restore data specific to a certain instance of for example a problem.
7153:
7154: =head2 Storing And Retrieving Data
7155:
7156: X<store()>X<cstore()>X<restore()>Three of the most important functions
7157: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7158: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7159: is is the non-critical message twin of cstore. These functions are for
7160: handlers to store a perl hash to a user's permanent data space in an
7161: easy manner, and to retrieve it again on another call. It is expected
7162: that a handler would use this once at the beginning to retrieve data,
7163: and then again once at the end to send only the new data back.
7164:
7165: The data is stored in the user's data directory on the user's
7166: homeserver under the ID of the course.
7167:
7168: The hash that is returned by restore will have all of the previous
7169: value for all of the elements of the hash.
7170:
7171: Example:
7172:
7173: #creating a hash
7174: my %hash;
7175: $hash{'foo'}='bar';
7176:
7177: #storing it
7178: &Apache::lonnet::cstore(\%hash);
7179:
7180: #changing a value
7181: $hash{'foo'}='notbar';
7182:
7183: #adding a new value
7184: $hash{'bar'}='foo';
7185: &Apache::lonnet::cstore(\%hash);
7186:
7187: #retrieving the hash
7188: my %history=&Apache::lonnet::restore();
7189:
7190: #print the hash
7191: foreach my $key (sort(keys(%history))) {
7192: print("\%history{$key} = $history{$key}");
7193: }
7194:
7195: Will print out:
7196:
7197: %history{1:foo} = bar
7198: %history{1:keys} = foo:timestamp
7199: %history{1:timestamp} = 990455579
7200: %history{2:bar} = foo
7201: %history{2:foo} = notbar
7202: %history{2:keys} = foo:bar:timestamp
7203: %history{2:timestamp} = 990455580
7204: %history{bar} = foo
7205: %history{foo} = notbar
7206: %history{timestamp} = 990455580
7207: %history{version} = 2
7208:
7209: Note that the special hash entries C<keys>, C<version> and
7210: C<timestamp> were added to the hash. C<version> will be equal to the
7211: total number of versions of the data that have been stored. The
7212: C<timestamp> attribute will be the UNIX time the hash was
7213: stored. C<keys> is available in every historical section to list which
7214: keys were added or changed at a specific historical revision of a
7215: hash.
7216:
7217: B<Warning>: do not store the hash that restore returns directly. This
7218: will cause a mess since it will restore the historical keys as if the
7219: were new keys. I.E. 1:foo will become 1:1:foo etc.
7220:
7221: Calling convention:
7222:
7223: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
7224: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
7225:
7226: For more detailed information, see lonnet specific documentation.
7227:
7228: =head1 RETURN MESSAGES
7229:
7230: =over 4
7231:
7232: =item * B<con_lost>: unable to contact remote host
7233:
7234: =item * B<con_delayed>: unable to contact remote host, message will be delivered
7235: when the connection is brought back up
7236:
7237: =item * B<con_failed>: unable to contact remote host and unable to save message
7238: for later delivery
7239:
7240: =item * B<error:>: an error a occured, a description of the error follows the :
7241:
7242: =item * B<no_such_host>: unable to fund a host associated with the user/domain
7243: that was requested
7244:
7245: =back
7246:
7247: =head1 PUBLIC SUBROUTINES
7248:
7249: =head2 Session Environment Functions
7250:
7251: =over 4
7252:
7253: =item *
7254: X<appenv()>
7255: B<appenv(%hash)>: the value of %hash is written to
7256: the user envirnoment file, and will be restored for each access this
7257: user makes during this session, also modifies the %env for the current
7258: process
7259:
7260: =item *
7261: X<delenv()>
7262: B<delenv($regexp)>: removes all items from the session
7263: environment file that matches the regular expression in $regexp. The
7264: values are also delted from the current processes %env.
7265:
7266: =back
7267:
7268: =head2 User Information
7269:
7270: =over 4
7271:
7272: =item *
7273: X<queryauthenticate()>
7274: B<queryauthenticate($uname,$udom)>: try to determine user's current
7275: authentication scheme
7276:
7277: =item *
7278: X<authenticate()>
7279: B<authenticate($uname,$upass,$udom)>: try to
7280: authenticate user from domain's lib servers (first use the current
7281: one). C<$upass> should be the users password.
7282:
7283: =item *
7284: X<homeserver()>
7285: B<homeserver($uname,$udom)>: find the server which has
7286: the user's directory and files (there must be only one), this caches
7287: the answer, and also caches if there is a borken connection.
7288:
7289: =item *
7290: X<idget()>
7291: B<idget($udom,@ids)>: find the usernames behind a list of IDs
7292: (IDs are a unique resource in a domain, there must be only 1 ID per
7293: username, and only 1 username per ID in a specific domain) (returns
7294: hash: id=>name,id=>name)
7295:
7296: =item *
7297: X<idrget()>
7298: B<idrget($udom,@unames)>: find the IDs behind a list of
7299: usernames (returns hash: name=>id,name=>id)
7300:
7301: =item *
7302: X<idput()>
7303: B<idput($udom,%ids)>: store away a list of names and associated IDs
7304:
7305: =item *
7306: X<rolesinit()>
7307: B<rolesinit($udom,$username,$authhost)>: get user privileges
7308:
7309: =item *
7310: X<getsection()>
7311: B<getsection($udom,$uname,$cname)>: finds the section of student in the
7312: course $cname, return section name/number or '' for "not in course"
7313: and '-1' for "no section"
7314:
7315: =item *
7316: X<userenvironment()>
7317: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
7318: passed in @what from the requested user's environment, returns a hash
7319:
7320: =back
7321:
7322: =head2 User Roles
7323:
7324: =over 4
7325:
7326: =item *
7327:
7328: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
7329: actions
7330: F: full access
7331: U,I,K: authentication modes (cxx only)
7332: '': forbidden
7333: 1: user needs to choose course
7334: 2: browse allowed
7335:
7336: =item *
7337:
7338: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
7339: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
7340: and course level
7341:
7342: =item *
7343:
7344: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
7345: explanation of a user role term
7346:
7347: =back
7348:
7349: =head2 User Modification
7350:
7351: =over 4
7352:
7353: =item *
7354:
7355: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
7356: user for the level given by URL. Optional start and end dates (leave empty
7357: string or zero for "no date")
7358:
7359: =item *
7360:
7361: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
7362: change a users, password, possible return values are: ok,
7363: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
7364: refused
7365:
7366: =item *
7367:
7368: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
7369:
7370: =item *
7371:
7372: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
7373: modify user
7374:
7375: =item *
7376:
7377: modifystudent
7378:
7379: modify a students enrollment and identification information.
7380: The course id is resolved based on the current users environment.
7381: This means the envoking user must be a course coordinator or otherwise
7382: associated with a course.
7383:
7384: This call is essentially a wrapper for lonnet::modifyuser and
7385: lonnet::modify_student_enrollment
7386:
7387: Inputs:
7388:
7389: =over 4
7390:
7391: =item B<$udom> Students loncapa domain
7392:
7393: =item B<$uname> Students loncapa login name
7394:
7395: =item B<$uid> Students id/student number
7396:
7397: =item B<$umode> Students authentication mode
7398:
7399: =item B<$upass> Students password
7400:
7401: =item B<$first> Students first name
7402:
7403: =item B<$middle> Students middle name
7404:
7405: =item B<$last> Students last name
7406:
7407: =item B<$gene> Students generation
7408:
7409: =item B<$usec> Students section in course
7410:
7411: =item B<$end> Unix time of the roles expiration
7412:
7413: =item B<$start> Unix time of the roles start date
7414:
7415: =item B<$forceid> If defined, allow $uid to be changed
7416:
7417: =item B<$desiredhome> server to use as home server for student
7418:
7419: =back
7420:
7421: =item *
7422:
7423: modify_student_enrollment
7424:
7425: Change a students enrollment status in a class. The environment variable
7426: 'role.request.course' must be defined for this function to proceed.
7427:
7428: Inputs:
7429:
7430: =over 4
7431:
7432: =item $udom, students domain
7433:
7434: =item $uname, students name
7435:
7436: =item $uid, students user id
7437:
7438: =item $first, students first name
7439:
7440: =item $middle
7441:
7442: =item $last
7443:
7444: =item $gene
7445:
7446: =item $usec
7447:
7448: =item $end
7449:
7450: =item $start
7451:
7452: =back
7453:
7454:
7455: =item *
7456:
7457: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
7458: custom role; give a custom role to a user for the level given by URL. Specify
7459: name and domain of role author, and role name
7460:
7461: =item *
7462:
7463: revokerole($udom,$uname,$url,$role) : revoke a role for url
7464:
7465: =item *
7466:
7467: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
7468:
7469: =back
7470:
7471: =head2 Course Infomation
7472:
7473: =over 4
7474:
7475: =item *
7476:
7477: coursedescription($courseid) : returns a hash of information about the
7478: specified course id, including all environment settings for the
7479: course, the description of the course will be in the hash under the
7480: key 'description'
7481:
7482: =item *
7483:
7484: resdata($name,$domain,$type,@which) : request for current parameter
7485: setting for a specific $type, where $type is either 'course' or 'user',
7486: @what should be a list of parameters to ask about. This routine caches
7487: answers for 5 minutes.
7488:
7489: =back
7490:
7491: =head2 Course Modification
7492:
7493: =over 4
7494:
7495: =item *
7496:
7497: writecoursepref($courseid,%prefs) : write preferences (environment
7498: database) for a course
7499:
7500: =item *
7501:
7502: createcourse($udom,$description,$url) : make/modify course
7503:
7504: =back
7505:
7506: =head2 Resource Subroutines
7507:
7508: =over 4
7509:
7510: =item *
7511:
7512: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
7513:
7514: =item *
7515:
7516: repcopy($filename) : subscribes to the requested file, and attempts to
7517: replicate from the owning library server, Might return
7518: 'unavailable', 'not_found', 'forbidden', 'ok', or
7519: 'bad_request', also attempts to grab the metadata for the
7520: resource. Expects the local filesystem pathname
7521: (/home/httpd/html/res/....)
7522:
7523: =back
7524:
7525: =head2 Resource Information
7526:
7527: =over 4
7528:
7529: =item *
7530:
7531: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
7532: a vairety of different possible values, $varname should be a request
7533: string, and the other parameters can be used to specify who and what
7534: one is asking about.
7535:
7536: Possible values for $varname are environment.lastname (or other item
7537: from the envirnment hash), user.name (or someother aspect about the
7538: user), resource.0.maxtries (or some other part and parameter of a
7539: resource)
7540:
7541: =item *
7542:
7543: directcondval($number) : get current value of a condition; reads from a state
7544: string
7545:
7546: =item *
7547:
7548: condval($condidx) : value of condition index based on state
7549:
7550: =item *
7551:
7552: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
7553: resource's metadata, $what should be either a specific key, or either
7554: 'keys' (to get a list of possible keys) or 'packages' to get a list of
7555: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
7556:
7557: this function automatically caches all requests
7558:
7559: =item *
7560:
7561: metadata_query($query,$custom,$customshow) : make a metadata query against the
7562: network of library servers; returns file handle of where SQL and regex results
7563: will be stored for query
7564:
7565: =item *
7566:
7567: symbread($filename) : return symbolic list entry (filename argument optional);
7568: returns the data handle
7569:
7570: =item *
7571:
7572: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
7573: a possible symb for the URL in $thisfn, and if is an encryypted
7574: resource that the user accessed using /enc/ returns a 1 on success, 0
7575: on failure, user must be in a course, as it assumes the existance of
7576: the course initial hash, and uses $env('request.course.id'}
7577:
7578:
7579: =item *
7580:
7581: symbclean($symb) : removes versions numbers from a symb, returns the
7582: cleaned symb
7583:
7584: =item *
7585:
7586: is_on_map($uri) : checks if the $uri is somewhere on the current
7587: course map, user must be in a course for it to work.
7588:
7589: =item *
7590:
7591: numval($salt) : return random seed value (addend for rndseed)
7592:
7593: =item *
7594:
7595: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
7596: a random seed, all arguments are optional, if they aren't sent it uses the
7597: environment to derive them. Note: if symb isn't sent and it can't get one
7598: from &symbread it will use the current time as its return value
7599:
7600: =item *
7601:
7602: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
7603: unfakeable, receipt
7604:
7605: =item *
7606:
7607: receipt() : API to ireceipt working off of env values; given out to users
7608:
7609: =item *
7610:
7611: countacc($url) : count the number of accesses to a given URL
7612:
7613: =item *
7614:
7615: 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
7616:
7617: =item *
7618:
7619: 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)
7620:
7621: =item *
7622:
7623: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
7624:
7625: =item *
7626:
7627: devalidate($symb) : devalidate temporary spreadsheet calculations,
7628: forcing spreadsheet to reevaluate the resource scores next time.
7629:
7630: =back
7631:
7632: =head2 Storing/Retreiving Data
7633:
7634: =over 4
7635:
7636: =item *
7637:
7638: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
7639: for this url; hashref needs to be given and should be a \%hashname; the
7640: remaining args aren't required and if they aren't passed or are '' they will
7641: be derived from the env
7642:
7643: =item *
7644:
7645: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
7646: uses critical subroutine
7647:
7648: =item *
7649:
7650: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
7651: all args are optional
7652:
7653: =item *
7654:
7655: dumpstore($namespace,$udom,$uname,$regexp,$range) :
7656: dumps the complete (or key matching regexp) namespace into a hash
7657: ($udom, $uname, $regexp, $range are optional) for a namespace that is
7658: normally &store()ed into
7659:
7660: $range should be either an integer '100' (give me the first 100
7661: matching records)
7662: or be two integers sperated by a - with no spaces
7663: '30-50' (give me the 30th through the 50th matching
7664: records)
7665:
7666:
7667: =item *
7668:
7669: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
7670: replaces a &store() version of data with a replacement set of data
7671: for a particular resource in a namespace passed in the $storehash hash
7672: reference
7673:
7674: =item *
7675:
7676: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
7677: works very similar to store/cstore, but all data is stored in a
7678: temporary location and can be reset using tmpreset, $storehash should
7679: be a hash reference, returns nothing on success
7680:
7681: =item *
7682:
7683: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
7684: similar to restore, but all data is stored in a temporary location and
7685: can be reset using tmpreset. Returns a hash of values on success,
7686: error string otherwise.
7687:
7688: =item *
7689:
7690: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
7691: deltes all keys for $symb form the temporary storage hash.
7692:
7693: =item *
7694:
7695: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
7696: reference filled in from namesp ($udom and $uname are optional)
7697:
7698: =item *
7699:
7700: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
7701: namesp ($udom and $uname are optional)
7702:
7703: =item *
7704:
7705: dump($namespace,$udom,$uname,$regexp,$range) :
7706: dumps the complete (or key matching regexp) namespace into a hash
7707: ($udom, $uname, $regexp, $range are optional)
7708:
7709: $range should be either an integer '100' (give me the first 100
7710: matching records)
7711: or be two integers sperated by a - with no spaces
7712: '30-50' (give me the 30th through the 50th matching
7713: records)
7714: =item *
7715:
7716: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
7717: $store can be a scalar, an array reference, or if the amount to be
7718: incremented is > 1, a hash reference.
7719:
7720: ($udom and $uname are optional)
7721:
7722: =item *
7723:
7724: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
7725: ($udom and $uname are optional)
7726:
7727: =item *
7728:
7729: cput($namespace,$storehash,$udom,$uname) : critical put
7730: ($udom and $uname are optional)
7731:
7732: =item *
7733:
7734: newput($namespace,$storehash,$udom,$uname) :
7735:
7736: Attempts to store the items in the $storehash, but only if they don't
7737: currently exist, if this succeeds you can be certain that you have
7738: successfully created a new key value pair in the $namespace db.
7739:
7740:
7741: Args:
7742: $namespace: name of database to store values to
7743: $storehash: hashref to store to the db
7744: $udom: (optional) domain of user containing the db
7745: $uname: (optional) name of user caontaining the db
7746:
7747: Returns:
7748: 'ok' -> succeeded in storing all keys of $storehash
7749: 'key_exists: <key>' -> failed to anything out of $storehash, as at
7750: least <key> already existed in the db (other
7751: requested keys may also already exist)
7752: 'error: <msg>' -> unable to tie the DB or other erorr occured
7753: 'con_lost' -> unable to contact request server
7754: 'refused' -> action was not allowed by remote machine
7755:
7756:
7757: =item *
7758:
7759: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
7760: reference filled in from namesp (encrypts the return communication)
7761: ($udom and $uname are optional)
7762:
7763: =item *
7764:
7765: log($udom,$name,$home,$message) : write to permanent log for user; use
7766: critical subroutine
7767:
7768: =back
7769:
7770: =head2 Network Status Functions
7771:
7772: =over 4
7773:
7774: =item *
7775:
7776: dirlist($uri) : return directory list based on URI
7777:
7778: =item *
7779:
7780: spareserver() : find server with least workload from spare.tab
7781:
7782: =back
7783:
7784: =head2 Apache Request
7785:
7786: =over 4
7787:
7788: =item *
7789:
7790: ssi($url,%hash) : server side include, does a complete request cycle on url to
7791: localhost, posts hash
7792:
7793: =back
7794:
7795: =head2 Data to String to Data
7796:
7797: =over 4
7798:
7799: =item *
7800:
7801: hash2str(%hash) : convert a hash into a string complete with escaping and '='
7802: and '&' separators, supports elements that are arrayrefs and hashrefs
7803:
7804: =item *
7805:
7806: hashref2str($hashref) : convert a hashref into a string complete with
7807: escaping and '=' and '&' separators, supports elements that are
7808: arrayrefs and hashrefs
7809:
7810: =item *
7811:
7812: arrayref2str($arrayref) : convert an arrayref into a string complete
7813: with escaping and '&' separators, supports elements that are arrayrefs
7814: and hashrefs
7815:
7816: =item *
7817:
7818: str2hash($string) : convert string to hash using unescaping and
7819: splitting on '=' and '&', supports elements that are arrayrefs and
7820: hashrefs
7821:
7822: =item *
7823:
7824: str2array($string) : convert string to hash using unescaping and
7825: splitting on '&', supports elements that are arrayrefs and hashrefs
7826:
7827: =back
7828:
7829: =head2 Logging Routines
7830:
7831: =over 4
7832:
7833: These routines allow one to make log messages in the lonnet.log and
7834: lonnet.perm logfiles.
7835:
7836: =item *
7837:
7838: logtouch() : make sure the logfile, lonnet.log, exists
7839:
7840: =item *
7841:
7842: logthis() : append message to the normal lonnet.log file, it gets
7843: preiodically rolled over and deleted.
7844:
7845: =item *
7846:
7847: logperm() : append a permanent message to lonnet.perm.log, this log
7848: file never gets deleted by any automated portion of the system, only
7849: messages of critical importance should go in here.
7850:
7851: =back
7852:
7853: =head2 General File Helper Routines
7854:
7855: =over 4
7856:
7857: =item *
7858:
7859: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
7860: (a) files in /uploaded
7861: (i) If a local copy of the file exists -
7862: compares modification date of local copy with last-modified date for
7863: definitive version stored on home server for course. If local copy is
7864: stale, requests a new version from the home server and stores it.
7865: If the original has been removed from the home server, then local copy
7866: is unlinked.
7867: (ii) If local copy does not exist -
7868: requests the file from the home server and stores it.
7869:
7870: If $caller is 'uploadrep':
7871: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
7872: for request for files originally uploaded via DOCS.
7873: - returns 'ok' if fresh local copy now available, -1 otherwise.
7874:
7875: Otherwise:
7876: This indicates a call from the content generation phase of the request.
7877: - returns the entire contents of the file or -1.
7878:
7879: (b) files in /res
7880: - returns the entire contents of a file or -1;
7881: it properly subscribes to and replicates the file if neccessary.
7882:
7883:
7884: =item *
7885:
7886: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
7887: reference
7888:
7889: returns either a stat() list of data about the file or an empty list
7890: if the file doesn't exist or couldn't find out about it (connection
7891: problems or user unknown)
7892:
7893: =item *
7894:
7895: filelocation($dir,$file) : returns file system location of a file
7896: based on URI; meant to be "fairly clean" absolute reference, $dir is a
7897: directory that relative $file lookups are to looked in ($dir of /a/dir
7898: and a file of ../bob will become /a/bob)
7899:
7900: =item *
7901:
7902: hreflocation($dir,$file) : returns file system location or a URL; same as
7903: filelocation except for hrefs
7904:
7905: =item *
7906:
7907: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
7908:
7909: =back
7910:
7911: =head2 Usererfile file routines (/uploaded*)
7912:
7913: =over 4
7914:
7915: =item *
7916:
7917: userfileupload(): main rotine for putting a file in a user or course's
7918: filespace, arguments are,
7919:
7920: formname - required - this is the name of the element in $env where the
7921: filename, and the contents of the file to create/modifed exist
7922: the filename is in $env{'form.'.$formname.'.filename'} and the
7923: contents of the file is located in $env{'form.'.$formname}
7924: coursedoc - if true, store the file in the course of the active role
7925: of the current user
7926: subdir - required - subdirectory to put the file in under ../userfiles/
7927: if undefined, it will be placed in "unknown"
7928:
7929: (This routine calls clean_filename() to remove any dangerous
7930: characters from the filename, and then calls finuserfileupload() to
7931: complete the transaction)
7932:
7933: returns either the url of the uploaded file (/uploaded/....) if successful
7934: and /adm/notfound.html if unsuccessful
7935:
7936: =item *
7937:
7938: clean_filename(): routine for cleaing a filename up for storage in
7939: userfile space, argument is:
7940:
7941: filename - proposed filename
7942:
7943: returns: the new clean filename
7944:
7945: =item *
7946:
7947: finishuserfileupload(): routine that creaes and sends the file to
7948: userspace, probably shouldn't be called directly
7949:
7950: docuname: username or courseid of destination for the file
7951: docudom: domain of user/course of destination for the file
7952: formname: same as for userfileupload()
7953: fname: filename (inculding subdirectories) for the file
7954:
7955: returns either the url of the uploaded file (/uploaded/....) if successful
7956: and /adm/notfound.html if unsuccessful
7957:
7958: =item *
7959:
7960: renameuserfile(): renames an existing userfile to a new name
7961:
7962: Args:
7963: docuname: username or courseid of destination for the file
7964: docudom: domain of user/course of destination for the file
7965: old: current file name (including any subdirs under userfiles)
7966: new: desired file name (including any subdirs under userfiles)
7967:
7968: =item *
7969:
7970: mkdiruserfile(): creates a directory is a userfiles dir
7971:
7972: Args:
7973: docuname: username or courseid of destination for the file
7974: docudom: domain of user/course of destination for the file
7975: dir: dir to create (including any subdirs under userfiles)
7976:
7977: =item *
7978:
7979: removeuserfile(): removes a file that exists in userfiles
7980:
7981: Args:
7982: docuname: username or courseid of destination for the file
7983: docudom: domain of user/course of destination for the file
7984: fname: filname to delete (including any subdirs under userfiles)
7985:
7986: =item *
7987:
7988: removeuploadedurl(): convience function for removeuserfile()
7989:
7990: Args:
7991: url: a full /uploaded/... url to delete
7992:
7993: =item *
7994:
7995: get_portfile_permissions():
7996: Args:
7997: domain: domain of user or course contain the portfolio files
7998: user: name of user or num of course contain the portfolio files
7999: Returns:
8000: hashref of a dump of the proper file_permissions.db
8001:
8002:
8003: =item *
8004:
8005: get_access_controls():
8006:
8007: Args:
8008: current_permissions: the hash ref returned from get_portfile_permissions()
8009: group: (optional) the group you want the files associated with
8010: file: (optional) the file you want access info on
8011:
8012: Returns:
8013: a hash (keys are file names) of hashes containing
8014: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8015: values are XML containing access control settings (see below)
8016:
8017: Internal notes:
8018:
8019: access controls are stored in file_permissions.db as key=value pairs.
8020: key -> path to file/file_name\0uniqueID:scope_end_start
8021: where scope -> public,guest,course,group,domains or users.
8022: end -> UNIX time for end of access (0 -> no end date)
8023: start -> UNIX time for start of access
8024:
8025: value -> XML description of access control
8026: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8027: <start></start>
8028: <end></end>
8029:
8030: <password></password> for scope type = guest
8031:
8032: <domain></domain> for scope type = course or group
8033: <number></number>
8034: <roles id="">
8035: <role></role>
8036: <access></access>
8037: <section></section>
8038: <group></group>
8039: </roles>
8040:
8041: <dom></dom> for scope type = domains
8042:
8043: <users> for scope type = users
8044: <user>
8045: <uname></uname>
8046: <udom></udom>
8047: </user>
8048: </users>
8049: </scope>
8050:
8051: Access data is also aggregated for each file in an additional key=value pair:
8052: key -> path to file/file_name\0accesscontrol
8053: value -> reference to hash
8054: hash contains key = value pairs
8055: where key = uniqueID:scope_end_start
8056: value = UNIX time record was last updated
8057:
8058: Used to improve speed of look-ups of access controls for each file.
8059:
8060: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8061:
8062: parse_access_controls():
8063:
8064: Parses XML of an access control record
8065: Args
8066: 1. Text string (XML) of access comtrol record
8067:
8068: Returns:
8069: 1. Hash of access control settings.
8070:
8071: modify_access_controls():
8072:
8073: Modifies access controls for a portfolio file
8074: Args
8075: 1. file name
8076: 2. reference to hash of required changes,
8077: 3. domain
8078: 4. username
8079: where domain,username are the domain of the portfolio owner
8080: (either a user or a course)
8081:
8082: Returns:
8083: 1. result of additions or updates ('ok' or 'error', with error message).
8084: 2. result of deletions ('ok' or 'error', with error message).
8085: 3. reference to hash of any new or updated access controls.
8086: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8087: key = integer (inbound ID)
8088: value = uniqueID
8089:
8090: =back
8091:
8092: =head2 HTTP Helper Routines
8093:
8094: =over 4
8095:
8096: =item *
8097:
8098: escape() : unpack non-word characters into CGI-compatible hex codes
8099:
8100: =item *
8101:
8102: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8103:
8104: =back
8105:
8106: =head1 PRIVATE SUBROUTINES
8107:
8108: =head2 Underlying communication routines (Shouldn't call)
8109:
8110: =over 4
8111:
8112: =item *
8113:
8114: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8115:
8116: =item *
8117:
8118: reply() : uses subreply to send a message to remote machine, logs all failures
8119:
8120: =item *
8121:
8122: critical() : passes a critical message to another server; if cannot
8123: get through then place message in connection buffer directory and
8124: returns con_delayed, if incapable of saving message, returns
8125: con_failed
8126:
8127: =item *
8128:
8129: reconlonc() : tries to reconnect lonc client processes.
8130:
8131: =back
8132:
8133: =head2 Resource Access Logging
8134:
8135: =over 4
8136:
8137: =item *
8138:
8139: flushcourselogs() : flush (save) buffer logs and access logs
8140:
8141: =item *
8142:
8143: courselog($what) : save message for course in hash
8144:
8145: =item *
8146:
8147: courseacclog($what) : save message for course using &courselog(). Perform
8148: special processing for specific resource types (problems, exams, quizzes, etc).
8149:
8150: =item *
8151:
8152: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8153: as a PerlChildExitHandler
8154:
8155: =back
8156:
8157: =head2 Other
8158:
8159: =over 4
8160:
8161: =item *
8162:
8163: symblist($mapname,%newhash) : update symbolic storage links
8164:
8165: =back
8166:
8167: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>