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