Annotation of loncom/lonmap.pm, revision 1.2
1.1 foxr 1: # The LearningOnline Network
2: #
3: # Read maps into a 'big hash'.
4: #
1.2 ! foxr 5: # $Id: lonmap.pm,v 1.1 2011/09/07 10:58:36 foxr Exp $
1.1 foxr 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
29: ###
30:
31: package lonmap;
32: use strict;
33:
34: #------------- Required external modules.
35:
36: use Error qw(:try);
37:
38: use HTML::TokeParser;
39:
40:
1.2 ! foxr 41: use LONCAPA;
1.1 foxr 42: use Apache::lonnet;
43:
44: #------------- File scoped variables:
45:
46: my $map_number = 1; # keep track of maps within the course.
47: my $course_id; # Will be the id of the course being read in.
48:
49: #
50: # The variables below are auxiliary hashes. They will be tacked onto the
51: # big hash though currently not used by clients.. you never know about later.
52: #
53:
54: my %randompick;
55: my %randompickseed;
56: my %randomorder;
57: my %encurl;
58: my %hiddenurl;
1.2 ! foxr 59: my %parmhash;
1.1 foxr 60: my @cond; # Array of conditions.
1.2 ! foxr 61: my $retfrid;
1.1 foxr 62: #
63: # Other stuff we make global (sigh) so that it does not need
64: # to be passed around all the time:
65: #
66:
67: my $username; # User for whom the map is being read.
68: my $userdomain; # Domain the user lives in.
69: my %mapalias_cache; # Keeps track of map aliases -> resources detects duplicates.
70:
71: #------------- Executable code:
72:
73:
74: #----------------------------------------------------------------
75: #
76: # General utilities:
77:
78:
79: #
80: # I _think_ this does common sub-expression simplification and
81: # optimization for condition strings...based on common pattern matching.
82: # Parameters:
83: # expression - the condition expression string.
84: # Returns:
85: # The optimized expression if an optimization could be found.
86: #
87: # NOTE:
88: # Added repetetive optimization..it's possible that an
89: # optimization results in an expression that can be recognized further in
90: # a subsequent optimization pass:
91: #
92:
93: sub simplify {
94: my $expression=shift;
95: my $prior = ''; # This is safe as a null expression is pretty optimal.
96:
97: while ($prior ne $expression) {
98: $prior = $expression; # Stop when the substitutions below do nothing.
99: # (0&1) = 1
100: $expression=~s/\(0\&([_\.\d]+)\)/$1/g;
101: # (8)=8
102: $expression=~s/\(([_\.\d]+)\)/$1/g;
103: # 8&8=8
104: $expression=~s/([^_\.\d])([_\.\d]+)\&\2([^_\.\d])/$1$2$3/g;
105: # 8|8=8
106: $expression=~s/([^_\.\d])([_\.\d]+)(?:\|\2)+([^_\.\d])/$1$2$3/g;
107: # (5&3)&4=5&3&4
108: $expression=~s/\(([_\.\d]+)((?:\&[_\.\d]+)+)\)\&([_\.\d]+[^_\.\d])/$1$2\&$3/g;
109: # (((5&3)|(4&6)))=((5&3)|(4&6))
110: $expression=~
111: s/\((\(\([_\.\d]+(?:\&[_\.\d]+)*\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+\))\)/$1/g;
112: # ((5&3)|(4&6))|(1&2)=(5&3)|(4&6)|(1&2)
113: $expression=~
114: s/\((\([_\.\d]+(?:\&[_\.\d]+)*\))((?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+)\)\|(\([_\.\d]+(?:\&[_\.\d]+)*\))/\($1$2\|$3\)/g;
115: }
116: return $expression;
117: }
118:
119:
120: #
121: # Merge the conditions into the big hash
122: # these will result in hash entries of the form:
123: # 'condition.n' where 'n' is the array index of the condition in the
124: # @cond array above.
125: #
126: # Parameters:
127: # $hash - big hashthat's being built up.
128: #
129: sub merge_conditions {
130: my $hash = shift;
131:
1.2 ! foxr 132: for (my $i = 0; $i < scalar(@cond); $i++) {
1.1 foxr 133: $hash->{'condition' . '.' . $i} = $cond[$i];
134: }
135: }
136:
137: # Merge the contents of a 'child hash' into a parent hash hanging it off another key.
138: # This is _not_ done by hanging a reference to the child hash as the parent may be
139: # bound to a GDBM file e.g. and shared by more than one process ..and references are
140: # pretty clearly not going to work across process boundaries.
141: #
142: # Parameters:
143: # $parent - The hash to which the child will be merged (reference)
144: # $key - The key in the parent hash on which the child elements will be hung.
145: # given a key named $childkey the final parent hash entry will be
146: # $parent . '.' $childkey
147: # $child - The hash whose contents we merge into the parent (reference)
148: #
149: sub merge_hash {
150: my ($parent, $key, $child) = @_;
151:
152: foreach my $childkey (keys (%$child)) {
153: $parent->{$key . '.' . $childkey} = $child->{$childkey};
154: }
155: }
156:
157: #----------------------------------------------------------------------------------
158: #
159: # Code to keep track of map aliases and to determine if there are doubly
160: # defined aliases.
161: #
162:
163: #
164: # Maintains the mapalias hash. This is a hash of arrays. Each array
165: # is indexed by the alias and contains the set of resource ids pointed to by that
166: # alias. In an ideal world, there will only be one element in each array.
167: # The point of this, however is to determine which aliases might be doubley defined
168: # due to map nesting e.g.
169: #
170: # Parameters:
171: # $value - Alias name.
172: # $resid - Resource id pointed to by the alias.
173: #
174: #
175: sub count_mapalias {
176: my ($value,$resid) = @_;
177: push(@{ $mapalias_cache{$value} }, $resid);
178: }
179: #
180: # Looks at each key in the mapalias hash and, for each case where an
181: # alias points to more than one value adds an error text to the
182: # result string.'
183: #
184: # Parameters:
1.2 ! foxr 185: # hash - Reference to the hash we are trying t build up.
1.1 foxr 186: # Implicit inputs
187: # %mapalias - a hash that is indexed by map aliases and contains for each key
188: # an array of the resource id's the alias 'points to'.
189: # Returns:
190: # A hopefully empty string of messages that descsribe the aliases that have more
191: # than one value. This string is formatted like an html list.
192: #
193: #
194: sub get_mapalias_errors {
1.2 ! foxr 195: my $hash = shift;
1.1 foxr 196: my $error_text;
197: foreach my $mapalias (sort(keys(%mapalias_cache))) {
198: next if (scalar(@{ $mapalias_cache{$mapalias} } ) == 1);
199: my $count;
200: my $which =
201: join('</li><li>',
202: map {
203: my $id = $_;
1.2 ! foxr 204: if (exists($hash->{'src_'.$id})) {
1.1 foxr 205: $count++;
206: }
207: my ($mapid) = split(/\./,$id);
208: &mt('Resource "[_1]" <br /> in Map "[_2]"',
1.2 ! foxr 209: $hash->{'title_'.$id},
! 210: $hash->{'title_'.$hash->{'ids_'.$hash->{'map_id_'.$mapid}}});
1.1 foxr 211: } (@{ $mapalias_cache{$mapalias} }));
212: next if ($count < 2);
213: $error_text .= '<div class="LC_error">'.
214: &mt('Error: Found the mapalias "[_1]" defined multiple times.',
215: $mapalias).
216: '</div><ul><li>'.$which.'</li></ul>';
217: }
218: &clear_mapalias_count();
219: return $error_text;
220: }
221: #
222: # Clears the map aliase hash.
223: #
224: sub clear_mapalias_count {
225: undef(%mapalias_cache);
226: }
227:
228: #----------------------------------------------------------------
229: #
230: # Code dealing with resource versions.
231: #
232:
233: #
1.2 ! foxr 234: # Put a version into a src element of a hash or url:
! 235: #
! 236: # Parameters:
! 237: # uri - URI into which the version must be added.
! 238: # hash - Reference to the hash being built up.
! 239: # short- Short coursename.
! 240: #
! 241:
! 242: sub putinversion {
! 243: my ($uri, $hash, $short) = @_;
! 244: my $key=$short.'_'.&Apache::lonnet::clutter($uri);
! 245: if ($hash->{'version_'.$uri}) {
! 246: my $version=$hash->{'version_'.$uri};
! 247: if ($version eq 'mostrecent') { return $uri; }
! 248: if ($version eq &Apache::lonnet::getversion(
! 249: &Apache::lonnet::filelocation('',$uri)))
! 250: { return $uri; }
! 251: $uri=~s/\.(\w+)$/\.$version\.$1/;
! 252: }
! 253: &Apache::lonnet::do_cache_new('courseresversion',$key,&Apache::lonnet::declutter($uri),600);
! 254: return $uri;
! 255: }
! 256:
! 257:
! 258: #
1.1 foxr 259: # Create hash entries for each version of the course.
260: # Parameters:
261: # $cenv - Reference to a course environment from lonnet::coursedescription.
262: # $hash - Reference to a hash that will be populated.
263:
264: #
265: sub process_versions {
266: my ($cenv, $hash) = @_;
267:
268:
269: my %versions = &Apache::lonnet::dump('resourceversions',
270: $cenv->{'domain'},
271: $cenv->{'num'});
272:
273: foreach my $ver (keys (%versions)) {
274: if ($ver =~/^error\:/) { # lonc/lond transaction failed.
275: throw Error::Simple('lonc/lond returned error: ' . $ver);
276: }
277: $hash->{'version_'.$ver} = $versions{$ver};
278: }
279: }
280:
281: #
282: # Generate text for a version discrepancy error:
283: # Parameters:
284: # $uri - URI of the resource.
285: # $used - Version used.
286: # $unused - Veresion of duplicate.
287: #
288: sub versionerror {
289: my ($uri, $used, $unused) = @_;
290: my ($uri,$usedversion,$unusedversion)=@_;
291: return '<br />'.
292: &mt('Version discrepancy: resource [_1] included in both version [_2] and version [_3]. Using version [_2].',
293: $uri,$used,$unused).'<br />';
294:
295: }
296:
297: # Removes the version number from a URI and returns the resulting
298: # URI (e.g. mumbly.version.stuff => mumbly.stuff).
299: #
300: # If the URI has not been seen with a version before the
301: # hash{'version_'.resultingURI} is set to the version number.
302: # If the hash has already been seen, but differs then
303: # an error is raised.
304: #
305: # Parameters:
306: # $uri - potentially with a version.
307: # $hash - reference to a hash to fill in.
308: # Returns:
309: # URI with the version cut out.
310: #
311: sub vesiontrack {
312: my ($uri, $hash) = @_;
313:
314:
315: if ($uri=~/\.(\d+)\.\w+$/) { # URI like *.n.text it's version 'n'
316: my $version=$1;
317: $uri=~s/\.\d+\.(\w+)$/\.$1/; # elide the version.
318: unless ($hash->{'version_'.$uri}) {
319: $hash->{'version_'.$uri}=$version;
320: } elsif ($version!=$hash->{'version_'.$uri}) {
1.2 ! foxr 321: throw Error::Simple(&versionerror($uri, $hash->{'version_'.$uri}, $version));
1.1 foxr 322: }
323: }
324: return $uri;
325: }
326: #
327: # Appends the version of a resource to its uri and also caches the
328: # URI (contents?) on the local server
329: #
330: # Parameters:
331: # $uri - URI of the course (without version informatino.
332: # $hash - What we have of the big hash.
333: #
334: # Side-Effects:
335: # The URI is cached by memcached.
336: #
337: # Returns:
338: # The version appended URI.
339: #
340: sub append_version {
341: my ($uri, $hash) = @_;
342:
343: # Create the key for the cache entry.
344:
345: my $key = $course_id . '_' . &Apache::lonnet::clutter($uri);
346:
347: # If there is a version it will already be in the hash:
348:
349: if ($hash->{'version_' . $uri}) {
350: my $version = $hash->{'version_' . $uri};
351: if ($version eq 'mostrecent') {
352: return $uri; # Most recent version does not require decoration (or caching?).
353: }
354: if ($version eq
355: &Apache::lonnet::getversion(&Apache::lonnet::filelocation('', $uri))) {
356: return $uri; # version matches the most recent file version?
357: }
358: $uri =~ s/\.(\w+)$/\.$version\.$1/; # insert the versino prior to the last .word.
359: }
360:
361: # cache the version:
362:
363: &Apache::lonnet::do_cache_new('courseresversion', $key,
364: &Apache::lonnet::declutter($uri), 600);
365:
366: return $uri;
367:
368: }
369: #--------------------------------------------------------------------------------
370: # Post processing subs:
371: sub hiddenurls {
372: my $hash = shift;
373:
374: my $randomoutentry='';
375: foreach my $rid (keys %randompick) {
376: my $rndpick=$randompick{$rid};
377: my $mpc=$hash->{'map_pc_'.$hash->{'src_'.$rid}};
378: # ------------------------------------------- put existing resources into array
379: my @currentrids=();
380: foreach my $key (sort(keys(%$hash))) {
381: if ($key=~/^src_($mpc\.\d+)/) {
382: if ($hash->{'src_'.$1}) { push @currentrids, $1; }
383: }
384: }
385: # rids are number.number and we want to numercially sort on
386: # the second number
387: @currentrids=sort {
388: my (undef,$aid)=split(/\./,$a);
389: my (undef,$bid)=split(/\./,$b);
390: $aid <=> $bid;
391: } @currentrids;
392: next if ($#currentrids<$rndpick);
393: # -------------------------------- randomly eliminate the ones that should stay
394: my (undef,$id)=split(/\./,$rid);
395: if ($randompickseed{$rid}) { $id=$randompickseed{$rid}; }
396: my $rndseed=&Apache::lonnet::rndseed($id); # use id instead of symb
397: &Apache::lonnet::setup_random_from_rndseed($rndseed);
398: my @whichids=&Math::Random::random_permuted_index($#currentrids+1);
399: for (my $i=1;$i<=$rndpick;$i++) { $currentrids[$whichids[$i]]=''; }
400: #&Apache::lonnet::logthis("$id,$rndseed,".join(':',@whichids));
401: # -------------------------------------------------------- delete the leftovers
402: for (my $k=0; $k<=$#currentrids; $k++) {
403: if ($currentrids[$k]) {
404: $hash->{'randomout_'.$currentrids[$k]}=1;
405: my ($mapid,$resid)=split(/\./,$currentrids[$k]);
406: $randomoutentry.='&'.
407: &Apache::lonnet::encode_symb($hash->{'map_id_'.$mapid},
408: $resid,
409: $hash->{'src_'.$currentrids[$k]}
410: ).'&';
411: }
412: }
413: }
414: # ------------------------------ take care of explicitly hidden urls or folders
415: foreach my $rid (keys %hiddenurl) {
416: $hash->{'randomout_'.$rid}=1;
417: my ($mapid,$resid)=split(/\./,$rid);
418: $randomoutentry.='&'.
419: &Apache::lonnet::encode_symb($hash->{'map_id_'.$mapid},$resid,
420: $hash->{'src_'.$rid}).'&';
421: }
422: # --------------------------------------- add randomout to the hash.
423: if ($randomoutentry) {
424: $hash->{'acc.randomout'} = $randomoutentry;
425:
426: }
427: }
428:
429: #
430: # It's not so clear to me what this sub does.
431: #
432: # Parameters
433: # uri - URI from the course description hash.
434: # short - Course short name.
435: # fn - Course filename.
436: # hash - Reference to the big hash as filled in so far
437: #
438:
439: sub accinit {
1.2 ! foxr 440: my ($uri, $short, $fn, $hash)=@_;
1.1 foxr 441: my %acchash=();
442: my %captured=();
443: my $condcounter=0;
444: $acchash{'acc.cond.'.$short.'.0'}=0;
445:
446: # This loop is only interested in conditions and
447: # parameters in the big hash:
448:
449: foreach my $key (keys(%$hash)) {
450:
451: # conditions:
452:
453: if ($key=~/^conditions/) {
454: my $expr=$hash->{$key};
455:
456: # try to find and factor out common sub-expressions
457: # Any subexpression that is found is simplified, removed from
458: # the original condition expression and the simplified sub-expression
459: # substituted back in to the epxression..I'm not actually convinced this
460: # factors anything out...but instead maybe simplifies common factors(?)
461:
462: foreach my $sub ($expr=~m/(\(\([_\.\d]+(?:\&[_\.\d]+)+\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)+\))+\))/g) {
463: my $orig=$sub;
464:
465: my ($factor) = ($sub=~/\(\(([_\.\d]+\&(:?[_\.\d]+\&)*)(?:[_\.\d]+\&*)+\)(?:\|\(\1(?:[_\.\d]+\&*)+\))+\)/);
466: next if (!defined($factor));
467:
468: $sub=~s/\Q$factor\E//g;
469: $sub=~s/^\(/\($factor\(/;
470: $sub.=')';
471: $sub=simplify($sub);
472: $expr=~s/\Q$orig\E/$sub/;
473: }
474: $hash->{$key}=$expr;
475:
476: # If not yet seen, record in acchash and that we've seen it.
477:
478: unless (defined($captured{$expr})) {
479: $condcounter++;
480: $captured{$expr}=$condcounter;
481: $acchash{'acc.cond.'.$short.'.'.$condcounter}=$expr;
482: }
483: # Parameters:
484:
485: } elsif ($key=~/^param_(\d+)\.(\d+)/) {
486: my $prefix=&Apache::lonnet::encode_symb($hash->{'map_id_'.$1},$2,
487: $hash->{'src_'.$1.'.'.$2});
488: foreach my $param (split(/\&/,$hash->{$key})) {
489: my ($typename,$value)=split(/\=/,$param);
490: my ($type,$name)=split(/\:/,$typename);
491: $parmhash{$prefix.'.'.&unescape($name)}=
492: &unescape($value);
493: $parmhash{$prefix.'.'.&unescape($name).'.type'}=
494: &unescape($type);
495: }
496: }
497: }
498: # This loop only processes id entries in the big hash.
499:
500: foreach my $key (keys(%$hash)) {
501: if ($key=~/^ids/) {
502: foreach my $resid (split(/\,/,$hash->{$key})) {
503: my $uri=$hash->{'src_'.$resid};
504: my ($uripath,$urifile) =
505: &Apache::lonnet::split_uri_for_cond($uri);
506: if ($uripath) {
507: my $uricond='0';
508: if (defined($hash->{'conditions_'.$resid})) {
509: $uricond=$captured{$hash->{'conditions_'.$resid}};
510: }
511: if (defined($acchash{'acc.res.'.$short.'.'.$uripath})) {
512: if ($acchash{'acc.res.'.$short.'.'.$uripath}=~
513: /(\&\Q$urifile\E\:[^\&]*)/) {
514: my $replace=$1;
515: my $regexp=$replace;
516: #$regexp=~s/\|/\\\|/g;
517: $acchash{'acc.res.'.$short.'.'.$uripath} =~
518: s/\Q$regexp\E/$replace\|$uricond/;
519: } else {
520: $acchash{'acc.res.'.$short.'.'.$uripath}.=
521: $urifile.':'.$uricond.'&';
522: }
523: } else {
524: $acchash{'acc.res.'.$short.'.'.$uripath}=
525: '&'.$urifile.':'.$uricond.'&';
526: }
527: }
528: }
529: }
530: }
531: $acchash{'acc.res.'.$short.'.'}='&:0&';
532: my $courseuri=$uri;
533: $courseuri=~s/^\/res\///;
534: my $regexp = 1;
535:
536: &merge_hash($hash, '', \%acchash); # there's already an acc prefix in the hash keys.
537:
538:
539: }
540:
541:
542: #
543: # Traces a route recursively through the map after it has been loaded
544: # (I believe this really visits each resource that is reachable fromt he
545: # start top node.
546: #
547: # - Marks hidden resources as hidden.
548: # - Marks which resource URL's must be encrypted.
549: # - Figures out (if necessary) the first resource in the map.
550: # - Further builds the chunks of the big hash that define how
551: # conditions work
552: #
553: # Note that the tracing strategy won't visit resources that are not linked to
554: # anything or islands in the map (groups of resources that form a path but are not
555: # linked in to the path that can be traced from the start resource...but that's ok
556: # because by definition, those resources are not reachable by users of the course.
557: #
558: # Parameters:
559: # sofar - _URI of the prior entry or 0 if this is the top.
560: # rid - URI of the resource to visit.
561: # beenhere - list of resources (each resource enclosed by &'s) that have
562: # already been visited.
563: # encflag - If true the resource that resulted in a recursive call to us
564: # has an encoded URL (which means contained resources should too).
565: # hdnflag - If true,the resource that resulted in a recursive call to us
566: # was hidden (which means contained resources should be hidden too).
567: # hash - Reference to the hash we are traversing.
568: # Returns
569: # new value indicating how far the map has been traversed (the sofar).
570: #
571: sub traceroute {
1.2 ! foxr 572: my ($sofar, $rid, $beenhere, $encflag, $hdnflag, $hash)=@_;
1.1 foxr 573: my $newsofar=$sofar=simplify($sofar);
574:
575: unless ($beenhere=~/\&\Q$rid\E\&/) {
576: $beenhere.=$rid.'&';
577: my ($mapid,$resid)=split(/\./,$rid);
578: my $symb=&Apache::lonnet::encode_symb($hash->{'map_id_'.$mapid},$resid,
579: $hash->{'src_'.$rid});
580: my $hidden=&Apache::lonnet::EXT('resource.0.hiddenresource',$symb);
581:
582: if ($hdnflag || lc($hidden) eq 'yes') {
583: $hiddenurl{$rid}=1;
584: }
585: if (!$hdnflag && lc($hidden) eq 'no') {
586: delete($hiddenurl{$rid});
587: }
588:
589: my $encrypt=&Apache::lonnet::EXT('resource.0.encrypturl',$symb);
590: if ($encflag || lc($encrypt) eq 'yes') { $encurl{$rid}=1; }
591:
592: if (($retfrid eq '') && ($hash->{'src_'.$rid})
593: && ($hash->{'src_'.$rid}!~/\.sequence$/)) {
594: $retfrid=$rid;
595: }
596:
597: if (defined($hash->{'conditions_'.$rid})) {
598: $hash->{'conditions_'.$rid}=simplify(
599: '('.$hash->{'conditions_'.$rid}.')|('.$sofar.')');
600: } else {
601: $hash->{'conditions_'.$rid}=$sofar;
602: }
603:
604: # if the expression is just the 0th condition keep it
605: # otherwise leave a pointer to this condition expression
606:
607: $newsofar = ($sofar eq '0') ? $sofar : '_'.$rid;
608:
609: # Recurse if the resource is a map:
610:
611: if (defined($hash->{'is_map_'.$rid})) {
612: if (defined($hash->{'map_start_'.$hash->{'src_'.$rid}})) {
613: $sofar=$newsofar=
614: &traceroute($sofar,
615: $hash->{'map_start_'.$hash->{'src_'.$rid}},
616: $beenhere,
617: $encflag || $encurl{$rid},
618: $hdnflag || $hiddenurl{$rid});
619: }
620: }
621:
622: # Processes links to this resource:
623: # - verify the existence of any conditionals on the link to here.
624: # - Recurse to any resources linked to us.
625: #
626: if (defined($hash->{'to_'.$rid})) {
627: foreach my $id (split(/\,/,$hash->{'to_'.$rid})) {
628: my $further=$sofar;
629: #
630: # If there's a condition associated with this link be sure
631: # it's been defined else that's an error:
632: #
633: if ($hash->{'undercond_'.$id}) {
634: if (defined($hash->{'condid_'.$hash->{'undercond_'.$id}})) {
635: $further=simplify('('.'_'.$rid.')&('.
636: $hash->{'condid_'.$hash->{'undercond_'.$id}}.')');
637: } else {
1.2 ! foxr 638: my $errtext.=&mt('<br />Undefined condition ID: [_1]',$hash->{'undercond_'.$id});
1.1 foxr 639: throw Error::Simple($errtext);
640: }
641: }
642: # Recurse to resoruces that have to's to us.
643: $newsofar=&traceroute($further,$hash->{'goesto_'.$id},$beenhere,
644: $encflag,$hdnflag);
645: }
646: }
647: }
648: return $newsofar;
649: }
650:
651:
652: #---------------------------------------------------------------------------------
653: #
654: # Map parsing code:
655: #
656:
657: #
658: # Parse the <param> tag. for most parameters, the only action is to define/extend
659: # a has entry for {'param_{refid}'} where refid is the resource the parameter is
660: # attached to and the value built up is an & separated list of parameters of the form:
661: # type:part.name=value
662: #
663: # In addition there is special case code for:
664: # - randompick
665: # - randompickseed
666: # - randomorder
667: #
668: # - encrypturl
669: # - hiddenresource
670: #
671: # Parameters:
672: # token - The token array from HTML::TokeParse we mostly care about element [2]
673: # which is a hash of attribute => values supplied in the tag
674: # (remember this sub is only processing start tag tokens).
675: # mno - Map number. This is used to qualify resource ids within a map
676: # to make them unique course wide (a process known as uniquifaction).
677: # hash - Reference to the hash we are building.
678: #
679: sub parse_param {
680: my ($token, $mno, $hash) = @_;
681:
682: # Qualify the reference and name by the map number and part number.
683: # if no explicit part number is supplied, 0 is the implicit part num.
684:
685: my $referid=$mno.'.'.$token->[2]->{'to'}; # Resource param applies to.
686: my $name=$token->[2]->{'name'}; # Name of parameter
687: my $part;
688:
689:
690: if ($name=~/^parameter_(.*)_/) {
691: $part=$1;
692: } else {
693: $part=0;
694: }
695:
696: # Peel the parameter_ off the parameter name.
697:
698: $name=~s/^.*_([^_]*)$/$1/;
699:
700: # The value is:
701: # type.part.name.value
702:
703: my $newparam=
704: &escape($token->[2]->{'type'}).':'.
705: &escape($part.'.'.$name).'='.
706: &escape($token->[2]->{'value'});
707:
708: # The hash key is param_resourceid.
709: # Multiple parameters for a single resource are & separated in the hash.
710:
711:
712: if (defined($hash->{'param_'.$referid})) {
713: $hash->{'param_'.$referid}.='&'.$newparam;
714: } else {
715: $hash->{'param_'.$referid}=''.$newparam;
716: }
717: #
718: # These parameters have to do with randomly selecting
719: # resources, therefore a separate hash is also created to
720: # make it easy to locate them when actually computing the resource set later on
721: # See the code conditionalized by ($randomize) in read_map().
722:
723: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompick$/) { # Random selection turned on
724: $randompick{$referid}=$token->[2]->{'value'};
725: }
726: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompickseed$/) { # Randomseed provided.
727: $randompickseed{$referid}=$token->[2]->{'value'};
728: }
729: if ($token->[2]->{'name'}=~/^parameter_(0_)*randomorder$/) { # Random order turned on.
730: $randomorder{$referid}=$token->[2]->{'value'};
731: }
732:
733: # These parameters have to do with how the URLs of resources are presented to
734: # course members(?). encrypturl presents encypted url's while
735: # hiddenresource hides the URL.
736: #
737:
738: if ($token->[2]->{'name'}=~/^parameter_(0_)*encrypturl$/) {
739: if ($token->[2]->{'value'}=~/^yes$/i) {
740: $encurl{$referid}=1;
741: }
742: }
743: if ($token->[2]->{'name'}=~/^parameter_(0_)*hiddenresource$/) {
744: if ($token->[2]->{'value'}=~/^yes$/i) {
745: $hiddenurl{$referid}=1;
746: }
747: }
748:
749: }
750:
751:
752: #
753: # Parses a resource tag to produce the value to push into the
754: # map_ids array.
755: #
756: #
757: # Information about the actual type of resource is provided by the file extension
758: # of the uri (e.g. .problem, .sequence etc. etc.).
759: #
760: # Parameters:
761: # $token - A token from HTML::TokeParser
762: # This is an array that describes the most recently parsed HTML item.
763: # $lpc - Map nesting level (?)
764: # $ispage - True if this resource is encapsulated in a .page (assembled resourcde).
765: # $uri - URI of the enclosing resource.
766: # $hash - Reference to the hash we are building.
767: #
768: # Returns:
769: # Value of the id attribute of the tag.
770: #
771: # Note:
772: # The token is an array that contains the following elements:
773: # [0] => 'S' indicating this is a start token
774: # [1] => 'resource' indicating this tag is a <resource> tag.
775: # [2] => Hash of attribute =>value pairs.
776: # [3] => @(keys [2]).
777: # [4] => unused.
778: #
779: # The attributes of the resourcde tag include:
780: #
781: # id - The resource id.
782: # src - The URI of the resource.
783: # type - The resource type (e.g. start and finish).
784: # title - The resource title.
785: #
786:
787: sub parse_resource {
788: my ($token,$lpc,$ispage,$uri, $hash) = @_;
789:
790: # I refuse to countenance code like this that has
791: # such a dirty side effect (and forcing this sub to be called within a loop).
792: #
793: # if ($token->[2]->{'type'} eq 'zombie') { next; }
794: #
795: # The original code both returns _and_ skips to the next pass of the >caller's<
796: # loop, that's just dirty.
797: #
798:
799: # Zombie resources don't produce anything useful.
800:
801: if ($token->[2]->{'type'} eq 'zombie') {
802: return undef;
803: }
804:
805: my $rid=$lpc.'.'.$token->[2]->{'id'}; # Resource id in hash is levelcounter.id-in-xml.
806:
807: # Save the hash element type and title:
808:
809: $hash->{'kind_'.$rid}='res';
810: $hash->{'title_'.$rid}=$token->[2]->{'title'};
811:
812: # Get the version free URI for the resource.
813: # If a 'version' attribute was supplied, and this resource's version
814: # information has not yet been stored, store it.
815: #
816:
817:
818: my $turi=&versiontrack($token->[2]->{'src'});
819: if ($token->[2]->{'version'}) {
820: unless ($hash->{'version_'.$turi}) {
821:
822: #Where does the value of $1 below come from?
823: #$1 for the regexps in versiontrack should have gone out of scope.
824: #
825: # I think this may be dead code since versiontrack ought to set
826: # this hash element(?).
827: #
828: $hash->{'version_'.$turi}=$1;
829: }
830: }
831: # Pull out the title and do entity substitution on &colon
832: # Q: Why no other entity substitutions?
833:
834: my $title=$token->[2]->{'title'};
835: $title=~s/\&colon\;/\:/gs;
836:
837:
838:
839: # I think the point of all this code is to construct a final
840: # URI that apache and its rewrite rules can use to
841: # fetch the resource. Thi s sonly necessary if the resource
842: # is not a page. If the resource is a page then it must be
843: # assembled (at fetch time?).
844:
845: unless ($ispage) {
846: $turi=~/\.(\w+)$/;
847: my $embstyle=&Apache::loncommon::fileembstyle($1);
848: if ($token->[2]->{'external'} eq 'true') { # external
849: $turi=~s/^https?\:\/\//\/adm\/wrapper\/ext\//;
850: } elsif ($turi=~/^\/*uploaded\//) { # uploaded
851: if (($embstyle eq 'img')
852: || ($embstyle eq 'emb')
853: || ($embstyle eq 'wrp')) {
854: $turi='/adm/wrapper'.$turi;
855: } elsif ($embstyle eq 'ssi') {
856: #do nothing with these
857: } elsif ($turi!~/\.(sequence|page)$/) {
858: $turi='/adm/coursedocs/showdoc'.$turi;
859: }
860: } elsif ($turi=~/\S/) { # normal non-empty internal resource
861: my $mapdir=$uri;
862: $mapdir=~s/[^\/]+$//;
863: $turi=&Apache::lonnet::hreflocation($mapdir,$turi);
864: if (($embstyle eq 'img')
865: || ($embstyle eq 'emb')
866: || ($embstyle eq 'wrp')) {
867: $turi='/adm/wrapper'.$turi;
868: }
869: }
870: }
871: # Store reverse lookup, remove query string resource 'ids'_uri => resource id.
872: # If the URI appears more than one time in the sequence, it's resourcde
873: # id's are constructed as a comma spearated list.
874:
875: my $idsuri=$turi;
876: $idsuri=~s/\?.+$//;
877: if (defined($hash->{'ids_'.$idsuri})) {
878: $hash->{'ids_'.$idsuri}.=','.$rid;
879: } else {
880: $hash->{'ids_'.$idsuri}=''.$rid;
881: }
882:
883:
884:
885: if ($turi=~/\/(syllabus|aboutme|navmaps|smppg|bulletinboard|viewclasslist)$/) {
886: $turi.='?register=1';
887: }
888:
889:
890: # resource id lookup: 'src'_resourc-di => URI decorated with a query
891: # parameter as above if necessary due to the resource type.
892:
893: $hash->{'src_'.$rid}=$turi;
894:
895: # Mark the external-ness of the resource:
896:
897: if ($token->[2]->{'external'} eq 'true') {
898: $hash->{'ext_'.$rid}='true:';
899: } else {
900: $hash->{'ext_'.$rid}='false:';
901: }
902:
903: # If the resource is a start/finish resource set those
904: # entries in the has so that navigation knows where everything starts.
905: # If there is a malformed sequence that has no start or no finish
906: # resource, should this be detected and errors thrown? How would such a
907: # resource come into being other than being manually constructed by a person
908: # and then uploaded? Could that happen if an author decided a sequence was almost
909: # right edited it by hand and then reuploaded it to 'fix it' but accidently cut the
910: # start or finish resources?
911: #
912: # All resourcess also get a type_id => (start | finish | normal) hash entr.
913: #
914: if ($token->[2]->{'type'}) {
915: $hash->{'type_'.$rid}=$token->[2]->{'type'};
916: if ($token->[2]->{'type'} eq 'start') {
917: $hash->{'map_start_'.$uri}="$rid";
918: }
919: if ($token->[2]->{'type'} eq 'finish') {
920: $hash->{'map_finish_'.$uri}="$rid";
921: }
922: } else {
923: $hash->{'type_'.$rid}='normal';
924: }
925:
926: # Sequences end pages are constructed entities. They require that the
927: # map that defines _them_ be loaded as well into the hash...with this resourcde
928: # as the base of the nesting.
929: # Resources like that are also marked with is_map_id => 1 entries.
930: #
931:
932: if (($turi=~/\.sequence$/) ||
933: ($turi=~/\.page$/)) {
934: $hash->{'is_map_'.$rid}=1;
935: &read_map($turi,$rid, $hash);
936: }
937: return $token->[2]->{'id'};
938: }
939:
940: # Links define how you are allowed to move from one resource to another.
941: # They are the transition edges in the directed graph that a map is.
942: # This sub takes informatino from a <link> tag and constructs the
943: # navigation bits and pieces of a map. There is no requirement that the
944: # resources that are linke are already defined, however clearly the map is
945: # badly broken if they are not _eventually_ defined.
946: #
947: # Note that links can be unconditional or conditional.
948: #
949: # Parameters:
950: # linkpc - The link counter for this level of map nesting (this is
951: # reset to zero by read_map prior to starting to process
952: # links for map).
953: # lpc - The map level ocounter (how deeply nested this map is in
954: # the hierarchy of maps that are recursively read in.
955: # to - resource id (within the XML) of the target of the edge.
956: # from - resource id (within the XML) of the source of the edge.
957: # condition- id of condition associated with the edge (also within the XML).
958: # hash - reference to the hash we are building.
959:
960: #
961:
962: sub make_link {
963: my ($linkpc,$lpc,$to,$from,$condition, $hash) = @_;
964:
965: # Compute fully qualified ids for the link, the
966: # and from/to by prepending lpc.
967: #
968:
969: my $linkid=$lpc.'.'.$linkpc;
970: my $goesto=$lpc.'.'.$to;
971: my $comesfrom=$lpc.'.'.$from;
972: my $undercond=0;
973:
974:
975: # If there is a condition, qualify it with the level counter.
976:
977: if ($condition) {
978: $undercond=$lpc.'.'.$condition;
979: }
980:
981: # Links are represnted by:
982: # goesto_.fuullyqualifedlinkid => fully qualified to
983: # comesfrom.fullyqualifiedlinkid => fully qualified from
984: # undercond_.fullyqualifiedlinkid => fully qualified condition id.
985:
986: $hash->{'goesto_'.$linkid}=$goesto;
987: $hash->{'comesfrom_'.$linkid}=$comesfrom;
988: $hash->{'undercond_'.$linkid}=$undercond;
989:
990: # In addition:
991: # to_.fully qualified from => comma separated list of
992: # link ids with that from.
993: # Similarly:
994: # from_.fully qualified to => comma separated list of link ids`
995: # with that to.
996: # That allows us given a resource id to know all edges that go to it
997: # and leave from it.
998: #
999:
1000: if (defined($hash->{'to_'.$comesfrom})) {
1001: $hash->{'to_'.$comesfrom}.=','.$linkid;
1002: } else {
1003: $hash->{'to_'.$comesfrom}=''.$linkid;
1004: }
1005: if (defined($hash->{'from_'.$goesto})) {
1006: $hash->{'from_'.$goesto}.=','.$linkid;
1007: } else {
1008: $hash->{'from_'.$goesto}=''.$linkid;
1009: }
1010: }
1011:
1012: # ------------------------------------------------------------------- Condition
1013: #
1014: # Processes <condition> tags, storing sufficient information about them
1015: # in the hash so that they can be evaluated and used to conditionalize
1016: # what is presented to the student.
1017: #
1018: # these can have the following attributes
1019: #
1020: # id = A unique identifier of the condition within the map.
1021: #
1022: # value = Is a perl script-let that, when evaluated in safe space
1023: # determines whether or not the condition is true.
1024: # Normally this takes the form of a test on an Apache::lonnet::EXT call
1025: # to find the value of variable associated with a resource in the
1026: # map identified by a mapalias.
1027: # Here's a fragment of XML code that illustrates this:
1028: #
1029: # <param to="5" value="mainproblem" name="parameter_0_mapalias" type="string" />
1030: # <resource src="" id="1" type="start" title="Start" />
1031: # <resource src="/res/msu/albertel/b_and_c/p1.problem" id="5" title="p1.problem" />
1032: # <condition value="&EXT('user.resource.resource.0.tries','mainproblem')
1033: # <2 " id="61" type="stop" />
1034: # <link to="5" index="1" from="1" condition="61" />
1035: #
1036: # In this fragment:
1037: # - The param tag establishes an alias to resource id 5 of 'mainproblem'.
1038: # - The resource that is the start of the map is identified.
1039: # - The resource tag identifies the resource associated with this tag
1040: # and gives it the id 5.
1041: # - The condition is true if the tries variable associated with mainproblem
1042: # is less than 2 (that is the user has had more than 2 tries).
1043: # The condition type is a stop condition which inhibits(?) the associated
1044: # link if the condition is false.
1045: # - The link to resource 5 from resource 1 is affected by this condition.
1046: #
1047: # type = Type of the condition. The type determines how the condition affects the
1048: # link associated with it and is one of
1049: # - 'force'
1050: # - 'stop'
1051: # anything else including not supplied..which treated as:
1052: # - 'normal'.
1053: # Presumably maps get created by the resource assembly tool and therefore
1054: # illegal type values won't squirm their way into the XML.
1055: # hash - Reference to the hash we are trying to build up.
1056: #
1057: # Side effects:
1058: # - The kind_level-qualified-condition-id hash element is set to 'cond'.
1059: # - The condition text is pushed into the cond array and its element number is
1060: # set in the condid_level-qualified-condition-id element of the hash.
1061: # - The condition type is colon appneded to the cond array element for this condition.
1062: sub parse_condition {
1063: my ($token, $lpc, $hash) = @_;
1064: my $rid=$lpc.'.'.$token->[2]->{'id'};
1065:
1066: $hash->{'kind_'.$rid}='cond';
1067:
1068: my $condition = $token->[2]->{'value'};
1069: $condition =~ s/[\n\r]+/ /gs;
1070: push(@cond, $condition);
1071: $hash->{'condid_'.$rid}=$#cond;
1072: if ($token->[2]->{'type'}) {
1073: $cond[$#cond].=':'.$token->[2]->{'type'};
1074: } else {
1075: $cond[$#cond].=':normal';
1076: }
1077: }
1078:
1079: #
1080: # Parse mapalias parameters.
1081: # these are tags of the form:
1082: # <param to="nn"
1083: # value="some-alias-for-resourceid-nn"
1084: # name="parameter_0_mapalias"
1085: # type="string" />
1086: # A map alias is a textual name for a resource:
1087: # - The to attribute identifies the resource (this gets level qualified below)
1088: # - The value attributes provides the alias string.
1089: # - name must be of the regexp form: /^parameter_(0_)*mapalias$/
1090: # - e.g. the string 'parameter_' followed by 0 or more "0_" strings
1091: # terminating with the string 'mapalias'.
1092: # Examples:
1093: # 'parameter_mapalias', 'parameter_0_mapalias', parameter_0_0_mapalias'
1094: # Invalid to ids are silently ignored.
1095: #
1096: # Parameters:
1097: # token - The token array fromthe HMTML::TokeParser
1098: # lpc - The current map level counter.
1099: # hash - Reference to the hash that we are building.
1100: #
1101: sub parse_mapalias_param {
1102: my ($token, $lpc, $hash) = @_;
1103:
1104: # Fully qualify the to value and ignore the alias if there is no
1105: # corresponding resource.
1106:
1107: my $referid=$lpc.'.'.$token->[2]->{'to'};
1108: return if (!exists($hash->{'src_'.$referid}));
1109:
1110: # If this is a valid mapalias parameter,
1111: # Append the target id to the count_mapalias element for that
1112: # alias so that we can detect doubly defined aliases
1113: # e.g.:
1114: # <param to="1" value="george" name="parameter_0_mapalias" type="string" />
1115: # <param to="2" value="george" name="parameter_0_mapalias" type="string" />
1116: #
1117: # The example above is trivial but the case that's important has to do with
1118: # constructing a map that includes a nested map where the nested map may have
1119: # aliases that conflict with aliases established in the enclosing map.
1120: #
1121: # ...and create/update the hash mapalias entry to actually store the alias.
1122: #
1123:
1124: if ($token->[2]->{'name'}=~/^parameter_(0_)*mapalias$/) {
1125: &count_mapalias($token->[2]->{'value'},$referid);
1126: $hash->{'mapalias_'.$token->[2]->{'value'}}=$referid;
1127: }
1128: }
1129:
1130:
1131: #---------------------------------------------------------------------------------
1132: #
1133: # Code to process the map file.
1134:
1135: # read a map file and add it to the hash. Since a course map can contain resources
1136: # that are themselves maps, read_map might be recursively called.
1137: #
1138: # Parameters:
1139: # $uri - URI of the course itself (not the map file).
1140: # $parent_rid - map number qualified id of the parent of the map being read.
1141: # For the top level course map this is 0.0. For the first nested
1142: # map 1.n where n is the id of the resource within the
1143: # top level map and so on.
1144: # $hash - Reference to a hash that will become the big hash for the course
1145: # This hash is modified as per the map description.
1146: # Side-effects:
1147: # $map_number - Will be incremented. This keeps track of the number of the map
1148: # we are currently working on (see parent_rid above, the number to the
1149: # left of the . in $parent_rid is the map number).
1150: #
1151: #
1152: sub read_map {
1153: my ($uri, $parent_rid, $hash) = @_;
1154:
1155: # Check for duplication: A map may only be included once.
1156:
1157: if($hash->{'map_pc_' . $uri}) {
1.2 ! foxr 1158: throw Error::Simple('Duplicate map: ', $uri);
1.1 foxr 1159: }
1160: # count the map number and save it locally so that we don't lose it
1161: # when we recurse.
1162:
1163: $map_number++;
1164: my $lmap_no = $map_number;
1165:
1166: # save the map_pc and map_id elements of the hash for this map:
1167: # map_pc_uri is the map number of the map with that URI.
1168: # map_id_$lmap_no is the URI for this map level.
1169: #
1170: $hash->{'map_pc_' . $uri} = $lmap_no;
1171: $hash->{'map_id_' . $lmap_no} = $uri;
1172:
1173: # Create the path up to the top of the course.
1174: # this is in 'map_hierarchy_mapno' that's a comma separated path down to us
1175: # in the hierarchy:
1176:
1177: if ($parent_rid =~/^(\d+).\d+$/) {
1178: my $parent_no = $1; # Parent's map number.
1179: if (defined($hash->{'map_hierarchy_' . $parent_no})) {
1180: $hash->{'map_hierarchy_' . $lmap_no} =
1.2 ! foxr 1181: $hash->{'map_hierarchy_' . $parent_no} . ',' . $parent_no;
1.1 foxr 1182: } else {
1183: # Only 1 level deep ..nothing to append to:
1184:
1185: $hash->{'map_hierarchy_' . $lmap_no} = $parent_no;
1186: }
1187: }
1188:
1189: # figure out the name of the map file we need to read.
1190: # ensure that it is a .page or a .sequence as those are the only
1191: # sorts of files that make sense for this sub
1192:
1193: my $filename = &Apache::lonnet::filelocation('', &append_version($uri, $hash));
1194: my $ispage = ($filename =~/\.page$/);
1.2 ! foxr 1195: unless ($ispage || ($filename =~ /\.sequence$/)) {
1.1 foxr 1196: throw Error::Simple(&mt("<br />Invalid map: <tt>[_1]</tt>", $filename));
1197: }
1198:
1199: $filename =~ /\.(\w+)$/;
1200:
1.2 ! foxr 1201: $hash->{'map_type_'.$lmap_no}=$1;
1.1 foxr 1202:
1203: # Repcopy the file and get its contents...report errors if we can't
1204:
1205: my $contents = &Apache::lonet::getfile($filename);
1206: if($contents eq -1) {
1207: throw Error::Simple(&mt('<br />Map not loaded: The file <tt>[_1]</tt> does not exist.',
1208: $filename));
1209: }
1210: # Now that we succesfully retrieved the file we can make our parsing passes over it:
1211: # parsing is done in passes:
1212: # 1. Parameters are parsed.
1213: # 2. Resource, links and conditions are parsed.
1214: #
1215: # post processing takes care of the case where the sequence is random ordered
1216: # or randomselected.
1217:
1218: # Parse the parameters, This pass only cares about start tags for <param>
1219: # tags.. this is because there is no body to a <param> tag.
1220: #
1221:
1.2 ! foxr 1222: my $parser = HTML::TokeParser->new(\$contents);
1.1 foxr 1223: $parser->attr_encoded(1); # Don't interpret entities in attributes (leave &xyz; alone).
1224:
1225: while (my $token = $parser->get_token()) {
1226: if (($token->[0] eq 'S') && ($token->[1] eq 'param')) {
1227: &parse_param($token, $map_number, $hash);
1228: }
1229: }
1230:
1231: # ready for pass 2: Resource links and conditions.
1232: # Note that if the map is random-ordered link tags are computed by randomizing
1233: # resource order. Furthermore, since conditions are set on links rather than
1234: # resources, they are also not processed if random order is turned on.
1235: #
1236:
1.2 ! foxr 1237: $parser = HTML::TokeParser->new(\$contents); # no way to reset the existing parser
1.1 foxr 1238: $parser->attr_encoded(1);
1239:
1240: my $linkpc=0;
1241: my $randomize = ($randomorder{$parent_rid} =~ /^yes$/i);
1242:
1243: my @map_ids;
1244: while (my $token = $parser->get_token) {
1245: next if ($token->[0] ne 'S');
1246:
1247: # Resource
1248:
1249: if ($token->[1] eq 'resource') {
1.2 ! foxr 1250: my $resource_id = &parse_resource($token,$lmap_no,$ispage,$uri, $hash);
1.1 foxr 1251: if (defined $resource_id) {
1252: push(@map_ids, $resource_id);
1253: }
1254:
1255: # Link
1256:
1257: } elsif ($token->[1] eq 'link' && !$randomize) {
1.2 ! foxr 1258: &make_link(++$linkpc,$lmap_no,$token->[2]->{'to'},
1.1 foxr 1259: $token->[2]->{'from'},
1260: $token->[2]->{'condition'}, $hash); # note ..condition may be undefined.
1261:
1262: # condition
1263:
1264: } elsif ($token->[1] eq 'condition' && !$randomize) {
1.2 ! foxr 1265: &parse_condition($token,$lmap_no, $hash);
1.1 foxr 1266: }
1267: }
1268:
1269: # This section handles random ordering by permuting the
1270: # IDs of the map according to the user's random seed.
1271: #
1272:
1273: if ($randomize) {
1274: if (!$env{'request.role.adv'}) {
1275: my $seed;
1276:
1277: # In the advanced role, the map's random seed
1278: # parameter is used as the basis for computing the
1279: # seed ... if it has been specified:
1280:
1281: if (defined($randompickseed{$parent_rid})) {
1282: $seed = $randompickseed{$parent_rid};
1283: } else {
1284:
1285: # Otherwise the parent's fully encoded symb is used.
1286:
1287: my ($mapid,$resid)=split(/\./,$parent_rid);
1288: my $symb=
1289: &Apache::lonnet::encode_symb($hash->{'map_id_'.$mapid},
1290: $resid,$hash->{'src_'.$parent_rid});
1291:
1292: $seed = $symb;
1293: }
1294:
1295:
1296: my $rndseed=&Apache::lonnet::rndseed($seed, $username, $userdomain);
1297: &Apache::lonnet::setup_random_from_rndseed($rndseed);
1298:
1299: # Take the set of map ids we have decoded and permute them to a
1300: # random order based on the seed set above. All of this is
1301: # processing the randomorder parameter if it is set, not
1302: # randompick.
1303:
1304: @map_ids=&math::Random::random_permutation(@map_ids);
1305: }
1306:
1307:
1308: my $from = shift(@map_ids);
1.2 ! foxr 1309: my $from_rid = $lmap_no.'.'.$from;
1.1 foxr 1310: $hash->{'map_start_'.$uri} = $from_rid;
1311: $hash->{'type_'.$from_rid}='start';
1312:
1313: # Create links to reflect the random re-ordering done above.
1314: # In the code to process the map XML, we did not process links or conditions
1315: # if randomorder was set. This means that for an instructor to choose
1316:
1317: while (my $to = shift(@map_ids)) {
1.2 ! foxr 1318: &make_link(++$linkpc,$lmap_no,$to,$from);
! 1319: my $to_rid = $lmap_no.'.'.$to;
1.1 foxr 1320: $hash->{'type_'.$to_rid}='normal';
1321: $from = $to;
1322: $from_rid = $to_rid;
1323: }
1324:
1325: $hash->{'map_finish_'.$uri}= $from_rid;
1326: $hash->{'type_'.$from_rid}='finish';
1327: }
1328:
1329: # The last parsing pass parses the <mapalias> tags that associate a name
1330: # with resource ids.
1331:
1332: $parser = HTML::TokeParser->new(\$contents);
1333: $parser->attr_encoded(1);
1334:
1335: while (my $token = $parser->get_token) {
1336: next if ($token->[0] ne 'S');
1337: if ($token->[1] eq 'param') {
1.2 ! foxr 1338: &parse_mapalias_param($token,$lmap_no, $hash);
1.1 foxr 1339: }
1340: }
1341:
1342: }
1343:
1344:
1345: #
1346: # Load a map from file into a target hash. This is done by first parsing the
1347: # map file into local hashes and then unrolling those hashes into the big hash.
1348: #
1349: # Parameters:
1350: #
1351: # $cnum - number of course being read.
1352: # $cdom - Domain in which the course is evaluated.
1353: # $uname - Name of the user for whom the course is being read
1354: # $udom - Name of the domain of the user for whom the course is being read.
1355: # $target_hash- Reference to the target hash into which all of this is read.
1356: # Note tht some of the hash entries we need to build require knowledge of the
1357: # course URI.. these are expected to be filled in by the caller.
1358: #
1359: # Errors are logged to lonnet and are managed via the Perl structured exception package.
1360: #
1361: #
1362: sub loadmap {
1363: my ($cnum, $cdom, $uname, $udom, $filepath, $target_hash) = @_;
1364:
1365: # Clear the auxillary hashes and the cond array.
1366:
1367:
1368: %randompick = ();
1369: %randompickseed = ();
1370: %encurl = ();
1371: %hiddenurl = ();
1.2 ! foxr 1372: %parmhash = ();
1.1 foxr 1373: @cond = ();
1.2 ! foxr 1374: $retfrid = '';
1.1 foxr 1375:
1.2 ! foxr 1376:
1.1 foxr 1377: #
1378:
1379: $username = $uname;
1380: $userdomain = $udom;
1381:
1382: my $short_name = $cdom . $cnum;
1383:
1384: try {
1385:
1386:
1387: # Get the information we need about the course.
1388: # Return without filling in anything if we can't get any info:
1389:
1.2 ! foxr 1390: my %cenv = &Apache::lonnet::coursedescription($short_name,
1.1 foxr 1391: {'freshen_cache' => 1,
1392: 'user' => $uname});
1393: unless ($cenv{'url'}) {
1394: &Apache::lonnet::logthis("lonmap::loadmap failed: $cnum/$cdom - did not get url");
1395: return;
1396: }
1397: $course_id = $cdom . '.' . $cnum; # Long course id.
1398:
1399: # Load the version information into the hash
1400:
1401:
1402: &process_versions(\%cenv, $target_hash);
1403:
1404:
1405: # Figure out the map filename's URI, and set up some starting points for the map.
1406:
1.2 ! foxr 1407: my $course_uri = $cenv{'url'};
! 1408: my $map_uri = &Apache::lonnet::clutter($course_uri);
1.1 foxr 1409:
1410: $target_hash->{'src_0.0'} = &versiontrack($map_uri, $target_hash);
1411: $target_hash->{'title_0.0'} = &Apache::lonnet::metadata($course_uri, 'title');
1.2 ! foxr 1412: $target_hash->{'ids_'.$map_uri} = '0.0';
1.1 foxr 1413: $target_hash->{'is_map_0.0'} = 1;
1414: &read_map($course_uri, '0.0', &hash);
1415:
1416: #
1417:
1.2 ! foxr 1418: if (defined($target_hash->{'map_start_'.$map_uri})) {
1.1 foxr 1419:
1.2 ! foxr 1420: &traceroute('0',$target_hash->{'map_start_'.$course_uri},'&', $target_hash);
! 1421: &accinit($course_uri, $short_name, $filepath, $target_hash);
! 1422: &hiddenurls($target_hash);
! 1423: }
! 1424: my $errors = &get_mapalias_errors($target_hash);
! 1425: if ($errors ne "") {
! 1426: throw Error::Simple("Map alias errors: ", $errors);
! 1427: }
! 1428:
! 1429: # Put the versions in to src:
! 1430:
! 1431: foreach my $key (keys(%$target_hash)) {
! 1432: if ($key =~ /^src_/) {
! 1433: $target_hash->{$key} =
! 1434: &putinversion($target_hash->{$key}, $target_hash, $short_name);
! 1435: } elsif ($key =~ /^(map_(?:start|finish|pc)_)(.*)/) {
! 1436: my ($type, $url) = ($1,$2);
! 1437: my $value = $target_hash->{$key};
! 1438: $target_hash->{$type.&putinversion($url, $target_hash, $short_name)}=$value;
! 1439: }
1.1 foxr 1440: }
1441:
1442: # Merge in the child hashes in case the caller wants that information as well.
1443:
1444:
1.2 ! foxr 1445: &merge_hash($target_hash, 'randompick', \%randompick);
! 1446: &merge_hash($target_hash, 'randompickseed', \%randompick);
! 1447: &merge_hash($target_hash, 'randomorder', \%randomorder);
! 1448: &merge_hash($target_hash, 'encurl', \%encurl);
! 1449: &merge_hash($target_hash, 'hiddenurl', \%hiddenurl);
! 1450: &merge_hash($target_hash, 'param', \%parmhash);
! 1451: &merge_conditions($target_hash);
1.1 foxr 1452: }
1453: otherwise {
1454: my $e = shift;
1455: &Apache::lonnet::logthis("lonmap::loadmap failed: " . $e->stringify());
1456: }
1457:
1458: }
1459:
1460:
1461: 1;
1462:
1463: #
1464: # Module initialization code:
1465: #
1466:
1467: 1;
1468: __END__
1469:
1470: =head1 NAME
1471:
1472: Apache::lonmap - Construct a hash that represents a course (Big Hash).
1473:
1474: =head1 SYNOPSIS
1475:
1476: &Apache::lonmap::loadmap($filepath, \%target_hash);
1477:
1478: =head1 INTRODUCTION
1479:
1480: This module reads a course filename into a hash reference. It's up to the caller
1481: to to things like decide the has should be tied to some external file and handle the locking
1482: if this file should be shared amongst several Apache children.
1483:
1484: =head1 SUBROUTINES
1485:
1486: =over
1487:
1488: =item loadmap($filepath, $targethash)
1489:
1490:
1491: Reads the map file into a target hash.
1492:
1493: =over
1494:
1495: =item $filepath - The path to the map file to read.
1496:
1497: =item $targethash - A reference to hash into which the course is read.
1498:
1499: =back
1500:
1501: =item process_versions($cenv, $hash)
1502:
1503: Makes hash entries for each version of a course described by a course environment
1504: returned from Apache::lonnet::coursedescription.
1505:
1506: =over
1507:
1508: =item $cenv - Reference to the environment hash returned by Apache::lonnet::coursedescription
1509:
1510: =item $hash - Hash to be filled in with 'version_xxx' entries as per the big hash.
1511:
1512: =back
1513:
1514: =back
1515:
1516:
1517: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>