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