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