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