File:
[LON-CAPA] /
rat /
lonuserstate.pm
Revision
1.146:
download - view:
text,
annotated -
select for diffs
Wed Jun 26 21:22:55 2013 UTC (11 years, 3 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bubblesheet grading of CODEd exams in which exam folder has either randomorder
or randompick set causes new parameter (examcode) to be set at map level for
a sepecific user each graded student.
- Parameter value is set to CODE on the student's bubblsheet exam.
- If used, requires course roles to be selected in a user session on a 2.11 server.
- Ensures resources are displayed in same order to student, and more importantly,
ensures points totals will be correct in student's quickgrades view, if randompick
was used.
1: # The LearningOnline Network with CAPA
2: # Construct and maintain state and binary representation of course for user
3: #
4: # $Id: lonuserstate.pm,v 1.146 2013/06/26 21:22:55 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::lonuserstate;
31:
32: # ------------------------------------------------- modules used by this module
33: use strict;
34: use HTML::TokeParser;
35: use Apache::lonnet;
36: use Apache::lonlocal;
37: use Apache::loncommon();
38: use GDBM_File;
39: use Apache::lonmsg;
40: use Safe;
41: use Safe::Hole;
42: use Opcode;
43: use Apache::lonenc;
44: use Fcntl qw(:flock);
45: use LONCAPA;
46: use File::Basename;
47:
48:
49:
50: # ---------------------------------------------------- Globals for this package
51:
52: my $pc; # Package counter is this what 'Guts' calls the map counter?
53: my %hash; # The big tied hash
54: my %parmhash;# The hash with the parameters
55: my @cond; # Array with all of the conditions
56: my $errtext; # variable with all errors
57: my $retfrid; # variable with the very first RID in the course
58: my $retfurl; # first URL
59: my %randompick; # randomly picked resources
60: my %randompickseed; # optional seed for randomly picking resources
61: my %randomorder; # maps to order contents randomly
62: my %randomizationcode; # code used to grade folder for bubblesheet exam
63: my %encurl; # URLs in this folder are supposed to be encrypted
64: my %hiddenurl; # this URL (or complete folder) is supposed to be hidden
65:
66: # ----------------------------------- Remove version from URL and store in hash
67:
68: sub versionerror {
69: my ($uri,$usedversion,$unusedversion)=@_;
70: return '<br />'.&mt('Version discrepancy: resource [_1] included in both version [_2] and version [_3]. Using version [_2].',
71: $uri,$usedversion,$unusedversion).'<br />';
72: }
73:
74: # Removes the version number from a URI and returns the resulting
75: # URI (e.g. mumbly.version.stuff => mumbly.stuff).
76: #
77: # If the URI has not been seen with a versio before the
78: # hash{'version_'.resultingURI} is set to the version number.
79: # If the URI has been seen and the version does not match and error
80: # is added to the error string.
81: #
82: # Parameters:
83: # URI potentially with a version.
84: # Returns:
85: # URI with the version cut out.
86: # See above for side effects.
87: #
88:
89: sub versiontrack {
90: my $uri=shift;
91: if ($uri=~/\.(\d+)\.\w+$/) {
92: my $version=$1;
93: $uri=~s/\.\d+\.(\w+)$/\.$1/;
94: unless ($hash{'version_'.$uri}) {
95: $hash{'version_'.$uri}=$version;
96: } elsif ($version!=$hash{'version_'.$uri}) {
97: $errtext.=&versionerror($uri,$hash{'version_'.$uri},$version);
98: }
99: }
100: return $uri;
101: }
102:
103: # -------------------------------------------------------------- Put in version
104:
105: sub putinversion {
106: my $uri=shift;
107: my $key=$env{'request.course.id'}.'_'.&Apache::lonnet::clutter($uri);
108: if ($hash{'version_'.$uri}) {
109: my $version=$hash{'version_'.$uri};
110: if ($version eq 'mostrecent') { return $uri; }
111: if ($version eq &Apache::lonnet::getversion(
112: &Apache::lonnet::filelocation('',$uri)))
113: { return $uri; }
114: $uri=~s/\.(\w+)$/\.$version\.$1/;
115: }
116: &Apache::lonnet::do_cache_new('courseresversion',$key,&Apache::lonnet::declutter($uri),600);
117: return $uri;
118: }
119:
120: # ----------------------------------------- Processing versions file for course
121:
122: sub processversionfile {
123: my %cenv=@_;
124: my %versions=&Apache::lonnet::dump('resourceversions',
125: $cenv{'domain'},
126: $cenv{'num'});
127: foreach my $ver (keys(%versions)) {
128: if ($ver=~/^error\:/) { return; }
129: $hash{'version_'.$ver}=$versions{$ver};
130: }
131: }
132:
133: # --------------------------------------------------------- Loads from disk
134:
135:
136: #
137: # Loads a map file.
138: # Note that this may implicitly recurse via parse_resource if one of the resources
139: # is itself composed.
140: #
141: # Parameters:
142: # uri - URI of the map file.
143: # parent_rid - Resource id in the map of the parent resource (0.0 for the top level map)
144: # courseid - Course id for the course for which the map is being loaded
145: #
146: sub loadmap {
147: my ($uri,$parent_rid,$courseid)=@_;
148:
149: # Is the map already included?
150:
151: if ($hash{'map_pc_'.$uri}) {
152: $errtext.='<p class="LC_error">'.
153: &mt('Multiple use of sequence/page [_1]! The course will not function properly.','<tt>'.$uri.'</tt>').
154: '</p>';
155: return;
156: }
157: # Register the resource in it's map_pc_ [for the URL]
158: # map_id.nnn is the nesting level -> to the URI.
159:
160: $pc++;
161: my $lpc=$pc;
162: $hash{'map_pc_'.$uri}=$lpc;
163: $hash{'map_id_'.$lpc}=$uri;
164:
165: # If the parent is of the form n.m hang this map underneath it in the
166: # map hierarchy.
167:
168: if ($parent_rid =~ /^(\d+)\.\d+$/) {
169: my $parent_pc = $1;
170: if (defined($hash{'map_hierarchy_'.$parent_pc})) {
171: $hash{'map_hierarchy_'.$lpc}=$hash{'map_hierarchy_'.$parent_pc}.','.
172: $parent_pc;
173: } else {
174: $hash{'map_hierarchy_'.$lpc}=$parent_pc;
175: }
176: }
177:
178: # Determine and check filename of the sequence we need to read:
179:
180: my $fn=&Apache::lonnet::filelocation('',&putinversion($uri));
181:
182: my $ispage=($fn=~/\.page$/);
183:
184: # We can only nest sequences or pages. Anything else is an illegal nest.
185:
186: unless (($fn=~/\.sequence$/) || $ispage) {
187: $errtext.=&mt("<br />Invalid map: <tt>[_1]</tt>",$fn);
188: return;
189: }
190:
191: # Read the XML that constitutes the file.
192:
193: my $instr=&Apache::lonnet::getfile($fn);
194:
195: if ($instr eq -1) {
196: $errtext.=&mt('<br />Map not loaded: The file <tt>[_1]</tt> does not exist.',$fn);
197: return;
198: }
199:
200: # Successfully got file, parse it
201:
202: # parse for parameter processing.
203: # Note that these are <param... / > tags
204: # so we only care about 'S' (tag start) nodes.
205:
206:
207: my $parser = HTML::TokeParser->new(\$instr);
208: $parser->attr_encoded(1);
209:
210: # first get all parameters
211:
212:
213: while (my $token = $parser->get_token) {
214: next if ($token->[0] ne 'S');
215: if ($token->[1] eq 'param') {
216: &parse_param($token,$lpc);
217: }
218: }
219:
220: # Get set to take another pass through the XML:
221: # for resources and links.
222:
223: $parser = HTML::TokeParser->new(\$instr);
224: $parser->attr_encoded(1);
225:
226: my $linkpc=0;
227:
228: $fn=~/\.(\w+)$/;
229:
230: $hash{'map_type_'.$lpc}=$1;
231:
232: my $randomize = ($randomorder{$parent_rid} =~ /^yes$/i);
233:
234: # Parse the resources, link and condition tags.
235: # Note that if randomorder or random select is chosen the links and
236: # conditions are meaningless but are determined by the randomization.
237: # This is handled in the next chunk of code.
238:
239: my @map_ids;
240: my $codechecked;
241: while (my $token = $parser->get_token) {
242: next if ($token->[0] ne 'S');
243:
244: # Resource
245:
246: if ($token->[1] eq 'resource') {
247: my $resource_id = &parse_resource($token,$lpc,$ispage,$uri,$courseid);
248: if (defined $resource_id) {
249: push(@map_ids, $resource_id);
250: unless ($codechecked) {
251: my $startsymb =
252: &Apache::lonnet::encode_symb($hash{'map_id_'.$lpc},$resource_id,
253: $hash{'src_'."$lpc.$resource_id"});
254: my $code =
255: &Apache::lonnet::EXT('resource.0.examcode',$startsymb,undef,undef,
256: undef,undef,$courseid);
257: if ($code) {
258: $randomizationcode{$parent_rid} = $code;
259: }
260: $codechecked = 1;
261: }
262: }
263:
264: # Link
265:
266: } elsif ($token->[1] eq 'link' && !$randomize) {
267: &make_link(++$linkpc,$lpc,$token->[2]->{'to'},
268: $token->[2]->{'from'},
269: $token->[2]->{'condition'}); # note ..condition may be undefined.
270:
271: # condition
272:
273: } elsif ($token->[1] eq 'condition' && !$randomize) {
274: &parse_condition($token,$lpc);
275: }
276: }
277: undef($codechecked);
278:
279:
280: # Handle randomization and random selection
281:
282: if ($randomize) {
283: if (!$env{'request.role.adv'}) {
284: my $seed;
285:
286: # In the advanced role, the map's random seed
287: # parameter is used as the basis for computing the
288: # seed ... if it has been specified:
289:
290: if (defined($randompickseed{$parent_rid})) {
291: $seed = $randompickseed{$parent_rid};
292: } else {
293:
294: # Otherwise the parent's fully encoded symb is used.
295:
296: my ($mapid,$resid)=split(/\./,$parent_rid);
297: my $symb=
298: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
299: $resid,$hash{'src_'.$parent_rid});
300:
301: $seed = $symb;
302: }
303:
304: # TODO: Here for sure we need to pass along the username/domain
305: # so that we can impersonate users in lonprintout e.g.
306:
307: my $setcode;
308: if (defined($randomizationcode{$parent_rid})) {
309: if ($env{'form.CODE'} eq '') {
310: $env{'form.CODE'} = $randomizationcode{$parent_rid};
311: $setcode = 1;
312: }
313: }
314:
315: my $rndseed=&Apache::lonnet::rndseed($seed);
316: &Apache::lonnet::setup_random_from_rndseed($rndseed);
317:
318: if ($setcode) {
319: undef($env{'form.CODE'});
320: undef($setcode);
321: }
322:
323: # Take the set of map ids we have decoded and permute them to a
324: # random order based on the seed set above. All of this is
325: # processing the randomorder parameter if it is set, not
326: # randompick.
327:
328: @map_ids=&Math::Random::random_permutation(@map_ids);
329: }
330:
331:
332: my $from = shift(@map_ids);
333: my $from_rid = $lpc.'.'.$from;
334: $hash{'map_start_'.$uri} = $from_rid;
335: $hash{'type_'.$from_rid}='start';
336:
337: # Create links to reflect the random re-ordering done above.
338: # In the code to process the map XML, we did not process links or conditions
339: # if randomorder was set. This means that for an instructor to choose
340:
341: while (my $to = shift(@map_ids)) {
342: &make_link(++$linkpc,$lpc,$to,$from);
343: my $to_rid = $lpc.'.'.$to;
344: $hash{'type_'.$to_rid}='normal';
345: $from = $to;
346: $from_rid = $to_rid;
347: }
348:
349: $hash{'map_finish_'.$uri}= $from_rid;
350: $hash{'type_'.$from_rid}='finish';
351: }
352:
353: $parser = HTML::TokeParser->new(\$instr);
354: $parser->attr_encoded(1);
355:
356: # last parse out the mapalias params. Thes provide mnemonic
357: # tags to resources that can be used in conditions
358:
359: while (my $token = $parser->get_token) {
360: next if ($token->[0] ne 'S');
361: if ($token->[1] eq 'param') {
362: &parse_mapalias_param($token,$lpc);
363: }
364: }
365: }
366:
367:
368: # -------------------------------------------------------------------- Resource
369: #
370: # Parses a resource tag to produce the value to push into the
371: # map_ids array.
372: #
373: #
374: # Information about the actual type of resource is provided by the file extension
375: # of the uri (e.g. .problem, .sequence etc. etc.).
376: #
377: # Parameters:
378: # $token - A token from HTML::TokeParser
379: # This is an array that describes the most recently parsed HTML item.
380: # $lpc - Map nesting level (?)
381: # $ispage - True if this resource is encapsulated in a .page (assembled resourcde).
382: # $uri - URI of the enclosing resource.
383: # $courseid - Course id of the course containing the resource being parsed.
384: # Returns:
385: # Value of the id attribute of the tag.
386: #
387: # Note:
388: # The token is an array that contains the following elements:
389: # [0] => 'S' indicating this is a start token
390: # [1] => 'resource' indicating this tag is a <resource> tag.
391: # [2] => Hash of attribute =>value pairs.
392: # [3] => @(keys [2]).
393: # [4] => unused.
394: #
395: # The attributes of the resourcde tag include:
396: #
397: # id - The resource id.
398: # src - The URI of the resource.
399: # type - The resource type (e.g. start and finish).
400: # title - The resource title.
401:
402:
403: sub parse_resource {
404: my ($token,$lpc,$ispage,$uri,$courseid) = @_;
405:
406: # I refuse to countenance code like this that has
407: # such a dirty side effect (and forcing this sub to be called within a loop).
408: #
409: # if ($token->[2]->{'type'} eq 'zombie') { next; }
410: #
411: # The original code both returns _and_ skips to the next pass of the >caller's<
412: # loop, that's just dirty.
413: #
414:
415: # Zombie resources don't produce anything useful.
416:
417: if ($token->[2]->{'type'} eq 'zombie') {
418: return undef;
419: }
420:
421: my $rid=$lpc.'.'.$token->[2]->{'id'}; # Resource id in hash is levelcounter.id-in-xml.
422:
423: # Save the hash element type and title:
424:
425: $hash{'kind_'.$rid}='res';
426: $hash{'title_'.$rid}=$token->[2]->{'title'};
427:
428: # Get the version free URI for the resource.
429: # If a 'version' attribute was supplied, and this resource's version
430: # information has not yet been stored, store it.
431: #
432:
433: my $turi=&versiontrack($token->[2]->{'src'});
434: if ($token->[2]->{'version'}) {
435: unless ($hash{'version_'.$turi}) {
436: $hash{'version_'.$turi}=$1;
437: }
438: }
439: # Pull out the title and do entity substitution on &colon
440: # Q: Why no other entity substitutions?
441:
442: my $title=$token->[2]->{'title'};
443: $title=~s/\&colon\;/\:/gs;
444:
445:
446:
447: # I think the point of all this code is to construct a final
448: # URI that apache and its rewrite rules can use to
449: # fetch the resource. Thi s sonly necessary if the resource
450: # is not a page. If the resource is a page then it must be
451: # assembled (at fetch time?).
452:
453: unless ($ispage) {
454: $turi=~/\.(\w+)$/;
455: my $embstyle=&Apache::loncommon::fileembstyle($1);
456: if ($token->[2]->{'external'} eq 'true') { # external
457: $turi=~s/^https?\:\/\//\/adm\/wrapper\/ext\//;
458: } elsif ($turi=~/^\/*uploaded\//) { # uploaded
459: if (($embstyle eq 'img')
460: || ($embstyle eq 'emb')
461: || ($embstyle eq 'wrp')) {
462: $turi='/adm/wrapper'.$turi;
463: } elsif ($embstyle eq 'ssi') {
464: #do nothing with these
465: } elsif ($turi!~/\.(sequence|page)$/) {
466: $turi='/adm/coursedocs/showdoc'.$turi;
467: }
468: } elsif ($turi=~/\S/) { # normal non-empty internal resource
469: my $mapdir=$uri;
470: $mapdir=~s/[^\/]+$//;
471: $turi=&Apache::lonnet::hreflocation($mapdir,$turi);
472: if (($embstyle eq 'img')
473: || ($embstyle eq 'emb')
474: || ($embstyle eq 'wrp')) {
475: $turi='/adm/wrapper'.$turi;
476: }
477: }
478: }
479: # Store reverse lookup, remove query string resource 'ids'_uri => resource id.
480: # If the URI appears more than one time in the sequence, it's resourcde
481: # id's are constructed as a comma spearated list.
482:
483: my $idsuri=$turi;
484: $idsuri=~s/\?.+$//;
485: if (defined($hash{'ids_'.$idsuri})) {
486: $hash{'ids_'.$idsuri}.=','.$rid;
487: } else {
488: $hash{'ids_'.$idsuri}=''.$rid;
489: }
490:
491:
492:
493: if ($turi=~/\/(syllabus|aboutme|navmaps|smppg|bulletinboard|viewclasslist)$/) {
494: $turi.='?register=1';
495: }
496:
497:
498: # resource id lookup: 'src'_resourc-di => URI decorated with a query
499: # parameter as above if necessary due to the resource type.
500:
501: $hash{'src_'.$rid}=$turi;
502:
503: # Mark the external-ness of the resource:
504:
505: if ($token->[2]->{'external'} eq 'true') {
506: $hash{'ext_'.$rid}='true:';
507: } else {
508: $hash{'ext_'.$rid}='false:';
509: }
510:
511: # If the resource is a start/finish resource set those
512: # entries in the has so that navigation knows where everything starts.
513: # TODO? If there is a malformed sequence that has no start or no finish
514: # resource, should this be detected and errors thrown? How would such a
515: # resource come into being other than being manually constructed by a person
516: # and then uploaded? Could that happen if an author decided a sequence was almost
517: # right edited it by hand and then reuploaded it to 'fix it' but accidently cut the
518: # start or finish resources?
519: #
520: # All resourcess also get a type_id => (start | finish | normal) hash entr.
521: #
522: if ($token->[2]->{'type'}) {
523: $hash{'type_'.$rid}=$token->[2]->{'type'};
524: if ($token->[2]->{'type'} eq 'start') {
525: $hash{'map_start_'.$uri}="$rid";
526: }
527: if ($token->[2]->{'type'} eq 'finish') {
528: $hash{'map_finish_'.$uri}="$rid";
529: }
530: } else {
531: $hash{'type_'.$rid}='normal';
532: }
533:
534: # Sequences end pages are constructed entities. They require that the
535: # map that defines _them_ be loaded as well into the hash...with this resourcde
536: # as the base of the nesting.
537: # Resources like that are also marked with is_map_id => 1 entries.
538: #
539:
540: if (($turi=~/\.sequence$/) ||
541: ($turi=~/\.page$/)) {
542: $hash{'is_map_'.$rid}=1;
543: &loadmap($turi,$rid,$courseid);
544: }
545: return $token->[2]->{'id'};
546: }
547:
548: #-------------------------------------------------------------------- link
549: # Links define how you are allowed to move from one resource to another.
550: # They are the transition edges in the directed graph that a map is.
551: # This sub takes informatino from a <link> tag and constructs the
552: # navigation bits and pieces of a map. There is no requirement that the
553: # resources that are linke are already defined, however clearly the map is
554: # badly broken if they are not _eventually_ defined.
555: #
556: # Note that links can be unconditional or conditional.
557: #
558: # Parameters:
559: # linkpc - The link counter for this level of map nesting (this is
560: # reset to zero by loadmap prior to starting to process
561: # links for map).
562: # lpc - The map level ocounter (how deeply nested this map is in
563: # the hierarchy of maps that are recursively read in.
564: # to - resource id (within the XML) of the target of the edge.
565: # from - resource id (within the XML) of the source of the edge.
566: # condition- id of condition associated with the edge (also within the XML).
567: #
568:
569: sub make_link {
570: my ($linkpc,$lpc,$to,$from,$condition) = @_;
571:
572: # Compute fully qualified ids for the link, the
573: # and from/to by prepending lpc.
574: #
575:
576: my $linkid=$lpc.'.'.$linkpc;
577: my $goesto=$lpc.'.'.$to;
578: my $comesfrom=$lpc.'.'.$from;
579: my $undercond=0;
580:
581:
582: # If there is a condition, qualify it with the level counter.
583:
584: if ($condition) {
585: $undercond=$lpc.'.'.$condition;
586: }
587:
588: # Links are represnted by:
589: # goesto_.fuullyqualifedlinkid => fully qualified to
590: # comesfrom.fullyqualifiedlinkid => fully qualified from
591: # undercond_.fullyqualifiedlinkid => fully qualified condition id.
592:
593: $hash{'goesto_'.$linkid}=$goesto;
594: $hash{'comesfrom_'.$linkid}=$comesfrom;
595: $hash{'undercond_'.$linkid}=$undercond;
596:
597: # In addition:
598: # to_.fully qualified from => comma separated list of
599: # link ids with that from.
600: # Similarly:
601: # from_.fully qualified to => comma separated list of link ids`
602: # with that to.
603: # That allows us given a resource id to know all edges that go to it
604: # and leave from it.
605: #
606:
607: if (defined($hash{'to_'.$comesfrom})) {
608: $hash{'to_'.$comesfrom}.=','.$linkid;
609: } else {
610: $hash{'to_'.$comesfrom}=''.$linkid;
611: }
612: if (defined($hash{'from_'.$goesto})) {
613: $hash{'from_'.$goesto}.=','.$linkid;
614: } else {
615: $hash{'from_'.$goesto}=''.$linkid;
616: }
617: }
618:
619: # ------------------------------------------------------------------- Condition
620: #
621: # Processes <condition> tags, storing sufficient information about them
622: # in the hash so that they can be evaluated and used to conditionalize
623: # what is presented to the student.
624: #
625: # these can have the following attributes
626: #
627: # id = A unique identifier of the condition within the map.
628: #
629: # value = Is a perl script-let that, when evaluated in safe space
630: # determines whether or not the condition is true.
631: # Normally this takes the form of a test on an Apache::lonnet::EXT call
632: # to find the value of variable associated with a resource in the
633: # map identified by a mapalias.
634: # Here's a fragment of XML code that illustrates this:
635: #
636: # <param to="5" value="mainproblem" name="parameter_0_mapalias" type="string" />
637: # <resource src="" id="1" type="start" title="Start" />
638: # <resource src="/res/msu/albertel/b_and_c/p1.problem" id="5" title="p1.problem" />
639: # <condition value="&EXT('user.resource.resource.0.tries','mainproblem')
640: # <2 " id="61" type="stop" />
641: # <link to="5" index="1" from="1" condition="61" />
642: #
643: # In this fragment:
644: # - The param tag establishes an alias to resource id 5 of 'mainproblem'.
645: # - The resource that is the start of the map is identified.
646: # - The resource tag identifies the resource associated with this tag
647: # and gives it the id 5.
648: # - The condition is true if the tries variable associated with mainproblem
649: # is less than 2 (that is the user has had more than 2 tries).
650: # The condition type is a stop condition which inhibits(?) the associated
651: # link if the condition is false.
652: # - The link to resource 5 from resource 1 is affected by this condition.
653: #
654: # type = Type of the condition. The type determines how the condition affects the
655: # link associated with it and is one of
656: # - 'force'
657: # - 'stop'
658: # anything else including not supplied..which treated as:
659: # - 'normal'.
660: # Presumably maps get created by the resource assembly tool and therefore
661: # illegal type values won't squirm their way into the XML.
662: #
663: # Side effects:
664: # - The kind_level-qualified-condition-id hash element is set to 'cond'.
665: # - The condition text is pushed into the cond array and its element number is
666: # set in the condid_level-qualified-condition-id element of the hash.
667: # - The condition type is colon appneded to the cond array element for this condition.
668: sub parse_condition {
669: my ($token,$lpc) = @_;
670: my $rid=$lpc.'.'.$token->[2]->{'id'};
671:
672: $hash{'kind_'.$rid}='cond';
673:
674: my $condition = $token->[2]->{'value'};
675: $condition =~ s/[\n\r]+/ /gs;
676: push(@cond, $condition);
677: $hash{'condid_'.$rid}=$#cond;
678: if ($token->[2]->{'type'}) {
679: $cond[$#cond].=':'.$token->[2]->{'type'};
680: } else {
681: $cond[$#cond].=':normal';
682: }
683: }
684:
685: # ------------------------------------------------------------------- Parameter
686: # Parse a <parameter> tag in the map.
687: # Parmameters:
688: # $token Token array for a start tag from HTML::TokeParser
689: # [0] = 'S'
690: # [1] = tagname ("param")
691: # [2] = Hash of {attribute} = values.
692: # [3] = Array of the keys in [2].
693: # [4] = unused.
694: # $lpc Current map nesting level.a
695: #
696: # Typical attributes:
697: # to=n - Number of the resource the parameter applies to.
698: # type=xx - Type of parameter value (e.g. string_yesno or int_pos).
699: # name=xxx - Name ofr parameter (e.g. parameter_randompick or parameter_randomorder).
700: # value=xxx - value of the parameter.
701:
702: sub parse_param {
703: my ($token,$lpc) = @_;
704: my $referid=$lpc.'.'.$token->[2]->{'to'}; # Resource param applies to.
705: my $name=$token->[2]->{'name'}; # Name of parameter
706: my $part;
707:
708:
709: if ($name=~/^parameter_(.*)_/) {
710: $part=$1;
711: } else {
712: $part=0;
713: }
714:
715: # Peel the parameter_ off the parameter name.
716:
717: $name=~s/^.*_([^_]*)$/$1/;
718:
719: # The value is:
720: # type.part.name.value
721:
722: my $newparam=
723: &escape($token->[2]->{'type'}).':'.
724: &escape($part.'.'.$name).'='.
725: &escape($token->[2]->{'value'});
726:
727: # The hash key is param_resourceid.
728: # Multiple parameters for a single resource are & separated in the hash.
729:
730:
731: if (defined($hash{'param_'.$referid})) {
732: $hash{'param_'.$referid}.='&'.$newparam;
733: } else {
734: $hash{'param_'.$referid}=''.$newparam;
735: }
736: #
737: # These parameters have to do with randomly selecting
738: # resources, therefore a separate hash is also created to
739: # make it easy to locate them when actually computing the resource set later on
740: # See the code conditionalized by ($randomize) in loadmap().
741:
742: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompick$/) { # Random selection turned on
743: $randompick{$referid}=$token->[2]->{'value'};
744: }
745: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompickseed$/) { # Randomseed provided.
746: $randompickseed{$referid}=$token->[2]->{'value'};
747: }
748: if ($token->[2]->{'name'}=~/^parameter_(0_)*randomorder$/) { # Random order turned on.
749: $randomorder{$referid}=$token->[2]->{'value'};
750: }
751:
752: # These parameters have to do with how the URLs of resources are presented to
753: # course members(?). encrypturl presents encypted url's while
754: # hiddenresource hides the URL.
755: #
756:
757: if ($token->[2]->{'name'}=~/^parameter_(0_)*encrypturl$/) {
758: if ($token->[2]->{'value'}=~/^yes$/i) {
759: $encurl{$referid}=1;
760: }
761: }
762: if ($token->[2]->{'name'}=~/^parameter_(0_)*hiddenresource$/) {
763: if ($token->[2]->{'value'}=~/^yes$/i) {
764: $hiddenurl{$referid}=1;
765: }
766: }
767: }
768: #
769: # Parse mapalias parameters.
770: # these are tags of the form:
771: # <param to="nn"
772: # value="some-alias-for-resourceid-nn"
773: # name="parameter_0_mapalias"
774: # type="string" />
775: # A map alias is a textual name for a resource:
776: # - The to attribute identifies the resource (this gets level qualified below)
777: # - The value attributes provides the alias string.
778: # - name must be of the regexp form: /^parameter_(0_)*mapalias$/
779: # - e.g. the string 'parameter_' followed by 0 or more "0_" strings
780: # terminating with the string 'mapalias'.
781: # Examples:
782: # 'parameter_mapalias', 'parameter_0_mapalias', parameter_0_0_mapalias'
783: # Invalid to ids are silently ignored.
784: #
785: # Parameters:
786: # token - The token array fromthe HMTML::TokeParser
787: # lpc - The current map level counter.
788: #
789: sub parse_mapalias_param {
790: my ($token,$lpc) = @_;
791:
792: # Fully qualify the to value and ignore the alias if there is no
793: # corresponding resource.
794:
795: my $referid=$lpc.'.'.$token->[2]->{'to'};
796: return if (!exists($hash{'src_'.$referid}));
797:
798: # If this is a valid mapalias parameter,
799: # Append the target id to the count_mapalias element for that
800: # alias so that we can detect doubly defined aliases
801: # e.g.:
802: # <param to="1" value="george" name="parameter_0_mapalias" type="string" />
803: # <param to="2" value="george" name="parameter_0_mapalias" type="string" />
804: #
805: # The example above is trivial but the case that's important has to do with
806: # constructing a map that includes a nested map where the nested map may have
807: # aliases that conflict with aliases established in the enclosing map.
808: #
809: # ...and create/update the hash mapalias entry to actually store the alias.
810: #
811:
812: if ($token->[2]->{'name'}=~/^parameter_(0_)*mapalias$/) {
813: &count_mapalias($token->[2]->{'value'},$referid);
814: $hash{'mapalias_'.$token->[2]->{'value'}}=$referid;
815: }
816: }
817:
818: # --------------------------------------------------------- Simplify expression
819:
820:
821: #
822: # Someone should really comment this to describe what it does to what and why.
823: #
824: sub simplify {
825: my $expression=shift;
826: # (0&1) = 1
827: $expression=~s/\(0\&([_\.\d]+)\)/$1/g;
828: # (8)=8
829: $expression=~s/\(([_\.\d]+)\)/$1/g;
830: # 8&8=8
831: $expression=~s/([^_\.\d])([_\.\d]+)\&\2([^_\.\d])/$1$2$3/g;
832: # 8|8=8
833: $expression=~s/([^_\.\d])([_\.\d]+)(?:\|\2)+([^_\.\d])/$1$2$3/g;
834: # (5&3)&4=5&3&4
835: $expression=~s/\(([_\.\d]+)((?:\&[_\.\d]+)+)\)\&([_\.\d]+[^_\.\d])/$1$2\&$3/g;
836: # (((5&3)|(4&6)))=((5&3)|(4&6))
837: $expression=~
838: s/\((\(\([_\.\d]+(?:\&[_\.\d]+)*\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+\))\)/$1/g;
839: # ((5&3)|(4&6))|(1&2)=(5&3)|(4&6)|(1&2)
840: $expression=~
841: s/\((\([_\.\d]+(?:\&[_\.\d]+)*\))((?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+)\)\|(\([_\.\d]+(?:\&[_\.\d]+)*\))/\($1$2\|$3\)/g;
842: return $expression;
843: }
844:
845: # -------------------------------------------------------- Build condition hash
846:
847: #
848: # Traces a route recursively through the map after it has been loaded
849: # (I believe this really visits each resourcde that is reachable fromt he
850: # start top node.
851: #
852: # - Marks hidden resources as hidden.
853: # - Marks which resource URL's must be encrypted.
854: # - Figures out (if necessary) the first resource in the map.
855: # - Further builds the chunks of the big hash that define how
856: # conditions work
857: #
858: # Note that the tracing strategy won't visit resources that are not linked to
859: # anything or islands in the map (groups of resources that form a path but are not
860: # linked in to the path that can be traced from the start resource...but that's ok
861: # because by definition, those resources are not reachable by users of the course.
862: #
863: # Parameters:
864: # sofar - _URI of the prior entry or 0 if this is the top.
865: # rid - URI of the resource to visit.
866: # beenhere - list of resources (each resource enclosed by &'s) that have
867: # already been visited.
868: # encflag - If true the resource that resulted in a recursive call to us
869: # has an encoded URL (which means contained resources should too).
870: # hdnflag - If true,the resource that resulted in a recursive call to us
871: # was hidden (which means contained resources should be hidden too).
872: # Returns
873: # new value indicating how far the map has been traversed (the sofar).
874: #
875: sub traceroute {
876: my ($sofar,$rid,$beenhere,$encflag,$hdnflag)=@_;
877: my $newsofar=$sofar=simplify($sofar);
878:
879: unless ($beenhere=~/\&\Q$rid\E\&/) {
880: $beenhere.=$rid.'&';
881: my ($mapid,$resid)=split(/\./,$rid);
882: my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$rid});
883: my $hidden=&Apache::lonnet::EXT('resource.0.hiddenresource',$symb);
884:
885: if ($hdnflag || lc($hidden) eq 'yes') {
886: $hiddenurl{$rid}=1;
887: }
888: if (!$hdnflag && lc($hidden) eq 'no') {
889: delete($hiddenurl{$rid});
890: }
891:
892: my $encrypt=&Apache::lonnet::EXT('resource.0.encrypturl',$symb);
893: if ($encflag || lc($encrypt) eq 'yes') { $encurl{$rid}=1; }
894:
895: if (($retfrid eq '') && ($hash{'src_'.$rid})
896: && ($hash{'src_'.$rid}!~/\.sequence$/)) {
897: $retfrid=$rid;
898: }
899:
900: if (defined($hash{'conditions_'.$rid})) {
901: $hash{'conditions_'.$rid}=simplify(
902: '('.$hash{'conditions_'.$rid}.')|('.$sofar.')');
903: } else {
904: $hash{'conditions_'.$rid}=$sofar;
905: }
906:
907: # if the expression is just the 0th condition keep it
908: # otherwise leave a pointer to this condition expression
909:
910: $newsofar = ($sofar eq '0') ? $sofar : '_'.$rid;
911:
912: # Recurse if the resource is a map:
913:
914: if (defined($hash{'is_map_'.$rid})) {
915: if (defined($hash{'map_start_'.$hash{'src_'.$rid}})) {
916: $sofar=$newsofar=
917: &traceroute($sofar,
918: $hash{'map_start_'.$hash{'src_'.$rid}},
919: $beenhere,
920: $encflag || $encurl{$rid},
921: $hdnflag || $hiddenurl{$rid});
922: }
923: }
924:
925: # Processes links to this resource:
926: # - verify the existence of any conditionals on the link to here.
927: # - Recurse to any resources linked to us.
928: #
929: if (defined($hash{'to_'.$rid})) {
930: foreach my $id (split(/\,/,$hash{'to_'.$rid})) {
931: my $further=$sofar;
932: #
933: # If there's a condition associated with this link be sure
934: # it's been defined else that's an error:
935: #
936: if ($hash{'undercond_'.$id}) {
937: if (defined($hash{'condid_'.$hash{'undercond_'.$id}})) {
938: $further=simplify('('.'_'.$rid.')&('.
939: $hash{'condid_'.$hash{'undercond_'.$id}}.')');
940: } else {
941: $errtext.=&mt('<br />Undefined condition ID: [_1]',$hash{'undercond_'.$id});
942: }
943: }
944: # Recurse to resoruces that have to's to us.
945: $newsofar=&traceroute($further,$hash{'goesto_'.$id},$beenhere,
946: $encflag,$hdnflag);
947: }
948: }
949: }
950: return $newsofar;
951: }
952:
953: # ------------------------------ Cascading conditions, quick access, parameters
954:
955: #
956: # Seems a rather strangely named sub given what the comment above says it does.
957:
958:
959: sub accinit {
960: my ($uri,$short,$fn)=@_;
961: my %acchash=();
962: my %captured=();
963: my $condcounter=0;
964: $acchash{'acc.cond.'.$short.'.0'}=0;
965:
966: # This loop is only interested in conditions and
967: # parameters in the big hash:
968:
969: foreach my $key (keys(%hash)) {
970:
971: # conditions:
972:
973: if ($key=~/^conditions/) {
974: my $expr=$hash{$key};
975:
976: # try to find and factor out common sub-expressions
977: # Any subexpression that is found is simplified, removed from
978: # the original condition expression and the simplified sub-expression
979: # substituted back in to the epxression..I'm not actually convinced this
980: # factors anything out...but instead maybe simplifies common factors(?)
981:
982: foreach my $sub ($expr=~m/(\(\([_\.\d]+(?:\&[_\.\d]+)+\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)+\))+\))/g) {
983: my $orig=$sub;
984:
985: my ($factor) = ($sub=~/\(\(([_\.\d]+\&(:?[_\.\d]+\&)*)(?:[_\.\d]+\&*)+\)(?:\|\(\1(?:[_\.\d]+\&*)+\))+\)/);
986: next if (!defined($factor));
987:
988: $sub=~s/\Q$factor\E//g;
989: $sub=~s/^\(/\($factor\(/;
990: $sub.=')';
991: $sub=simplify($sub);
992: $expr=~s/\Q$orig\E/$sub/;
993: }
994: $hash{$key}=$expr;
995:
996: # If not yet seen, record in acchash and that we've seen it.
997:
998: unless (defined($captured{$expr})) {
999: $condcounter++;
1000: $captured{$expr}=$condcounter;
1001: $acchash{'acc.cond.'.$short.'.'.$condcounter}=$expr;
1002: }
1003: # Parameters:
1004:
1005: } elsif ($key=~/^param_(\d+)\.(\d+)/) {
1006: my $prefix=&Apache::lonnet::encode_symb($hash{'map_id_'.$1},$2,
1007: $hash{'src_'.$1.'.'.$2});
1008: foreach my $param (split(/\&/,$hash{$key})) {
1009: my ($typename,$value)=split(/\=/,$param);
1010: my ($type,$name)=split(/\:/,$typename);
1011: $parmhash{$prefix.'.'.&unescape($name)}=
1012: &unescape($value);
1013: $parmhash{$prefix.'.'.&unescape($name).'.type'}=
1014: &unescape($type);
1015: }
1016: }
1017: }
1018: # This loop only processes id entries in the big hash.
1019:
1020: foreach my $key (keys(%hash)) {
1021: if ($key=~/^ids/) {
1022: foreach my $resid (split(/\,/,$hash{$key})) {
1023: my $uri=$hash{'src_'.$resid};
1024: my ($uripath,$urifile) =
1025: &Apache::lonnet::split_uri_for_cond($uri);
1026: if ($uripath) {
1027: my $uricond='0';
1028: if (defined($hash{'conditions_'.$resid})) {
1029: $uricond=$captured{$hash{'conditions_'.$resid}};
1030: }
1031: if (defined($acchash{'acc.res.'.$short.'.'.$uripath})) {
1032: if ($acchash{'acc.res.'.$short.'.'.$uripath}=~
1033: /(\&\Q$urifile\E\:[^\&]*)/) {
1034: my $replace=$1;
1035: my $regexp=$replace;
1036: #$regexp=~s/\|/\\\|/g;
1037: $acchash{'acc.res.'.$short.'.'.$uripath} =~
1038: s/\Q$regexp\E/$replace\|$uricond/;
1039: } else {
1040: $acchash{'acc.res.'.$short.'.'.$uripath}.=
1041: $urifile.':'.$uricond.'&';
1042: }
1043: } else {
1044: $acchash{'acc.res.'.$short.'.'.$uripath}=
1045: '&'.$urifile.':'.$uricond.'&';
1046: }
1047: }
1048: }
1049: }
1050: }
1051: $acchash{'acc.res.'.$short.'.'}='&:0&';
1052: my $courseuri=$uri;
1053: $courseuri=~s/^\/res\///;
1054: my $regexp = 1;
1055: &Apache::lonnet::delenv('(acc\.|httpref\.)',$regexp);
1056: &Apache::lonnet::appenv(\%acchash);
1057: }
1058:
1059: # ---------------- Selectively delete from randompick maps and hidden url parms
1060:
1061: sub hiddenurls {
1062: my $randomoutentry='';
1063: foreach my $rid (keys %randompick) {
1064: my $rndpick=$randompick{$rid};
1065: my $mpc=$hash{'map_pc_'.$hash{'src_'.$rid}};
1066: # ------------------------------------------- put existing resources into array
1067: my @currentrids=();
1068: foreach my $key (sort(keys(%hash))) {
1069: if ($key=~/^src_($mpc\.\d+)/) {
1070: if ($hash{'src_'.$1}) { push @currentrids, $1; }
1071: }
1072: }
1073: # rids are number.number and we want to numercially sort on
1074: # the second number
1075: @currentrids=sort {
1076: my (undef,$aid)=split(/\./,$a);
1077: my (undef,$bid)=split(/\./,$b);
1078: $aid <=> $bid;
1079: } @currentrids;
1080: next if ($#currentrids<$rndpick);
1081: # -------------------------------- randomly eliminate the ones that should stay
1082: my (undef,$id)=split(/\./,$rid);
1083: if ($randompickseed{$rid}) { $id=$randompickseed{$rid}; }
1084: my $setcode;
1085: if (defined($randomizationcode{$rid})) {
1086: if ($env{'form.CODE'} eq '') {
1087: $env{'form.CODE'} = $randomizationcode{$rid};
1088: $setcode = 1;
1089: }
1090: }
1091: my $rndseed=&Apache::lonnet::rndseed($id); # use id instead of symb
1092: if ($setcode) {
1093: undef($env{'form.CODE'});
1094: undef($setcode);
1095: }
1096: &Apache::lonnet::setup_random_from_rndseed($rndseed);
1097: my @whichids=&Math::Random::random_permuted_index($#currentrids+1);
1098: for (my $i=1;$i<=$rndpick;$i++) { $currentrids[$whichids[$i]]=''; }
1099: #&Apache::lonnet::logthis("$id,$rndseed,".join(':',@whichids));
1100: # -------------------------------------------------------- delete the leftovers
1101: for (my $k=0; $k<=$#currentrids; $k++) {
1102: if ($currentrids[$k]) {
1103: $hash{'randomout_'.$currentrids[$k]}=1;
1104: my ($mapid,$resid)=split(/\./,$currentrids[$k]);
1105: $randomoutentry.='&'.
1106: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
1107: $resid,
1108: $hash{'src_'.$currentrids[$k]}
1109: ).'&';
1110: }
1111: }
1112: }
1113: # ------------------------------ take care of explicitly hidden urls or folders
1114: foreach my $rid (keys %hiddenurl) {
1115: $hash{'randomout_'.$rid}=1;
1116: my ($mapid,$resid)=split(/\./,$rid);
1117: $randomoutentry.='&'.
1118: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,
1119: $hash{'src_'.$rid}).'&';
1120: }
1121: # --------------------------------------- append randomout entry to environment
1122: if ($randomoutentry) {
1123: &Apache::lonnet::appenv({'acc.randomout' => $randomoutentry});
1124: }
1125: }
1126:
1127: # ---------------------------------------------------- Read map and all submaps
1128:
1129: sub readmap {
1130: my $short=shift;
1131: $short=~s/^\///;
1132:
1133: # TODO: Hidden dependency on current user:
1134:
1135: my %cenv=&Apache::lonnet::coursedescription($short,{'freshen_cache'=>1});
1136:
1137: my $fn=$cenv{'fn'};
1138: my $uri;
1139: $short=~s/\//\_/g;
1140: unless ($uri=$cenv{'url'}) {
1141: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1142: "Could not load course $short.</font>");
1143: return ('',&mt('No course data available.'));;
1144: }
1145: @cond=('true:normal');
1146:
1147: unless (open(LOCKFILE,">$fn.db.lock")) {
1148: #
1149: # Most likely a permissions problem on the lockfile or its directory.
1150: #
1151: $retfurl = '';
1152: return ($retfurl,'<br />'.&mt('Map not loaded - Lock file could not be opened when reading map:').' <tt>'.$fn.'</tt>.');
1153: }
1154: my $lock=0;
1155: my $gotstate=0;
1156:
1157: # If we can get the lock without delay any files there are idle
1158: # and from some prior request. We'll kill them off and regenerate them:
1159:
1160: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1161: $lock=1; # Remember that we hold the lock.
1162: &unlink_tmpfiles($fn);
1163: }
1164: undef %randompick;
1165: undef %hiddenurl;
1166: undef %encurl;
1167: $retfrid='';
1168: $errtext='';
1169: my ($untiedhash,$untiedparmhash,$tiedhash,$tiedparmhash); # More state flags.
1170:
1171: # if we got the lock, regenerate course regnerate empty files and tie them.
1172:
1173: if ($lock) {
1174: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_WRCREAT(),0640)) {
1175: $tiedhash = 1;
1176: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_WRCREAT(),0640)) {
1177: $tiedparmhash = 1;
1178: $gotstate = &build_tmp_hashes($uri,
1179: $fn,
1180: $short,
1181: \%cenv); # TODO: Need to provide requested user@dom
1182: unless ($gotstate) {
1183: &Apache::lonnet::logthis('Failed to write statemap at first attempt '.$fn.' for '.$uri.'.</font>');
1184: }
1185: $untiedparmhash = untie(%parmhash);
1186: unless ($untiedparmhash) {
1187: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1188: 'Could not untie coursemap parmhash '.$fn.' for '.$uri.'.</font>');
1189: }
1190: }
1191: $untiedhash = untie(%hash);
1192: unless ($untiedhash) {
1193: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1194: 'Could not untie coursemap hash '.$fn.' for '.$uri.'.</font>');
1195: }
1196: }
1197: flock(LOCKFILE,LOCK_UN); # RF: this is what I don't get unless there are other
1198: # unlocked places the remainder happens..seems like if we
1199: # just kept the lock here the rest of the code would have
1200: # been much easier?
1201: }
1202: unless ($lock && $tiedhash && $tiedparmhash) {
1203: # if we are here it is likely because we are already trying to
1204: # initialize the course in another child, busy wait trying to
1205: # tie the hashes for the next 90 seconds, if we succeed forward
1206: # them on to navmaps, if we fail, throw up the Could not init
1207: # course screen
1208: #
1209: # RF: I'm not seeing the case where the ties/unties can fail in a way
1210: # that can be remedied by this. Since we owned the lock seems
1211: # Tie/untie failures are a result of something like a permissions problem instead?
1212: #
1213:
1214: # In any vent, undo what we did manage to do above first:
1215: if ($lock) {
1216: # Got the lock but not the DB files
1217: flock(LOCKFILE,LOCK_UN);
1218: $lock = 0;
1219: }
1220: if ($tiedhash) {
1221: unless($untiedhash) {
1222: untie(%hash);
1223: }
1224: }
1225: if ($tiedparmhash) {
1226: unless($untiedparmhash) {
1227: untie(%parmhash);
1228: }
1229: }
1230: # Log our failure:
1231:
1232: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1233: "Could not tie coursemap $fn for $uri.</font>");
1234: $tiedhash = '';
1235: $tiedparmhash = '';
1236: my $i=0;
1237:
1238: # Keep on retrying the lock for 90 sec until we succeed.
1239:
1240: while($i<90) {
1241: $i++;
1242: sleep(1);
1243: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1244:
1245: # Got the lock, tie the hashes...the assumption in this code is
1246: # that some other worker thread has created the db files quite recently
1247: # so no load is needed:
1248:
1249: $lock = 1;
1250: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
1251: $tiedhash = 1;
1252: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_READER(),0640)) {
1253: $tiedparmhash = 1;
1254: if (-e "$fn.state") {
1255: $retfurl='/adm/navmaps';
1256:
1257: # BUG BUG: Side effect!
1258: # Should conditionalize on something so that we can use this
1259: # to load maps for courses that are not current?
1260: #
1261: &Apache::lonnet::appenv({"request.course.id" => $short,
1262: "request.course.fn" => $fn,
1263: "request.course.uri" => $uri,
1264: "request.course.tied" => time});
1265:
1266: $untiedhash = untie(%hash);
1267: $untiedparmhash = untie(%parmhash);
1268: $gotstate = 1;
1269: last;
1270: }
1271: $untiedparmhash = untie(%parmhash);
1272: }
1273: $untiedhash = untie(%hash);
1274: }
1275: }
1276: }
1277: if ($lock) {
1278: flock(LOCKFILE,LOCK_UN);
1279: $lock = 0;
1280: if ($tiedparmhash) {
1281: unless ($untiedparmhash) {
1282: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1283: 'Could not untie coursemap parmhash '.$fn.' for '.$uri.'.</font>');
1284: }
1285: }
1286: if ($tiedparmhash) {
1287: unless ($untiedhash) {
1288: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1289: 'Could not untie coursemap hash '.$fn.' for '.$uri.'.</font>');
1290: }
1291: }
1292: }
1293: }
1294: # I think this branch of code is all about what happens if we just did the stuff above,
1295: # but found that the state file did not exist...again if we'd just held the lock
1296: # would that have made this logic simpler..as generating all the files would be
1297: # an atomic operation with respect to the lock.
1298: #
1299: unless ($gotstate) {
1300: $lock = 0;
1301: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1302: 'Could not read statemap '.$fn.' for '.$uri.'.</font>');
1303: &unlink_tmpfiles($fn);
1304: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1305: $lock=1;
1306: }
1307: undef %randompick;
1308: undef %hiddenurl;
1309: undef %encurl;
1310: $errtext='';
1311: $retfrid='';
1312: #
1313: # Once more through the routine of tying and loading and so on.
1314: #
1315: if ($lock) {
1316: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_WRCREAT(),0640)) {
1317: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_WRCREAT(),0640)) {
1318: $gotstate = &build_tmp_hashes($uri,$fn,$short,\%cenv); # TODO: User dependent?
1319: unless ($gotstate) {
1320: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1321: 'Failed to write statemap at second attempt '.$fn.' for '.$uri.'.</font>');
1322: }
1323: unless (untie(%parmhash)) {
1324: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1325: 'Could not untie coursemap parmhash '.$fn.'.db for '.$uri.'.</font>');
1326: }
1327: } else {
1328: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1329: 'Could not tie coursemap '.$fn.'__parms.db for '.$uri.'.</font>');
1330: }
1331: unless (untie(%hash)) {
1332: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1333: 'Could not untie coursemap hash '.$fn.'.db for '.$uri.'.</font>');
1334: }
1335: } else {
1336: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1337: 'Could not tie coursemap '.$fn.'.db for '.$uri.'.</font>');
1338: }
1339: flock(LOCKFILE,LOCK_UN);
1340: $lock = 0;
1341: } else {
1342: # Failed to get the immediate lock.
1343:
1344: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1345: 'Could not obtain lock to tie coursemap hash '.$fn.'.db for '.$uri.'.</font>');
1346: }
1347: }
1348: close(LOCKFILE);
1349: unless (($errtext eq '') || ($env{'request.course.uri'} =~ m{^/uploaded/})) {
1350: &Apache::lonmsg::author_res_msg($env{'request.course.uri'},
1351: $errtext); # TODO: User dependent?
1352: }
1353: # ------------------------------------------------- Check for critical messages
1354:
1355: # Depends on user must parameterize this as well..or separate as this is:
1356: # more part of determining what someone sees on entering a course?
1357:
1358: my @what=&Apache::lonnet::dump('critical',$env{'user.domain'},
1359: $env{'user.name'});
1360: if ($what[0]) {
1361: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
1362: $retfurl='/adm/email?critical=display';
1363: }
1364: }
1365: return ($retfurl,$errtext);
1366: }
1367:
1368: #
1369: # This sub is called when the course hash and the param hash have been tied and
1370: # their lock file is held.
1371: # Parameters:
1372: # $uri - URI that identifies the course.
1373: # $fn - The base path/filename of the files that make up the context
1374: # being built.
1375: # $short - Short course name.
1376: # $cenvref - Reference to the course environment hash returned by
1377: # Apache::lonnet::coursedescription
1378: #
1379: # Assumptions:
1380: # The globals
1381: # %hash, %paramhash are tied to their gdbm files and we hold the lock on them.
1382: #
1383: sub build_tmp_hashes {
1384: my ($uri,$fn,$short,$cenvref) = @_;
1385:
1386: unless(ref($cenvref) eq 'HASH') {
1387: return;
1388: }
1389: my %cenv = %{$cenvref};
1390: my $gotstate = 0;
1391: %hash=(); # empty the global course and parameter hashes.
1392: %parmhash=();
1393: $errtext=''; # No error messages yet.
1394: $pc=0;
1395: &clear_mapalias_count();
1396: &processversionfile(%cenv);
1397:
1398: # URI Of the map file.
1399:
1400: my $furi=&Apache::lonnet::clutter($uri);
1401: #
1402: # the map staring points.
1403: #
1404: $hash{'src_0.0'}=&versiontrack($furi);
1405: $hash{'title_0.0'}=&Apache::lonnet::metadata($uri,'title');
1406: $hash{'ids_'.$furi}='0.0';
1407: $hash{'is_map_0.0'}=1;
1408:
1409: # Load the map.. note that loadmap may implicitly recurse if the map contains
1410: # sub-maps.
1411:
1412:
1413: &loadmap($uri,'0.0',$short);
1414:
1415: # The code below only executes if there is a starting point for the map>
1416: # Q/BUG??? If there is no start resource for the map should that be an error?
1417: #
1418:
1419: if (defined($hash{'map_start_'.$uri})) {
1420: &Apache::lonnet::appenv({"request.course.id" => $short,
1421: "request.course.fn" => $fn,
1422: "request.course.uri" => $uri,
1423: "request.course.tied" => time});
1424: $env{'request.course.id'}=$short;
1425: &traceroute('0',$hash{'map_start_'.$uri},'&');
1426: &accinit($uri,$short,$fn);
1427: &hiddenurls();
1428: }
1429: $errtext .= &get_mapalias_errors();
1430: # ------------------------------------------------------- Put versions into src
1431: foreach my $key (keys(%hash)) {
1432: if ($key=~/^src_/) {
1433: $hash{$key}=&putinversion($hash{$key});
1434: } elsif ($key =~ /^(map_(?:start|finish|pc)_)(.*)/) {
1435: my ($type, $url) = ($1,$2);
1436: my $value = $hash{$key};
1437: $hash{$type.&putinversion($url)}=$value;
1438: }
1439: }
1440: # ---------------------------------------------------------------- Encrypt URLs
1441: foreach my $id (keys(%encurl)) {
1442: # $hash{'src_'.$id}=&Apache::lonenc::encrypted($hash{'src_'.$id});
1443: $hash{'encrypted_'.$id}=1;
1444: }
1445: # ----------------------------------------------- Close hashes to finally store
1446: # --------------------------------- Routine must pass this point, no early outs
1447: $hash{'first_rid'}=$retfrid;
1448: my ($mapid,$resid)=split(/\./,$retfrid);
1449: $hash{'first_mapurl'}=$hash{'map_id_'.$mapid};
1450: my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$retfrid});
1451: $retfurl=&add_get_param($hash{'src_'.$retfrid},{ 'symb' => $symb });
1452: if ($hash{'encrypted_'.$retfrid}) {
1453: $retfurl=&Apache::lonenc::encrypted($retfurl,(&Apache::lonnet::allowed('adv') ne 'F'));
1454: }
1455: $hash{'first_url'}=$retfurl;
1456: # ---------------------------------------------------- Store away initial state
1457: {
1458: my $cfh;
1459: if (open($cfh,">$fn.state")) {
1460: print $cfh join("\n",@cond);
1461: $gotstate = 1;
1462: } else {
1463: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
1464: "Could not write statemap $fn for $uri.</font>");
1465: }
1466: }
1467: return $gotstate;
1468: }
1469:
1470: sub unlink_tmpfiles {
1471: my ($fn) = @_;
1472: my $file_dir = dirname($fn);
1473:
1474: if ("$file_dir/" eq LONCAPA::tempdir()) {
1475: my @files = qw (.db _symb.db .state _parms.db);
1476: foreach my $file (@files) {
1477: if (-e $fn.$file) {
1478: unless (unlink($fn.$file)) {
1479: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
1480: "Could not unlink ".$fn.$file."</font>");
1481: }
1482: }
1483: }
1484: }
1485: return;
1486: }
1487:
1488: # ------------------------------------------------------- Evaluate state string
1489:
1490: sub evalstate {
1491: my $fn=$env{'request.course.fn'}.'.state';
1492: my $state='';
1493: if (-e $fn) {
1494: my @conditions=();
1495: {
1496: open(my $fh,"<$fn");
1497: @conditions=<$fh>;
1498: close($fh);
1499: }
1500: my $safeeval = new Safe;
1501: my $safehole = new Safe::Hole;
1502: $safeeval->permit("entereval");
1503: $safeeval->permit(":base_math");
1504: $safeeval->deny(":base_io");
1505: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1506: foreach my $line (@conditions) {
1507: chomp($line);
1508: my ($condition,$weight)=split(/\:/,$line);
1509: if ($safeeval->reval($condition)) {
1510: if ($weight eq 'force') {
1511: $state.='3';
1512: } else {
1513: $state.='2';
1514: }
1515: } else {
1516: if ($weight eq 'stop') {
1517: $state.='0';
1518: } else {
1519: $state.='1';
1520: }
1521: }
1522: }
1523: }
1524: &Apache::lonnet::appenv({'user.state.'.$env{'request.course.id'} => $state});
1525: return $state;
1526: }
1527:
1528: # This block seems to have code to manage/detect doubly defined
1529: # aliases in maps.
1530:
1531: {
1532: my %mapalias_cache;
1533: sub count_mapalias {
1534: my ($value,$resid) = @_;
1535: push(@{ $mapalias_cache{$value} }, $resid);
1536: }
1537:
1538: sub get_mapalias_errors {
1539: my $error_text;
1540: foreach my $mapalias (sort(keys(%mapalias_cache))) {
1541: next if (scalar(@{ $mapalias_cache{$mapalias} } ) == 1);
1542: my $count;
1543: my $which =
1544: join('</li><li>',
1545: map {
1546: my $id = $_;
1547: if (exists($hash{'src_'.$id})) {
1548: $count++;
1549: }
1550: my ($mapid) = split(/\./,$id);
1551: &mt('Resource "[_1]" <br /> in Map "[_2]"',
1552: $hash{'title_'.$id},
1553: $hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$mapid}}});
1554: } (@{ $mapalias_cache{$mapalias} }));
1555: next if ($count < 2);
1556: $error_text .= '<div class="LC_error">'.
1557: &mt('Error: Found the mapalias "[_1]" defined multiple times.',
1558: $mapalias).
1559: '</div><ul><li>'.$which.'</li></ul>';
1560: }
1561: &clear_mapalias_count();
1562: return $error_text;
1563: }
1564: sub clear_mapalias_count {
1565: undef(%mapalias_cache);
1566: }
1567: }
1568: 1;
1569: __END__
1570:
1571: =head1 NAME
1572:
1573: Apache::lonuserstate - Construct and maintain state and binary representation
1574: of course for user
1575:
1576: =head1 SYNOPSIS
1577:
1578: Invoked by lonroles.pm.
1579:
1580: &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
1581:
1582: =head1 INTRODUCTION
1583:
1584: This module constructs and maintains state and binary representation
1585: of course for user.
1586:
1587: This is part of the LearningOnline Network with CAPA project
1588: described at http://www.lon-capa.org.
1589:
1590: =head1 SUBROUTINES
1591:
1592: =over
1593:
1594: =item loadmap()
1595:
1596: Loads map from disk
1597:
1598: =item simplify()
1599:
1600: Simplify expression
1601:
1602: =item traceroute()
1603:
1604: Build condition hash
1605:
1606: =item accinit()
1607:
1608: Cascading conditions, quick access, parameters
1609:
1610: =item readmap()
1611:
1612: Read map and all submaps
1613:
1614: =item evalstate()
1615:
1616: Evaluate state string
1617:
1618: =back
1619:
1620: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>