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