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