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