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