1: # The LearningOnline Network with CAPA
2: # Construct and maintain state and binary representation of course for user
3: #
4: # $Id: lonuserstate.pm,v 1.149.2.5.2.3 2022/10/05 22:54:00 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: package Apache::lonuserstate;
31:
32: # ------------------------------------------------- modules used by this module
33: use strict;
34: use HTML::TokeParser;
35: use Apache::lonnet;
36: use Apache::lonlocal;
37: use Apache::loncommon();
38: use GDBM_File;
39: use Apache::lonmsg;
40: use Safe;
41: use Safe::Hole;
42: use Opcode;
43: use Apache::lonenc;
44: use Fcntl qw(:flock);
45: use LONCAPA qw(:DEFAULT :match);
46: use File::Basename;
47:
48:
49:
50: # ---------------------------------------------------- Globals for this package
51:
52: my $pc; # Package counter is this what 'Guts' calls the map counter?
53: my %hash; # The big tied hash
54: my %parmhash;# The hash with the parameters
55: my @cond; # Array with all of the conditions
56: my $errtext; # variable with all errors
57: my $retfrid; # variable with the very first RID in the course
58: my $retfurl; # first URL
59: my %randompick; # randomly picked resources
60: my %randompickseed; # optional seed for randomly picking resources
61: my %randomorder; # maps to order contents randomly
62: my %randomizationcode; # code used to grade folder for bubblesheet exam
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
65: my %deeplinkout; # this URL (or complete folder) unavailable in deep-link session
66: my %rescount; # count of unhidden items in each map
67: my %mapcount; # count of unhidden maps in each map
68:
69: # ----------------------------------- Remove version from URL and store in hash
70:
71: sub versionerror {
72: my ($uri,$usedversion,$unusedversion)=@_;
73: return '<br />'.&mt('Version discrepancy: resource [_1] included in both version [_2] and version [_3]. Using version [_2].',
74: $uri,$usedversion,$unusedversion).'<br />';
75: }
76:
77: # Removes the version number from a URI and returns the resulting
78: # URI (e.g. mumbly.version.stuff => mumbly.stuff).
79: #
80: # If the URI has not been seen with a versio before the
81: # hash{'version_'.resultingURI} is set to the version number.
82: # If the URI has been seen and the version does not match and error
83: # is added to the error string.
84: #
85: # Parameters:
86: # URI potentially with a version.
87: # Returns:
88: # URI with the version cut out.
89: # See above for side effects.
90: #
91:
92: sub versiontrack {
93: my $uri=shift;
94: if ($uri=~/\.(\d+)\.\w+$/) {
95: my $version=$1;
96: $uri=~s/\.\d+\.(\w+)$/\.$1/;
97: unless ($hash{'version_'.$uri}) {
98: $hash{'version_'.$uri}=$version;
99: } elsif ($version!=$hash{'version_'.$uri}) {
100: $errtext.=&versionerror($uri,$hash{'version_'.$uri},$version);
101: }
102: }
103: return $uri;
104: }
105:
106: # -------------------------------------------------------------- Put in version
107:
108: sub putinversion {
109: my $uri=shift;
110: my $key=$env{'request.course.id'}.'_'.&Apache::lonnet::clutter($uri);
111: if ($hash{'version_'.$uri}) {
112: my $version=$hash{'version_'.$uri};
113: if ($version eq 'mostrecent') { return $uri; }
114: if ($version eq &Apache::lonnet::getversion(
115: &Apache::lonnet::filelocation('',$uri)))
116: { return $uri; }
117: $uri=~s/\.(\w+)$/\.$version\.$1/;
118: }
119: &Apache::lonnet::do_cache_new('courseresversion',$key,&Apache::lonnet::declutter($uri),600);
120: return $uri;
121: }
122:
123: # ----------------------------------------- Processing versions file for course
124:
125: sub processversionfile {
126: my %cenv=@_;
127: my %versions=&Apache::lonnet::dump('resourceversions',
128: $cenv{'domain'},
129: $cenv{'num'});
130: foreach my $ver (keys(%versions)) {
131: if ($ver=~/^error\:/) { return; }
132: $hash{'version_'.$ver}=$versions{$ver};
133: }
134: }
135:
136: # --------------------------------------------------------- Loads from disk
137:
138:
139: #
140: # Loads a map file.
141: # Note that this may implicitly recurse via parse_resource if one of the resources
142: # is itself composed.
143: #
144: # Parameters:
145: # uri - URI of the map file.
146: # parent_rid - Resource id in the map of the parent resource (0.0 for the top level map)
147: # courseid - Course id for the course for which the map is being loaded
148: #
149: sub loadmap {
150: my ($uri,$parent_rid,$courseid)=@_;
151:
152: # Is the map already included?
153:
154: if ($hash{'map_pc_'.$uri}) {
155: $errtext.='<p class="LC_error">'.
156: &mt('Multiple use of sequence/page [_1]! The course will not function properly.','<tt>'.$uri.'</tt>').
157: '</p>';
158: return;
159: }
160: # Register the resource in it's map_pc_ [for the URL]
161: # map_id.nnn is the nesting level -> to the URI.
162:
163: $pc++;
164: my $lpc=$pc;
165: $hash{'map_pc_'.$uri}=$lpc;
166: $hash{'map_id_'.$lpc}=$uri;
167:
168: # If the parent is of the form n.m hang this map underneath it in the
169: # map hierarchy.
170:
171: if ($parent_rid =~ /^(\d+)\.\d+$/) {
172: my $parent_pc = $1;
173: if (defined($hash{'map_hierarchy_'.$parent_pc})) {
174: $hash{'map_hierarchy_'.$lpc}=$hash{'map_hierarchy_'.$parent_pc}.','.
175: $parent_pc;
176: } else {
177: $hash{'map_hierarchy_'.$lpc}=$parent_pc;
178: }
179: }
180:
181: # Determine and check filename of the sequence we need to read:
182:
183: my $fn=&Apache::lonnet::filelocation('',&putinversion($uri));
184:
185: my $ispage=($fn=~/\.page$/);
186:
187: # We can only nest sequences or pages. Anything else is an illegal nest.
188:
189: unless (($fn=~/\.sequence$/) || $ispage) {
190: $errtext.='<br />'.&mt('Invalid map: [_1]',"<tt>$fn</tt>");
191: return;
192: }
193:
194: # Read the XML that constitutes the file.
195:
196: my $instr=&Apache::lonnet::getfile($fn);
197:
198: if ($instr eq -1) {
199: $errtext.= '<br />'
200: .&mt('Map not loaded: The file [_1] does not exist.',
201: "<tt>$fn</tt>");
202: $hash{'map_type_'.$lpc}='none';
203: if (&is_advanced($courseid)) {
204: $errtext .= &error_detail($parent_rid,$courseid,$ispage,$uri);
205: }
206: return;
207: }
208:
209: # Successfully got file, parse it
210:
211: # parse for parameter processing.
212: # Note that these are <param... / > tags
213: # so we only care about 'S' (tag start) nodes.
214:
215:
216: my $parser = HTML::TokeParser->new(\$instr);
217: $parser->attr_encoded(1);
218:
219: # first get all parameters
220:
221:
222: while (my $token = $parser->get_token) {
223: next if ($token->[0] ne 'S');
224: if ($token->[1] eq 'param') {
225: &parse_param($token,$lpc);
226: }
227: }
228:
229: # Get set to take another pass through the XML:
230: # for resources and links.
231:
232: $parser = HTML::TokeParser->new(\$instr);
233: $parser->attr_encoded(1);
234:
235: my $linkpc=0;
236:
237: $fn=~/\.(\w+)$/;
238:
239: $hash{'map_type_'.$lpc}=$1;
240:
241: my $randomize = ($randomorder{$parent_rid} =~ /^yes$/i);
242:
243: # Parse the resources, link and condition tags.
244: # Note that if randomorder or random select is chosen the links and
245: # conditions are meaningless but are determined by the randomization.
246: # This is handled in the next chunk of code.
247:
248: my @map_ids;
249: my $codechecked;
250: $rescount{$lpc} = 0;
251: $mapcount{$lpc} = 0;
252: while (my $token = $parser->get_token) {
253: next if ($token->[0] ne 'S');
254:
255: # Resource
256:
257: if ($token->[1] eq 'resource') {
258: my $resource_id = &parse_resource($token,$lpc,$ispage,$uri,$courseid);
259: if (defined $resource_id) {
260: push(@map_ids, $resource_id);
261: if ($hash{'src_'.$lpc.'.'.$resource_id}) {
262: $rescount{$lpc} ++;
263: if (($hash{'src_'.$lpc.'.'.$resource_id}=~/\.sequence$/) ||
264: ($hash{'src_'.$lpc.'.'.$resource_id}=~/\.page$/)) {
265: $mapcount{$lpc} ++;
266: }
267: }
268: unless ($codechecked) {
269: my $startsymb =
270: &Apache::lonnet::encode_symb($hash{'map_id_'.$lpc},$resource_id,
271: $hash{'src_'."$lpc.$resource_id"});
272: my $code =
273: &Apache::lonnet::EXT('resource.0.examcode',$startsymb,undef,undef,
274: undef,undef,$courseid);
275: if ($code) {
276: $randomizationcode{$parent_rid} = $code;
277: }
278: $codechecked = 1;
279: }
280: }
281:
282: # Link
283:
284: } elsif ($token->[1] eq 'link' && !$randomize) {
285: &make_link(++$linkpc,$lpc,$token->[2]->{'to'},
286: $token->[2]->{'from'},
287: $token->[2]->{'condition'}); # note ..condition may be undefined.
288:
289: # condition
290:
291: } elsif ($token->[1] eq 'condition' && !$randomize) {
292: &parse_condition($token,$lpc);
293: }
294: }
295: undef($codechecked);
296:
297: # Handle randomization and random selection
298:
299: if ($randomize) {
300: unless (&is_advanced($courseid)) {
301: # Order of resources is not randomized if user has and advanced role in the course.
302: my $seed;
303:
304: # If the map's random seed parameter has been specified
305: # it is used as the basis for computing the seed ...
306:
307: if (defined($randompickseed{$parent_rid})) {
308: $seed = $randompickseed{$parent_rid};
309: } else {
310:
311: # Otherwise the parent's fully encoded symb is used.
312:
313: my ($mapid,$resid)=split(/\./,$parent_rid);
314: my $symb=
315: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
316: $resid,$hash{'src_'.$parent_rid});
317:
318: $seed = $symb;
319: }
320:
321: # TODO: Here for sure we need to pass along the username/domain
322: # so that we can impersonate users in lonprintout e.g.
323:
324: my $setcode;
325: if (defined($randomizationcode{$parent_rid})) {
326: if ($env{'form.CODE'} eq '') {
327: $env{'form.CODE'} = $randomizationcode{$parent_rid};
328: $setcode = 1;
329: }
330: }
331:
332: my $rndseed=&Apache::lonnet::rndseed($seed);
333: &Apache::lonnet::setup_random_from_rndseed($rndseed);
334:
335: if ($setcode) {
336: undef($env{'form.CODE'});
337: undef($setcode);
338: }
339:
340: # Take the set of map ids we have decoded and permute them to a
341: # random order based on the seed set above. All of this is
342: # processing the randomorder parameter if it is set, not
343: # randompick.
344:
345: @map_ids=&Math::Random::random_permutation(@map_ids);
346: }
347:
348: my $from = shift(@map_ids);
349: my $from_rid = $lpc.'.'.$from;
350: $hash{'map_start_'.$uri} = $from_rid;
351: $hash{'type_'.$from_rid}='start';
352:
353: # Create links to reflect the random re-ordering done above.
354: # In the code to process the map XML, we did not process links or conditions
355: # if randomorder was set. This means that for an instructor to choose
356:
357: while (my $to = shift(@map_ids)) {
358: &make_link(++$linkpc,$lpc,$to,$from);
359: my $to_rid = $lpc.'.'.$to;
360: $hash{'type_'.$to_rid}='normal';
361: $from = $to;
362: $from_rid = $to_rid;
363: }
364:
365: $hash{'map_finish_'.$uri}= $from_rid;
366: $hash{'type_'.$from_rid}='finish';
367: }
368:
369: $parser = HTML::TokeParser->new(\$instr);
370: $parser->attr_encoded(1);
371:
372: # last parse out the mapalias params. These provide mnemonic
373: # tags to resources that can be used in conditions
374:
375: while (my $token = $parser->get_token) {
376: next if ($token->[0] ne 'S');
377: if ($token->[1] eq 'param') {
378: &parse_mapalias_param($token,$lpc);
379: }
380: }
381: }
382:
383: sub is_advanced {
384: my ($courseid) = @_;
385: my $advanced;
386: if ($env{'request.course.id'}) {
387: $advanced = (&Apache::lonnet::allowed('adv') eq 'F');
388: } else {
389: $env{'request.course.id'} = $courseid;
390: $advanced = (&Apache::lonnet::allowed('adv') eq 'F');
391: $env{'request.course.id'} = '';
392: }
393: return $advanced;
394: }
395:
396: sub error_detail {
397: my ($parent_rid,$courseid,$ispage,$uri) = @_;
398: my $errinfo;
399: if ($courseid) {
400: my $courseurl = &Apache::lonnet::courseid_to_courseurl($courseid);
401: if ($parent_rid =~ /^(\d+)\.(\d+)$/) {
402: my ($parent_pc,$parent_id) = ($1,$2);
403: my ($parent_type,$published,$uploaded,$canedit,$role,$switchserver,$audom,$auname,
404: $editfile,$filerole,$fileswitch,$audomfile,$aunamefile);
405: if (($parent_pc eq '0') && ($hash{'map_id_1'} =~ m{^/res/($match_domain)/($match_username)/.+\.(sequence|page)$})) {
406: ($audomfile,$aunamefile) = ($1,$2);
407: ($editfile,$filerole,$fileswitch) = &canedit_published($audomfile,$aunamefile);
408: $errinfo = &mt('Top level published sequence file is missing.');
409: } else {
410: if ($parent_pc eq '1') {
411: if ($hash{'map_id_1'} eq "/uploaded$courseurl/default.sequence") {
412: $uploaded = 1;
413: if (&Apache::lonnet::allowed('mdc',$courseid)) {
414: $canedit = 1;
415: }
416: $errinfo = &mt('Map is referenced in the top level ([_1]Main Content[_2]) folder.',
417: '<span class="LC_cusr_emph">','</span>');
418: } elsif ($hash{'map_id_1'} =~ m{^/res/($match_domain)/($match_username)/.+\.(sequence|page)$}) {
419: ($audom,$auname) = ($1,$2);
420: ($canedit,$role,$switchserver) = &canedit_published($audom,$auname);
421: $published = 1;
422: $errinfo = &mt('Map is referenced in the top level published sequence file.');
423: }
424: } else {
425: if ($hash{'map_id_'.$parent_pc} =~ m{^\Q/uploaded$courseurl/default_\E\d+\.(sequence|page)$}) {
426: $uploaded = 1;
427: if (&Apache::lonnet::allowed('mdc',$courseid)) {
428: $canedit = 1;
429: }
430: } elsif ($hash{'map_id_'.$parent_pc} =~ m{^/res/($match_domain)/($match_username)/.+\.(sequence|page)$}) {
431: ($audom,$auname) = ($1,$2);
432: ($canedit,$role,$switchserver) = &canedit_published($audom,$auname);
433: $published = 1;
434: }
435: if (exists($hash{'ids_'.$hash{'map_id_'.$parent_pc}})) {
436: $parent_type = $hash{'map_type_'.$parent_pc};
437: if ($published) {
438: $errinfo = &mt("Map is referenced in the published $parent_type file: [_1].",
439: '<span class="LC_cusr_emph">'.$hash{'map_id_'.$parent_pc}.'</span>');
440: } else {
441: my $title = $hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$parent_pc}}};
442: if ($title ne '') {
443: my $mapdesc;
444: if ($parent_type eq 'sequence') {
445: $mapdesc = 'folder';
446: } else {
447: $mapdesc = 'composite page';
448: }
449: $errinfo = &mt("Map is referenced in the $mapdesc named: [_1].",
450: '<span class="LC_cusr_emph">'.$title.'</span>');
451: }
452: my @containers = split(/,/,$hash{'map_hierarchy_'.$parent_pc});
453: shift(@containers);
454: my $folderpath;
455: foreach my $id (@containers) {
456: my $name;
457: if ($id == 1) {
458: $name = &mt('Main Content');
459: } elsif ($hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$id}}} ne '') {
460: $name = $hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$id}}};
461: }
462: if ($name ne '') {
463: $folderpath .= $name.' » ';
464: }
465: }
466: if ($title eq '') {
467: $folderpath =~ s/\Q » \E$//;
468: } else {
469: $folderpath .= $title;
470: }
471: if ($folderpath) {
472: $errinfo .= '<br />'.&mt('Hierarchy is: [_1]',
473: '<span class="LC_cusr_emph">'.$folderpath.'</span>');
474: }
475: }
476: }
477: }
478: if ($uri =~ m{^/res/($match_domain)/($match_username)/.+\.(sequence|page)$}) {
479: ($audomfile,$aunamefile) = ($1,$2);
480: ($editfile,$filerole,$fileswitch) = &canedit_published($audomfile,$aunamefile);
481: }
482: }
483: if ($errinfo) {
484: $errinfo = '<br />'.$errinfo.'<br />';
485: }
486: if ($editfile) {
487: if ($errinfo ne '') {
488: $errinfo .= '<br />';
489: }
490: if ($canedit) {
491: $errinfo .= &mt('One way to rectify this problem is to create and publish the missing file');
492: } else {
493: $errinfo .= &mt('To rectify this problem, create and publish the missing file');
494: }
495: my $fileurl = $uri;
496: $fileurl =~s{^/res/}{/priv/};
497: if ($fileswitch) {
498: my $rolename = &Apache::lonnet::plaintext($filerole);
499: my $rolecode;
500: if ($filerole eq 'au') {
501: $rolecode = 'au./'.$audomfile.'/';
502: } else {
503: $rolecode = $filerole.'./'.$audomfile.'/'.$aunamefile;
504: }
505: $errinfo .= '.<br />'.&mt('You will need to [_1]switch server[_2].',
506: '<a href="/adm/switchserver?otherserver='.$switchserver.'&role='.$rolecode.
507: '&origurl='.&escape($fileurl).'">','</a>');
508: } else {
509: &js_escape(\$fileurl);
510: $errinfo .= ': <a href="javascript:go('."'$fileurl'".');">'.&mt('Create the missing file').'</a>';
511: }
512: }
513: if ($canedit) {
514: if ($errinfo ne '') {
515: $errinfo .= '<br />';
516: }
517: if ($published) {
518: my $rolename = &Apache::lonnet::plaintext($role);
519: my $rolecode;
520: if ($role eq 'au') {
521: $rolecode = 'au./'.$audom.'/';
522: } else {
523: $rolecode = $role.'./'.$audom.'/'.$auname;
524: }
525: if ($editfile) {
526: $errinfo .= &mt('Another way is to edit the parent map to remove the reference to the missing file');
527: } else {
528: $errinfo .= &mt('To rectify this problem edit the parent map to remove the reference to the missing file');
529: }
530: my $mapurl = $hash{'map_id_'.$parent_pc};
531: $mapurl =~s{^/res/}{/priv/};
532: if ($switchserver) {
533: $errinfo .= '.<br />'.
534: &mt('You will need to [_1]switch server[_2].',
535: '<a href="/adm/switchserver?otherserver='.$switchserver.'&role='.$rolecode.
536: '&origurl='.&escape($mapurl).'">','</a>');
537: } else {
538: &js_escape(\$mapurl);
539: $errinfo .= ': <a href="javascript:go('."'$mapurl'".');">'.&mt('Edit the map').'</a>';
540: }
541: } elsif ($uploaded && $courseid) {
542: my ($dest,$linktext);
543: my $crstype = &Apache::loncommon::course_type($courseid);
544: if ($parent_pc eq '1') {
545: $dest = '/adm/coursedocs?folderpath='.&escape('default&Main%20Content:::::');
546: $linktext = &mt('Edit Folder');
547: } elsif ($hash{'ids_'.$hash{'map_id_'.$parent_pc}} =~ /^(\d+)\.(\d+)$/) {
548: my ($editmap,$editidx) = ($1,$2);
549: my $symb = &Apache::lonnet::encode_symb($hash{'map_id_'.$editmap},
550: $editidx,$hash{'map_id_'.$parent_pc});
551: $dest = '/adm/coursedocs?command=directnav&symb='.&escape($symb);
552: if ($parent_type eq 'sequence') {
553: $linktext = &mt('Edit Folder');
554: } else {
555: $linktext = &mt('Edit Composite Page');
556: }
557: } else {
558: $dest = '/adm/coursedocs?folderpath='.&escape('default&Main%20Content:::::');
559: $linktext = &mt("Edit $crstype");
560: }
561: if ($editfile) {
562: $errinfo .= &mt("Another way is to use the $crstype Editor to delete the reference to the missing file");
563: } else {
564: $errinfo .= &mt("To rectify this problem use the $crstype Editor to delete the reference to the missing file");
565: }
566: $errinfo .= ': <a href="javascript:go('."'$dest'".');">'.$linktext.'</a>';
567: }
568: $errinfo .= '<br />';
569: }
570: }
571: }
572: return $errinfo;
573: }
574:
575: sub canedit_published {
576: my ($audom,$auname) = @_;
577: my ($canedit,$role,$switchserver);
578: my $now = time;
579: if (($auname eq $env{'user.name'}) && ($audom eq $env{'user.domain'})) {
580: if (exists($env{"user.role.au./$audom/"})) {
581: my ($start,$end) = split(/\./,$env{"user.role.au./$audom/"});
582: unless (($end && $end < $now) || ($start && $start > $now)) {
583: $canedit = 1;
584: $role = 'au';
585: }
586: }
587: }
588: unless ($canedit) {
589: foreach my $possrole ('ca','aa') {
590: if (exists($env{"user.role.$possrole./$audom/$auname"})) {
591: my ($end,$start) = split(/\./,$env{"user.role.$possrole./$audom/$auname"});
592: unless (($end && $end < time) || ($start && $start > time)) {
593: $canedit = 1;
594: $role = $possrole;
595: last;
596: }
597: }
598: }
599: }
600: if ($canedit) {
601: my $auhome = &Apache::lonnet::homeserver($auname,$audom);
602: my @ids=&Apache::lonnet::current_machine_ids();
603: if (($auhome ne 'no_host') && (!grep(/^\Q$auhome\E$/,@ids))) {
604: $switchserver = $auhome;
605: }
606: }
607: return ($canedit,$role,$switchserver);
608: }
609:
610: # -------------------------------------------------------------------- Resource
611: #
612: # Parses a resource tag to produce the value to push into the
613: # map_ids array.
614: #
615: #
616: # Information about the actual type of resource is provided by the file extension
617: # of the uri (e.g. .problem, .sequence etc. etc.).
618: #
619: # Parameters:
620: # $token - A token from HTML::TokeParser
621: # This is an array that describes the most recently parsed HTML item.
622: # $lpc - Map nesting level (?)
623: # $ispage - True if this resource is encapsulated in a .page (assembled resourcde).
624: # $uri - URI of the enclosing resource.
625: # $courseid - Course id of the course containing the resource being parsed.
626: # Returns:
627: # Value of the id attribute of the tag.
628: #
629: # Note:
630: # The token is an array that contains the following elements:
631: # [0] => 'S' indicating this is a start token
632: # [1] => 'resource' indicating this tag is a <resource> tag.
633: # [2] => Hash of attribute =>value pairs.
634: # [3] => @(keys [2]).
635: # [4] => unused.
636: #
637: # The attributes of the resourcde tag include:
638: #
639: # id - The resource id.
640: # src - The URI of the resource.
641: # type - The resource type (e.g. start and finish).
642: # title - The resource title.
643:
644:
645: sub parse_resource {
646: my ($token,$lpc,$ispage,$uri,$courseid) = @_;
647:
648: # I refuse to countenance code like this that has
649: # such a dirty side effect (and forcing this sub to be called within a loop).
650: #
651: # if ($token->[2]->{'type'} eq 'zombie') { next; }
652: #
653: # The original code both returns _and_ skips to the next pass of the >caller's<
654: # loop, that's just dirty.
655: #
656:
657: # Zombie resources don't produce anything useful.
658:
659: if ($token->[2]->{'type'} eq 'zombie') {
660: return undef;
661: }
662:
663: my $rid=$lpc.'.'.$token->[2]->{'id'}; # Resource id in hash is levelcounter.id-in-xml.
664:
665: # Save the hash element type and title:
666:
667: $hash{'kind_'.$rid}='res';
668: $hash{'title_'.$rid}=$token->[2]->{'title'};
669:
670: # Get the version free URI for the resource.
671: # If a 'version' attribute was supplied, and this resource's version
672: # information has not yet been stored, store it.
673: #
674:
675: my $turi=&versiontrack($token->[2]->{'src'});
676: if ($token->[2]->{'version'}) {
677: unless ($hash{'version_'.$turi}) {
678: $hash{'version_'.$turi}=$1;
679: }
680: }
681: # Pull out the title and do entity substitution on &colon
682: # Q: Why no other entity substitutions?
683:
684: my $title=$token->[2]->{'title'};
685: $title=~s/\&colon\;/\:/gs;
686:
687:
688:
689: # I think the point of all this code is to construct a final
690: # URI that apache and its rewrite rules can use to
691: # fetch the resource. Thi s sonly necessary if the resource
692: # is not a page. If the resource is a page then it must be
693: # assembled (at fetch time?).
694:
695: if ($ispage) {
696: if ($token->[2]->{'external'} eq 'true') { # external
697: $turi=~s{^http\://}{/ext/};
698: }
699: } else {
700: $turi=~/\.(\w+)$/;
701: my $embstyle=&Apache::loncommon::fileembstyle($1);
702: if ($token->[2]->{'external'} eq 'true') { # external
703: $turi=~s/^https?\:\/\//\/adm\/wrapper\/ext\//;
704: } elsif ($turi=~/^\/*uploaded\//) { # uploaded
705: if (($embstyle eq 'img')
706: || ($embstyle eq 'emb')
707: || ($embstyle eq 'wrp')) {
708: $turi='/adm/wrapper'.$turi;
709: } elsif ($embstyle eq 'ssi') {
710: #do nothing with these
711: } elsif ($turi!~/\.(sequence|page)$/) {
712: $turi='/adm/coursedocs/showdoc'.$turi;
713: }
714: } elsif ($turi=~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
715: $turi='/adm/wrapper'.$turi;
716: } elsif ($turi=~/\S/) { # normal non-empty internal resource
717: my $mapdir=$uri;
718: $mapdir=~s/[^\/]+$//;
719: $turi=&Apache::lonnet::hreflocation($mapdir,$turi);
720: if (($embstyle eq 'img')
721: || ($embstyle eq 'emb')
722: || ($embstyle eq 'wrp')) {
723: $turi='/adm/wrapper'.$turi;
724: }
725: }
726: }
727: # Store reverse lookup, remove query string resource 'ids'_uri => resource id.
728: # If the URI appears more than one time in the sequence, it's resourcde
729: # id's are constructed as a comma spearated list.
730:
731: my $idsuri=$turi;
732: $idsuri=~s/\?.+$//;
733: if (defined($hash{'ids_'.$idsuri})) {
734: $hash{'ids_'.$idsuri}.=','.$rid;
735: } else {
736: $hash{'ids_'.$idsuri}=''.$rid;
737: }
738:
739:
740:
741: if ($turi=~/\/(syllabus|aboutme|navmaps|smppg|bulletinboard|viewclasslist)$/) {
742: $turi.='?register=1';
743: }
744:
745:
746: # resource id lookup: 'src'_resourc-di => URI decorated with a query
747: # parameter as above if necessary due to the resource type.
748:
749: $hash{'src_'.$rid}=$turi;
750:
751: # Mark the external-ness of the resource:
752:
753: if ($token->[2]->{'external'} eq 'true') {
754: $hash{'ext_'.$rid}='true:';
755: } else {
756: $hash{'ext_'.$rid}='false:';
757: }
758:
759: # If the resource is a start/finish resource set those
760: # entries in the has so that navigation knows where everything starts.
761: # TODO? If there is a malformed sequence that has no start or no finish
762: # resource, should this be detected and errors thrown? How would such a
763: # resource come into being other than being manually constructed by a person
764: # and then uploaded? Could that happen if an author decided a sequence was almost
765: # right edited it by hand and then reuploaded it to 'fix it' but accidently cut the
766: # start or finish resources?
767: #
768: # All resourcess also get a type_id => (start | finish | normal) hash entr.
769: #
770: if ($token->[2]->{'type'}) {
771: $hash{'type_'.$rid}=$token->[2]->{'type'};
772: if ($token->[2]->{'type'} eq 'start') {
773: $hash{'map_start_'.$uri}="$rid";
774: }
775: if ($token->[2]->{'type'} eq 'finish') {
776: $hash{'map_finish_'.$uri}="$rid";
777: }
778: } else {
779: $hash{'type_'.$rid}='normal';
780: }
781:
782: # Sequences end pages are constructed entities. They require that the
783: # map that defines _them_ be loaded as well into the hash...with this resourcde
784: # as the base of the nesting.
785: # Resources like that are also marked with is_map_id => 1 entries.
786: #
787:
788: if (($turi=~/\.sequence$/) ||
789: ($turi=~/\.page$/)) {
790: $hash{'is_map_'.$rid}=1;
791: if ((!$hiddenurl{$rid}) || (&is_advanced($courseid))) {
792: &loadmap($turi,$rid,$courseid);
793: }
794: }
795: return $token->[2]->{'id'};
796: }
797:
798: #-------------------------------------------------------------------- link
799: # Links define how you are allowed to move from one resource to another.
800: # They are the transition edges in the directed graph that a map is.
801: # This sub takes informatino from a <link> tag and constructs the
802: # navigation bits and pieces of a map. There is no requirement that the
803: # resources that are linke are already defined, however clearly the map is
804: # badly broken if they are not _eventually_ defined.
805: #
806: # Note that links can be unconditional or conditional.
807: #
808: # Parameters:
809: # linkpc - The link counter for this level of map nesting (this is
810: # reset to zero by loadmap prior to starting to process
811: # links for map).
812: # lpc - The map level ocounter (how deeply nested this map is in
813: # the hierarchy of maps that are recursively read in.
814: # to - resource id (within the XML) of the target of the edge.
815: # from - resource id (within the XML) of the source of the edge.
816: # condition- id of condition associated with the edge (also within the XML).
817: #
818:
819: sub make_link {
820: my ($linkpc,$lpc,$to,$from,$condition) = @_;
821:
822: # Compute fully qualified ids for the link, the
823: # and from/to by prepending lpc.
824: #
825:
826: my $linkid=$lpc.'.'.$linkpc;
827: my $goesto=$lpc.'.'.$to;
828: my $comesfrom=$lpc.'.'.$from;
829: my $undercond=0;
830:
831:
832: # If there is a condition, qualify it with the level counter.
833:
834: if ($condition) {
835: $undercond=$lpc.'.'.$condition;
836: }
837:
838: # Links are represnted by:
839: # goesto_.fuullyqualifedlinkid => fully qualified to
840: # comesfrom.fullyqualifiedlinkid => fully qualified from
841: # undercond_.fullyqualifiedlinkid => fully qualified condition id.
842:
843: $hash{'goesto_'.$linkid}=$goesto;
844: $hash{'comesfrom_'.$linkid}=$comesfrom;
845: $hash{'undercond_'.$linkid}=$undercond;
846:
847: # In addition:
848: # to_.fully qualified from => comma separated list of
849: # link ids with that from.
850: # Similarly:
851: # from_.fully qualified to => comma separated list of link ids`
852: # with that to.
853: # That allows us given a resource id to know all edges that go to it
854: # and leave from it.
855: #
856:
857: if (defined($hash{'to_'.$comesfrom})) {
858: $hash{'to_'.$comesfrom}.=','.$linkid;
859: } else {
860: $hash{'to_'.$comesfrom}=''.$linkid;
861: }
862: if (defined($hash{'from_'.$goesto})) {
863: $hash{'from_'.$goesto}.=','.$linkid;
864: } else {
865: $hash{'from_'.$goesto}=''.$linkid;
866: }
867: }
868:
869: # ------------------------------------------------------------------- Condition
870: #
871: # Processes <condition> tags, storing sufficient information about them
872: # in the hash so that they can be evaluated and used to conditionalize
873: # what is presented to the student.
874: #
875: # these can have the following attributes
876: #
877: # id = A unique identifier of the condition within the map.
878: #
879: # value = Is a perl script-let that, when evaluated in safe space
880: # determines whether or not the condition is true.
881: # Normally this takes the form of a test on an Apache::lonnet::EXT call
882: # to find the value of variable associated with a resource in the
883: # map identified by a mapalias.
884: # Here's a fragment of XML code that illustrates this:
885: #
886: # <param to="5" value="mainproblem" name="parameter_0_mapalias" type="string" />
887: # <resource src="" id="1" type="start" title="Start" />
888: # <resource src="/res/msu/albertel/b_and_c/p1.problem" id="5" title="p1.problem" />
889: # <condition value="&EXT('user.resource.resource.0.tries','mainproblem')
890: # <2 " id="61" type="stop" />
891: # <link to="5" index="1" from="1" condition="61" />
892: #
893: # In this fragment:
894: # - The param tag establishes an alias to resource id 5 of 'mainproblem'.
895: # - The resource that is the start of the map is identified.
896: # - The resource tag identifies the resource associated with this tag
897: # and gives it the id 5.
898: # - The condition is true if the tries variable associated with mainproblem
899: # is less than 2 (that is the user has had more than 2 tries).
900: # The condition type is a stop condition which inhibits(?) the associated
901: # link if the condition is false.
902: # - The link to resource 5 from resource 1 is affected by this condition.
903: #
904: # type = Type of the condition. The type determines how the condition affects the
905: # link associated with it and is one of
906: # - 'force'
907: # - 'stop'
908: # anything else including not supplied..which treated as:
909: # - 'normal'.
910: # Presumably maps get created by the resource assembly tool and therefore
911: # illegal type values won't squirm their way into the XML.
912: #
913: # Side effects:
914: # - The kind_level-qualified-condition-id hash element is set to 'cond'.
915: # - The condition text is pushed into the cond array and its element number is
916: # set in the condid_level-qualified-condition-id element of the hash.
917: # - The condition type is colon appneded to the cond array element for this condition.
918: sub parse_condition {
919: my ($token,$lpc) = @_;
920: my $rid=$lpc.'.'.$token->[2]->{'id'};
921:
922: $hash{'kind_'.$rid}='cond';
923:
924: my $condition = $token->[2]->{'value'};
925: $condition =~ s/[\n\r]+/ /gs;
926: push(@cond, $condition);
927: $hash{'condid_'.$rid}=$#cond;
928: if ($token->[2]->{'type'}) {
929: $cond[$#cond].=':'.$token->[2]->{'type'};
930: } else {
931: $cond[$#cond].=':normal';
932: }
933: }
934:
935: # ------------------------------------------------------------------- Parameter
936: # Parse a <parameter> tag in the map.
937: # Parmameters:
938: # $token Token array for a start tag from HTML::TokeParser
939: # [0] = 'S'
940: # [1] = tagname ("param")
941: # [2] = Hash of {attribute} = values.
942: # [3] = Array of the keys in [2].
943: # [4] = unused.
944: # $lpc Current map nesting level.a
945: #
946: # Typical attributes:
947: # to=n - Number of the resource the parameter applies to.
948: # type=xx - Type of parameter value (e.g. string_yesno or int_pos).
949: # name=xxx - Name of parameter (e.g. parameter_randompick or parameter_randomorder).
950: # value=xxx - value of the parameter.
951:
952: sub parse_param {
953: my ($token,$lpc) = @_;
954: my $referid=$lpc.'.'.$token->[2]->{'to'}; # Resource param applies to.
955: my $name=$token->[2]->{'name'}; # Name of parameter
956: my $part;
957:
958:
959: if ($name=~/^parameter_(.*)_/) {
960: $part=$1;
961: } else {
962: $part=0;
963: }
964:
965: # Peel the parameter_ off the parameter name.
966:
967: $name=~s/^.*_([^_]*)$/$1/;
968:
969: # The value is:
970: # type.part.name.value
971:
972: my $newparam=
973: &escape($token->[2]->{'type'}).':'.
974: &escape($part.'.'.$name).'='.
975: &escape($token->[2]->{'value'});
976:
977: # The hash key is param_resourceid.
978: # Multiple parameters for a single resource are & separated in the hash.
979:
980:
981: if (defined($hash{'param_'.$referid})) {
982: $hash{'param_'.$referid}.='&'.$newparam;
983: } else {
984: $hash{'param_'.$referid}=''.$newparam;
985: }
986: #
987: # These parameters have to do with randomly selecting
988: # resources, therefore a separate hash is also created to
989: # make it easy to locate them when actually computing the resource set later on
990: # See the code conditionalized by ($randomize) in loadmap().
991:
992: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompick$/) { # Random selection turned on
993: $randompick{$referid}=$token->[2]->{'value'};
994: }
995: if ($token->[2]->{'name'}=~/^parameter_(0_)*randompickseed$/) { # Randomseed provided.
996: $randompickseed{$referid}=$token->[2]->{'value'};
997: }
998: if ($token->[2]->{'name'}=~/^parameter_(0_)*randomorder$/) { # Random order turned on.
999: $randomorder{$referid}=$token->[2]->{'value'};
1000: }
1001:
1002: # These parameters have to do with how the URLs of resources are presented to
1003: # course members(?). encrypturl presents encypted url's while
1004: # hiddenresource hides the URL.
1005: #
1006:
1007: if ($token->[2]->{'name'}=~/^parameter_(0_)*encrypturl$/) {
1008: if ($token->[2]->{'value'}=~/^yes$/i) {
1009: $encurl{$referid}=1;
1010: }
1011: }
1012: if ($token->[2]->{'name'}=~/^parameter_(0_)*hiddenresource$/) {
1013: if ($token->[2]->{'value'}=~/^yes$/i) {
1014: $hiddenurl{$referid}=1;
1015: }
1016: }
1017: }
1018: #
1019: # Parse mapalias parameters.
1020: # these are tags of the form:
1021: # <param to="nn"
1022: # value="some-alias-for-resourceid-nn"
1023: # name="parameter_0_mapalias"
1024: # type="string" />
1025: # A map alias is a textual name for a resource:
1026: # - The to attribute identifies the resource (this gets level qualified below)
1027: # - The value attributes provides the alias string.
1028: # - name must be of the regexp form: /^parameter_(0_)*mapalias$/
1029: # - e.g. the string 'parameter_' followed by 0 or more "0_" strings
1030: # terminating with the string 'mapalias'.
1031: # Examples:
1032: # 'parameter_mapalias', 'parameter_0_mapalias', parameter_0_0_mapalias'
1033: # Invalid to ids are silently ignored.
1034: #
1035: # Parameters:
1036: # token - The token array fromthe HMTML::TokeParser
1037: # lpc - The current map level counter.
1038: #
1039: sub parse_mapalias_param {
1040: my ($token,$lpc) = @_;
1041:
1042: # Fully qualify the to value and ignore the alias if there is no
1043: # corresponding resource.
1044:
1045: my $referid=$lpc.'.'.$token->[2]->{'to'};
1046: return if (!exists($hash{'src_'.$referid}));
1047:
1048: # If this is a valid mapalias parameter,
1049: # Append the target id to the count_mapalias element for that
1050: # alias so that we can detect doubly defined aliases
1051: # e.g.:
1052: # <param to="1" value="george" name="parameter_0_mapalias" type="string" />
1053: # <param to="2" value="george" name="parameter_0_mapalias" type="string" />
1054: #
1055: # The example above is trivial but the case that's important has to do with
1056: # constructing a map that includes a nested map where the nested map may have
1057: # aliases that conflict with aliases established in the enclosing map.
1058: #
1059: # ...and create/update the hash mapalias entry to actually store the alias.
1060: #
1061:
1062: if ($token->[2]->{'name'}=~/^parameter_(0_)*mapalias$/) {
1063: &count_mapalias($token->[2]->{'value'},$referid);
1064: $hash{'mapalias_'.$token->[2]->{'value'}}=$referid;
1065: }
1066: }
1067:
1068: # --------------------------------------------------------- Simplify expression
1069:
1070:
1071: #
1072: # Someone should really comment this to describe what it does to what and why.
1073: #
1074: sub simplify {
1075: my $expression=shift;
1076: # (0&1) = 1
1077: $expression=~s/\(0\&([_\.\d]+)\)/$1/g;
1078: # (8)=8
1079: $expression=~s/\(([_\.\d]+)\)/$1/g;
1080: # 8&8=8
1081: $expression=~s/([^_\.\d])([_\.\d]+)\&\2([^_\.\d])/$1$2$3/g;
1082: # 8|8=8
1083: $expression=~s/([^_\.\d])([_\.\d]+)(?:\|\2)+([^_\.\d])/$1$2$3/g;
1084: # (5&3)&4=5&3&4
1085: $expression=~s/\(([_\.\d]+)((?:\&[_\.\d]+)+)\)\&([_\.\d]+[^_\.\d])/$1$2\&$3/g;
1086: # (((5&3)|(4&6)))=((5&3)|(4&6))
1087: $expression=~
1088: s/\((\(\([_\.\d]+(?:\&[_\.\d]+)*\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+\))\)/$1/g;
1089: # ((5&3)|(4&6))|(1&2)=(5&3)|(4&6)|(1&2)
1090: $expression=~
1091: s/\((\([_\.\d]+(?:\&[_\.\d]+)*\))((?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+)\)\|(\([_\.\d]+(?:\&[_\.\d]+)*\))/\($1$2\|$3\)/g;
1092: return $expression;
1093: }
1094:
1095: # -------------------------------------------------------- Build condition hash
1096:
1097: #
1098: # Traces a route recursively through the map after it has been loaded
1099: # (I believe this really visits each resourcde that is reachable fromt he
1100: # start top node.
1101: #
1102: # - Marks hidden resources as hidden.
1103: # - Marks which resource URL's must be encrypted.
1104: # - Figures out (if necessary) the first resource in the map.
1105: # - Further builds the chunks of the big hash that define how
1106: # conditions work
1107: #
1108: # Note that the tracing strategy won't visit resources that are not linked to
1109: # anything or islands in the map (groups of resources that form a path but are not
1110: # linked in to the path that can be traced from the start resource...but that's ok
1111: # because by definition, those resources are not reachable by users of the course.
1112: #
1113: # Parameters:
1114: # sofar - _URI of the prior entry or 0 if this is the top.
1115: # rid - URI of the resource to visit.
1116: # beenhere - list of resources (each resource enclosed by &'s) that have
1117: # already been visited.
1118: # encflag - If true the resource that resulted in a recursive call to us
1119: # has an encoded URL (which means contained resources should too).
1120: # hdnflag - If true,the resource that resulted in a recursive call to us
1121: # was hidden (which means contained resources should be hidden too).
1122: # Returns
1123: # new value indicating how far the map has been traversed (the sofar).
1124: #
1125: sub traceroute {
1126: my ($sofar,$rid,$beenhere,$encflag,$hdnflag,$cid)=@_;
1127: my $newsofar=$sofar=simplify($sofar);
1128:
1129: unless ($beenhere=~/\&\Q$rid\E\&/) {
1130: $beenhere.=$rid.'&';
1131: my ($mapid,$resid)=split(/\./,$rid);
1132: my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$rid});
1133: my $hidden=&Apache::lonnet::EXT('resource.0.hiddenresource',$symb);
1134:
1135: if ($hdnflag || lc($hidden) eq 'yes') {
1136: $hiddenurl{$rid}=1;
1137: }
1138: if (!$hdnflag && lc($hidden) eq 'no') {
1139: delete($hiddenurl{$rid});
1140: }
1141:
1142: my $encrypt=&Apache::lonnet::EXT('resource.0.encrypturl',$symb);
1143: if ($encflag || lc($encrypt) eq 'yes') { $encurl{$rid}=1; }
1144:
1145: if (($retfrid eq '') && ($hash{'src_'.$rid})
1146: && ($hash{'src_'.$rid}!~/\.sequence$/)) {
1147: $retfrid=$rid;
1148: }
1149:
1150: my (@deeplink,@recurseup);
1151: if ($hash{'is_map_'.$rid}) {
1152: my ($cdom,$cnum) = split(/_/,$cid);
1153: my $mapsrc = $hash{'src_'.$rid};
1154: my $map_pc = $hash{'map_pc_'.$mapsrc};
1155: my @pcs = split(/,/,$hash{'map_hierarchy_'.$map_pc});
1156: shift(@pcs);
1157: @recurseup = map { &Apache::lonnet::declutter($hash{'map_id_'.$_}) } reverse(@pcs);
1158: my $mapname = &Apache::lonnet::declutter(&Apache::lonnet::deversion($mapsrc));
1159: my $deeplinkval = &get_mapparam($env{'user.name'},$env{'user.domain'},$cnum,$cdom,
1160: $rid,$mapname,'0.deeplink',\@recurseup);
1161: if ($deeplinkval ne '') {
1162: @deeplink = ($deeplinkval,'map');
1163: }
1164: } else {
1165: my @pcs = split(/,/,$hash{'map_hierarchy_'.$mapid});
1166: shift(@pcs);
1167: @recurseup = map { &Apache::lonnet::declutter($hash{'map_id_'.$_}) } reverse(@pcs);
1168: @deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb,'','','','',$cid,\@recurseup);
1169: }
1170: unless (@deeplink < 2) {
1171: $hash{'deeplinkonly_'.$rid}=join(':',map { &escape($_); } @deeplink);
1172: }
1173:
1174: if (defined($hash{'conditions_'.$rid})) {
1175: $hash{'conditions_'.$rid}=simplify(
1176: '('.$hash{'conditions_'.$rid}.')|('.$sofar.')');
1177: } else {
1178: $hash{'conditions_'.$rid}=$sofar;
1179: }
1180:
1181: # if the expression is just the 0th condition keep it
1182: # otherwise leave a pointer to this condition expression
1183:
1184: $newsofar = ($sofar eq '0') ? $sofar : '_'.$rid;
1185:
1186: # Recurse if the resource is a map:
1187:
1188: if (defined($hash{'is_map_'.$rid})) {
1189: if (defined($hash{'map_start_'.$hash{'src_'.$rid}})) {
1190: $sofar=$newsofar=
1191: &traceroute($sofar,
1192: $hash{'map_start_'.$hash{'src_'.$rid}},
1193: $beenhere,
1194: $encflag || $encurl{$rid},
1195: $hdnflag || $hiddenurl{$rid},
1196: $cid);
1197: }
1198: }
1199:
1200: # Processes links to this resource:
1201: # - verify the existence of any conditionals on the link to here.
1202: # - Recurse to any resources linked to us.
1203: #
1204: if (defined($hash{'to_'.$rid})) {
1205: foreach my $id (split(/\,/,$hash{'to_'.$rid})) {
1206: my $further=$sofar;
1207: #
1208: # If there's a condition associated with this link be sure
1209: # it's been defined else that's an error:
1210: #
1211: if ($hash{'undercond_'.$id}) {
1212: if (defined($hash{'condid_'.$hash{'undercond_'.$id}})) {
1213: $further=simplify('('.'_'.$rid.')&('.
1214: $hash{'condid_'.$hash{'undercond_'.$id}}.')');
1215: } else {
1216: $errtext.= '<br />'.
1217: &mt('Undefined condition ID: [_1]',
1218: $hash{'undercond_'.$id});
1219: }
1220: }
1221: # Recurse to resoruces that have to's to us.
1222: $newsofar=&traceroute($further,$hash{'goesto_'.$id},$beenhere,
1223: $encflag,$hdnflag,$cid);
1224: }
1225: }
1226: }
1227: return $newsofar;
1228: }
1229:
1230: # ------------------------------ Cascading conditions, quick access, parameters
1231:
1232: #
1233: # Seems a rather strangely named sub given what the comment above says it does.
1234:
1235:
1236: sub accinit {
1237: my ($uri,$short,$fn)=@_;
1238: my %acchash=();
1239: my %captured=();
1240: my $condcounter=0;
1241: $acchash{'acc.cond.'.$short.'.0'}=0;
1242:
1243: # This loop is only interested in conditions and
1244: # parameters in the big hash:
1245:
1246: foreach my $key (keys(%hash)) {
1247:
1248: # conditions:
1249:
1250: if ($key=~/^conditions/) {
1251: my $expr=$hash{$key};
1252:
1253: # try to find and factor out common sub-expressions
1254: # Any subexpression that is found is simplified, removed from
1255: # the original condition expression and the simplified sub-expression
1256: # substituted back in to the epxression..I'm not actually convinced this
1257: # factors anything out...but instead maybe simplifies common factors(?)
1258:
1259: foreach my $sub ($expr=~m/(\(\([_\.\d]+(?:\&[_\.\d]+)+\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)+\))+\))/g) {
1260: my $orig=$sub;
1261:
1262: my ($factor) = ($sub=~/\(\(([_\.\d]+\&(:?[_\.\d]+\&)*)(?:[_\.\d]+\&*)+\)(?:\|\(\1(?:[_\.\d]+\&*)+\))+\)/);
1263: next if (!defined($factor));
1264:
1265: $sub=~s/\Q$factor\E//g;
1266: $sub=~s/^\(/\($factor\(/;
1267: $sub.=')';
1268: $sub=simplify($sub);
1269: $expr=~s/\Q$orig\E/$sub/;
1270: }
1271: $hash{$key}=$expr;
1272:
1273: # If not yet seen, record in acchash and that we've seen it.
1274:
1275: unless (defined($captured{$expr})) {
1276: $condcounter++;
1277: $captured{$expr}=$condcounter;
1278: $acchash{'acc.cond.'.$short.'.'.$condcounter}=$expr;
1279: }
1280: # Parameters:
1281:
1282: } elsif ($key=~/^param_(\d+)\.(\d+)/) {
1283: my $prefix=&Apache::lonnet::encode_symb($hash{'map_id_'.$1},$2,
1284: $hash{'src_'.$1.'.'.$2});
1285: foreach my $param (split(/\&/,$hash{$key})) {
1286: my ($typename,$value)=split(/\=/,$param);
1287: my ($type,$name)=split(/\:/,$typename);
1288: $parmhash{$prefix.'.'.&unescape($name)}=
1289: &unescape($value);
1290: $parmhash{$prefix.'.'.&unescape($name).'.type'}=
1291: &unescape($type);
1292: }
1293: }
1294: }
1295: # This loop only processes id entries in the big hash.
1296:
1297: foreach my $key (keys(%hash)) {
1298: if ($key=~/^ids/) {
1299: foreach my $resid (split(/\,/,$hash{$key})) {
1300: my $uri=$hash{'src_'.$resid};
1301: my ($uripath,$urifile) =
1302: &Apache::lonnet::split_uri_for_cond($uri);
1303: if ($uripath) {
1304: my $uricond='0';
1305: if (defined($hash{'conditions_'.$resid})) {
1306: $uricond=$captured{$hash{'conditions_'.$resid}};
1307: }
1308: if (defined($acchash{'acc.res.'.$short.'.'.$uripath})) {
1309: if ($acchash{'acc.res.'.$short.'.'.$uripath}=~
1310: /(\&\Q$urifile\E\:[^\&]*)/) {
1311: my $replace=$1;
1312: my $regexp=$replace;
1313: #$regexp=~s/\|/\\\|/g;
1314: $acchash{'acc.res.'.$short.'.'.$uripath} =~
1315: s/\Q$regexp\E/$replace\|$uricond/;
1316: } else {
1317: $acchash{'acc.res.'.$short.'.'.$uripath}.=
1318: $urifile.':'.$uricond.'&';
1319: }
1320: } else {
1321: $acchash{'acc.res.'.$short.'.'.$uripath}=
1322: '&'.$urifile.':'.$uricond.'&';
1323: }
1324: }
1325: }
1326: }
1327: }
1328: $acchash{'acc.res.'.$short.'.'}='&:0&';
1329: my $courseuri=$uri;
1330: $courseuri=~s/^\/res\///;
1331: my $regexp = 1;
1332: &Apache::lonnet::delenv('(acc\.|httpref\.)',$regexp);
1333: &Apache::lonnet::appenv(\%acchash);
1334: }
1335:
1336: # ---------------- Selectively delete from randompick maps and hidden url parms
1337:
1338: sub hiddenurls {
1339: my $randomoutentry='';
1340: foreach my $rid (keys(%randompick)) {
1341: my $rndpick=$randompick{$rid};
1342: my $mpc=$hash{'map_pc_'.$hash{'src_'.$rid}};
1343: # ------------------------------------------- put existing resources into array
1344: my @currentrids=();
1345: foreach my $key (sort(keys(%hash))) {
1346: if ($key=~/^src_($mpc\.\d+)/) {
1347: if ($hash{'src_'.$1}) { push @currentrids, $1; }
1348: }
1349: }
1350: # rids are number.number and we want to numercially sort on
1351: # the second number
1352: @currentrids=sort {
1353: my (undef,$aid)=split(/\./,$a);
1354: my (undef,$bid)=split(/\./,$b);
1355: $aid <=> $bid;
1356: } @currentrids;
1357: next if ($#currentrids<$rndpick);
1358: # -------------------------------- randomly eliminate the ones that should stay
1359: my (undef,$id)=split(/\./,$rid);
1360: if ($randompickseed{$rid}) { $id=$randompickseed{$rid}; }
1361: my $setcode;
1362: if (defined($randomizationcode{$rid})) {
1363: if ($env{'form.CODE'} eq '') {
1364: $env{'form.CODE'} = $randomizationcode{$rid};
1365: $setcode = 1;
1366: }
1367: }
1368: my $rndseed=&Apache::lonnet::rndseed($id); # use id instead of symb
1369: if ($setcode) {
1370: undef($env{'form.CODE'});
1371: undef($setcode);
1372: }
1373: &Apache::lonnet::setup_random_from_rndseed($rndseed);
1374: my @whichids=&Math::Random::random_permuted_index($#currentrids+1);
1375: for (my $i=1;$i<=$rndpick;$i++) { $currentrids[$whichids[$i]]=''; }
1376: #&Apache::lonnet::logthis("$id,$rndseed,".join(':',@whichids));
1377: # -------------------------------------------------------- delete the leftovers
1378: for (my $k=0; $k<=$#currentrids; $k++) {
1379: if ($currentrids[$k]) {
1380: $hash{'randomout_'.$currentrids[$k]}=1;
1381: my ($mapid,$resid)=split(/\./,$currentrids[$k]);
1382: if ($rescount{$mapid}) {
1383: $rescount{$mapid} --;
1384: }
1385: if ($hash{'is_map_'.$currentrids[$k]}) {
1386: if ($mapcount{$mapid}) {
1387: $mapcount{$mapid} --;
1388: }
1389: }
1390: $randomoutentry.='&'.
1391: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
1392: $resid,
1393: $hash{'src_'.$currentrids[$k]}
1394: ).'&';
1395: }
1396: }
1397: }
1398: # ------------------------------ take care of explicitly hidden urls or folders
1399: foreach my $rid (keys(%hiddenurl)) {
1400: $hash{'randomout_'.$rid}=1;
1401: my ($mapid,$resid)=split(/\./,$rid);
1402: if ($rescount{$mapid}) {
1403: $rescount{$mapid} --;
1404: }
1405: if ($hash{'is_map_'.$rid}) {
1406: if ($mapcount{$mapid}) {
1407: $mapcount{$mapid} --;
1408: }
1409: }
1410: $randomoutentry.='&'.
1411: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,
1412: $hash{'src_'.$rid}).'&';
1413: }
1414: # --------------------------------------- append randomout entry to environment
1415: if ($randomoutentry) {
1416: &Apache::lonnet::appenv({'acc.randomout' => $randomoutentry});
1417: }
1418: }
1419:
1420: sub deeplinkouts {
1421: my $deeplinkoutentry;
1422: foreach my $rid (keys(%deeplinkout)) {
1423: $hash{'deeplinkout_'.$rid}=1;
1424: my ($mapid,$resid)=split(/\./,$rid);
1425: $deeplinkoutentry.='&'.
1426: &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,
1427: $hash{'src_'.$rid}).'&';
1428: }
1429: # --------------------------------------- append deeplinkout entry to environment
1430: if ($deeplinkoutentry) {
1431: &Apache::lonnet::appenv({'acc.deeplinkout' => $deeplinkoutentry});
1432: }
1433: }
1434:
1435: # -------------------------------------- populate big hash with map breadcrumbs
1436:
1437: # Create map_breadcrumbs_$pc from map_hierarchy_$pc by omitting intermediate
1438: # maps not shown in Course Contents table.
1439:
1440: sub mapcrumbs {
1441: my ($cid) = @_;
1442: foreach my $key (keys(%rescount)) {
1443: if ($hash{'map_hierarchy_'.$key}) {
1444: my $skipnext = 0;
1445: foreach my $id (split(/,/,$hash{'map_hierarchy_'.$key}),$key) {
1446: my $rid = $hash{'ids_'.$hash{'map_id_'.$id}};
1447: unless (($skipnext) || (!&is_advanced($cid) && $hash{'deeplinkout_'.$rid})) {
1448: $hash{'map_breadcrumbs_'.$key} .= "$id,";
1449: }
1450: unless (($id == 0) || ($id == 1)) {
1451: if ((!$rescount{$id}) || ($rescount{$id} == 1 && $mapcount{$id} == 1)) {
1452: $skipnext = 1;
1453: } else {
1454: $skipnext = 0;
1455: }
1456: }
1457: }
1458: $hash{'map_breadcrumbs_'.$key} =~ s/,$//;
1459: }
1460: }
1461: }
1462:
1463: # ---------------------------------------------------- Read map and all submaps
1464:
1465: sub readmap {
1466: my ($short,$critmsg_check) = @_;
1467: $short=~s/^\///;
1468:
1469: # TODO: Hidden dependency on current user:
1470:
1471: my %cenv=&Apache::lonnet::coursedescription($short,{'freshen_cache'=>1});
1472:
1473: my $fn=$cenv{'fn'};
1474: my $uri;
1475: $short=~s/\//\_/g;
1476: unless ($uri=$cenv{'url'}) {
1477: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1478: "Could not load course $short.</font>");
1479: return ('',&mt('No course data available.'));;
1480: }
1481: @cond=('true:normal');
1482:
1483: unless (open(LOCKFILE,">","$fn.db.lock")) {
1484: #
1485: # Most likely a permissions problem on the lockfile or its directory.
1486: #
1487: $retfurl = '';
1488: return ($retfurl,'<br />'.&mt('Map not loaded - Lock file could not be opened when reading map:').' <tt>'.$fn.'</tt>.');
1489: }
1490: my $lock=0;
1491: my $gotstate=0;
1492:
1493: # If we can get the lock without delay any files there are idle
1494: # and from some prior request. We'll kill them off and regenerate them:
1495:
1496: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1497: $lock=1; # Remember that we hold the lock.
1498: &unlink_tmpfiles($fn);
1499: }
1500: undef %randompick;
1501: undef %randompickseed;
1502: undef %randomorder;
1503: undef %randomizationcode;
1504: undef %hiddenurl;
1505: undef %encurl;
1506: undef %deeplinkout;
1507: undef %rescount;
1508: undef %mapcount;
1509: $retfrid='';
1510: $errtext='';
1511: my ($untiedhash,$untiedparmhash,$tiedhash,$tiedparmhash); # More state flags.
1512:
1513: # if we got the lock, regenerate course regnerate empty files and tie them.
1514:
1515: if ($lock) {
1516: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_WRCREAT(),0640)) {
1517: $tiedhash = 1;
1518: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_WRCREAT(),0640)) {
1519: $tiedparmhash = 1;
1520: $gotstate = &build_tmp_hashes($uri,
1521: $fn,
1522: $short,
1523: \%cenv); # TODO: Need to provide requested user@dom
1524: unless ($gotstate) {
1525: &Apache::lonnet::logthis('Failed to write statemap at first attempt '.$fn.' for '.$uri.'.</font>');
1526: }
1527: $untiedparmhash = untie(%parmhash);
1528: unless ($untiedparmhash) {
1529: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1530: 'Could not untie coursemap parmhash '.$fn.' for '.$uri.'.</font>');
1531: }
1532: }
1533: $untiedhash = untie(%hash);
1534: unless ($untiedhash) {
1535: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1536: 'Could not untie coursemap hash '.$fn.' for '.$uri.'.</font>');
1537: }
1538: }
1539: flock(LOCKFILE,LOCK_UN); # RF: this is what I don't get unless there are other
1540: # unlocked places the remainder happens..seems like if we
1541: # just kept the lock here the rest of the code would have
1542: # been much easier?
1543: }
1544: unless ($lock && $tiedhash && $tiedparmhash) {
1545: # if we are here it is likely because we are already trying to
1546: # initialize the course in another child, busy wait trying to
1547: # tie the hashes for the next 90 seconds, if we succeed forward
1548: # them on to navmaps, if we fail, throw up the Could not init
1549: # course screen
1550: #
1551: # RF: I'm not seeing the case where the ties/unties can fail in a way
1552: # that can be remedied by this. Since we owned the lock seems
1553: # Tie/untie failures are a result of something like a permissions problem instead?
1554: #
1555:
1556: # In any vent, undo what we did manage to do above first:
1557: if ($lock) {
1558: # Got the lock but not the DB files
1559: flock(LOCKFILE,LOCK_UN);
1560: $lock = 0;
1561: }
1562: if ($tiedhash) {
1563: unless($untiedhash) {
1564: untie(%hash);
1565: }
1566: }
1567: if ($tiedparmhash) {
1568: unless($untiedparmhash) {
1569: untie(%parmhash);
1570: }
1571: }
1572: # Log our failure:
1573:
1574: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1575: "Could not tie coursemap $fn for $uri.</font>");
1576: $tiedhash = '';
1577: $tiedparmhash = '';
1578: my $i=0;
1579:
1580: # Keep on retrying the lock for 90 sec until we succeed.
1581:
1582: while($i<90) {
1583: $i++;
1584: sleep(1);
1585: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1586:
1587: # Got the lock, tie the hashes...the assumption in this code is
1588: # that some other worker thread has created the db files quite recently
1589: # so no load is needed:
1590:
1591: $lock = 1;
1592: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
1593: $tiedhash = 1;
1594: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_READER(),0640)) {
1595: $tiedparmhash = 1;
1596: if (-e "$fn.state") {
1597: $retfurl='/adm/navmaps';
1598:
1599: # BUG BUG: Side effect!
1600: # Should conditionalize on something so that we can use this
1601: # to load maps for courses that are not current?
1602: #
1603: &Apache::lonnet::appenv({"request.course.id" => $short,
1604: "request.course.fn" => $fn,
1605: "request.course.uri" => $uri,
1606: "request.course.tied" => time});
1607:
1608: $untiedhash = untie(%hash);
1609: $untiedparmhash = untie(%parmhash);
1610: $gotstate = 1;
1611: last;
1612: }
1613: $untiedparmhash = untie(%parmhash);
1614: }
1615: $untiedhash = untie(%hash);
1616: }
1617: }
1618: }
1619: if ($lock) {
1620: flock(LOCKFILE,LOCK_UN);
1621: $lock = 0;
1622: if ($tiedparmhash) {
1623: unless ($untiedparmhash) {
1624: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1625: 'Could not untie coursemap parmhash '.$fn.' for '.$uri.'.</font>');
1626: }
1627: }
1628: if ($tiedparmhash) {
1629: unless ($untiedhash) {
1630: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1631: 'Could not untie coursemap hash '.$fn.' for '.$uri.'.</font>');
1632: }
1633: }
1634: }
1635: }
1636: # I think this branch of code is all about what happens if we just did the stuff above,
1637: # but found that the state file did not exist...again if we'd just held the lock
1638: # would that have made this logic simpler..as generating all the files would be
1639: # an atomic operation with respect to the lock.
1640: #
1641: unless ($gotstate) {
1642: $lock = 0;
1643: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1644: 'Could not read statemap '.$fn.' for '.$uri.'.</font>');
1645: &unlink_tmpfiles($fn);
1646: if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
1647: $lock=1;
1648: }
1649: undef %randompick;
1650: undef %randompickseed;
1651: undef %randomorder;
1652: undef %randomizationcode;
1653: undef %hiddenurl;
1654: undef %encurl;
1655: undef %deeplinkout;
1656: undef %rescount;
1657: undef %mapcount;
1658: $errtext='';
1659: $retfrid='';
1660: #
1661: # Once more through the routine of tying and loading and so on.
1662: #
1663: if ($lock) {
1664: if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_WRCREAT(),0640)) {
1665: if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_WRCREAT(),0640)) {
1666: $gotstate = &build_tmp_hashes($uri,$fn,$short,\%cenv); # TODO: User dependent?
1667: unless ($gotstate) {
1668: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1669: 'Failed to write statemap at second attempt '.$fn.' for '.$uri.'.</font>');
1670: }
1671: unless (untie(%parmhash)) {
1672: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1673: 'Could not untie coursemap parmhash '.$fn.'.db for '.$uri.'.</font>');
1674: }
1675: } else {
1676: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1677: 'Could not tie coursemap '.$fn.'__parms.db for '.$uri.'.</font>');
1678: }
1679: unless (untie(%hash)) {
1680: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1681: 'Could not untie coursemap hash '.$fn.'.db for '.$uri.'.</font>');
1682: }
1683: } else {
1684: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1685: 'Could not tie coursemap '.$fn.'.db for '.$uri.'.</font>');
1686: }
1687: flock(LOCKFILE,LOCK_UN);
1688: $lock = 0;
1689: } else {
1690: # Failed to get the immediate lock.
1691:
1692: &Apache::lonnet::logthis('<font color="blue">WARNING: '.
1693: 'Could not obtain lock to tie coursemap hash '.$fn.'.db for '.$uri.'.</font>');
1694: }
1695: }
1696: close(LOCKFILE);
1697: unless (($errtext eq '') || ($env{'request.course.uri'} =~ m{^/uploaded/})) {
1698: &Apache::lonmsg::author_res_msg($env{'request.course.uri'},
1699: $errtext); # TODO: User dependent?
1700: }
1701: # ------------------------------------------------- Check for critical messages
1702:
1703: # Depends on user must parameterize this as well..or separate as this is:
1704: # more part of determining what someone sees on entering a course?
1705: # When lonuserstate::readmap() is called from lonroles.pm, i.e.,
1706: # after selecting a role in a course, critical_redirect will be called,
1707: # unless the course has a blocking event in effect, which suppresses
1708: # critical message checking (users without evb priv).
1709: #
1710:
1711: if ($critmsg_check) {
1712: my ($redirect,$url) = &Apache::loncommon::critical_redirect();
1713: if ($redirect) {
1714: $retfurl = $url;
1715: }
1716: }
1717: return ($retfurl,$errtext);
1718: }
1719:
1720: #
1721: # This sub is called when the course hash and the param hash have been tied and
1722: # their lock file is held.
1723: # Parameters:
1724: # $uri - URI that identifies the course.
1725: # $fn - The base path/filename of the files that make up the context
1726: # being built.
1727: # $short - Short course name.
1728: # $cenvref - Reference to the course environment hash returned by
1729: # Apache::lonnet::coursedescription
1730: #
1731: # Assumptions:
1732: # The globals
1733: # %hash, %paramhash are tied to their gdbm files and we hold the lock on them.
1734: #
1735: sub build_tmp_hashes {
1736: my ($uri,$fn,$short,$cenvref) = @_;
1737:
1738: unless(ref($cenvref) eq 'HASH') {
1739: return;
1740: }
1741: my %cenv = %{$cenvref};
1742: my $gotstate = 0;
1743: %hash=(); # empty the global course and parameter hashes.
1744: %parmhash=();
1745: $errtext=''; # No error messages yet.
1746: $pc=0;
1747: &clear_mapalias_count();
1748: &processversionfile(%cenv);
1749:
1750: # URI Of the map file.
1751:
1752: my $furi=&Apache::lonnet::clutter($uri);
1753: #
1754: # the map staring points.
1755: #
1756: $hash{'src_0.0'}=&versiontrack($furi);
1757: $hash{'title_0.0'}=&Apache::lonnet::metadata($uri,'title');
1758: $hash{'ids_'.$furi}='0.0';
1759: $hash{'is_map_0.0'}=1;
1760:
1761: # Load the map.. note that loadmap may implicitly recurse if the map contains
1762: # sub-maps.
1763:
1764: &loadmap($uri,'0.0',$short);
1765:
1766: # The code below only executes if there is a starting point for the map>
1767: # Q/BUG??? If there is no start resource for the map should that be an error?
1768: #
1769:
1770: if (defined($hash{'map_start_'.$uri})) {
1771: &Apache::lonnet::appenv({"request.course.id" => $short,
1772: "request.course.fn" => $fn,
1773: "request.course.uri" => $uri,
1774: "request.course.tied" => time});
1775: $env{'request.course.id'}=$short;
1776: &traceroute('0',$hash{'map_start_'.$uri},'&','','',$short);
1777: &accinit($uri,$short,$fn);
1778: &hiddenurls();
1779: }
1780: $errtext .= &get_mapalias_errors();
1781: # ------------------------------------------------------- Put versions into src
1782: foreach my $key (keys(%hash)) {
1783: if ($key=~/^src_/) {
1784: $hash{$key}=&putinversion($hash{$key});
1785: } elsif ($key =~ /^(map_(?:start|finish|pc)_)(.*)/) {
1786: my ($type, $url) = ($1,$2);
1787: my $value = $hash{$key};
1788: $hash{$type.&putinversion($url)}=$value;
1789: }
1790: }
1791: # ---------------------------------------------------------------- Encrypt URLs
1792: foreach my $id (keys(%encurl)) {
1793: # $hash{'src_'.$id}=&Apache::lonenc::encrypted($hash{'src_'.$id});
1794: $hash{'encrypted_'.$id}=1;
1795: }
1796: # ----------------------------------------------- Close hashes to finally store
1797: # --------------------------------- Routine must pass this point, no early outs
1798: $hash{'first_rid'}=$retfrid;
1799: my ($mapid,$resid)=split(/\./,$retfrid);
1800: $hash{'first_mapurl'}=$hash{'map_id_'.$mapid};
1801: my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$retfrid});
1802: $retfurl=&add_get_param($hash{'src_'.$retfrid},{ 'symb' => $symb });
1803: if ($hash{'encrypted_'.$retfrid}) {
1804: $retfurl=&Apache::lonenc::encrypted($retfurl,(&Apache::lonnet::allowed('adv') ne 'F'));
1805: }
1806: $hash{'first_url'}=$retfurl;
1807: # ---------------------------------------------------- Store away initial state
1808: {
1809: my $cfh;
1810: if (open($cfh,">","$fn.state")) {
1811: print $cfh join("\n",@cond);
1812: $gotstate = 1;
1813: } else {
1814: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
1815: "Could not write statemap $fn for $uri.</font>");
1816: }
1817: }
1818:
1819: # Was initial access via a deep-link?
1820: my ($cdom,$cnum) = split(/_/,$short);
1821: if (($cdom ne '') && ($env{'request.deeplink.login'} ne '')) {
1822: my $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1823: if ($deeplink_symb) {
1824: my ($loginrid,$deeplink_login_pc,$login_hierarchy);
1825: my ($map,$resid,$url) = &Apache::lonnet::decode_symb($deeplink_symb);
1826: $loginrid = $hash{'map_pc_'.&Apache::lonnet::clutter($map)}.'.'.$resid;
1827: if ($deeplink_symb =~ /\.(page|sequence)$/) {
1828: $deeplink_login_pc = $hash{'map_pc_'.&Apache::lonnet::clutter($url)};
1829: } else {
1830: $deeplink_login_pc = $hash{'map_pc_'.&Apache::lonnet::clutter($map)};
1831: }
1832: my $deeplink;
1833: if ($hash{'deeplinkonly_'.$loginrid} ne '') {
1834: my @deeplinkinfo = map { &unescape($_); } split(/:/,$hash{'deeplinkonly_'.$loginrid});
1835: unless (@deeplinkinfo < 2) {
1836: $deeplink = $deeplinkinfo[0];
1837: }
1838: }
1839: if ($deeplink) {
1840: my $disallow;
1841: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
1842: if (($protect ne 'none') && ($protect ne '')) {
1843: my ($acctype,$item) = split(/:/,$protect);
1844: if ($acctype =~ /lti(c|d)$/) {
1845: unless ($env{'request.linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
1846: $disallow = 1;
1847: }
1848: } elsif ($acctype eq 'key') {
1849: unless ($env{'request.linkkey'} eq $item) {
1850: $disallow = 1;
1851: }
1852: }
1853: }
1854: if ($disallow) {
1855: &Apache::lonnet::delenv('request.deeplink.login');
1856: if ($env{'request.deeplink.target'} ne '') {
1857: &Apache::lonnet::delenv('request.deeplink.target');
1858: }
1859: } else {
1860: if ($others eq 'hide') {
1861: my @recfolders;
1862: if ($scope eq 'rec') {
1863: foreach my $key (keys(%hash)) {
1864: if ($key=~/^map_hierarchy_(\d+)$/) {
1865: my $mpc = $1;
1866: my @ids = split(/,/,$hash{$key});
1867: if (grep(/^$deeplink_login_pc$/,@ids)) {
1868: my $idx;
1869: foreach my $mapid (@ids) {
1870: if ($idx) {
1871: push(@recfolders,$mapid);
1872: } elsif ($mapid == $deeplink_login_pc) {
1873: push(@recfolders,$mapid);
1874: $idx = $mapid;
1875: }
1876: }
1877: push(@recfolders,$mpc);
1878: }
1879: }
1880: }
1881: }
1882: foreach my $key (keys(%hash)) {
1883: if ($key=~/^src_(.+)$/) {
1884: my $rid = $1;
1885: next if ($rid eq '0.0');
1886: next if ($rid eq $loginrid);
1887: if ($scope ne 'res') {
1888: my $mapid = (split(/\./,$rid))[0];
1889: next if ($mapid eq $deeplink_login_pc);
1890: if ($scope eq 'rec') {
1891: next if (grep(/^$mapid$/,@recfolders));
1892: }
1893: }
1894: $deeplinkout{$rid} = 1;
1895: }
1896: }
1897: }
1898: }
1899: &deeplinkouts();
1900: }
1901: }
1902: }
1903: &mapcrumbs();
1904: return $gotstate;
1905: }
1906:
1907: sub unlink_tmpfiles {
1908: my ($fn) = @_;
1909: my $file_dir = dirname($fn);
1910:
1911: if ("$file_dir/" eq LONCAPA::tempdir()) {
1912: my @files = qw (.db _symb.db .state _parms.db);
1913: foreach my $file (@files) {
1914: if (-e $fn.$file) {
1915: unless (unlink($fn.$file)) {
1916: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
1917: "Could not unlink ".$fn.$file."</font>");
1918: }
1919: }
1920: }
1921: }
1922: return;
1923: }
1924:
1925: # ------------------------------------------------------- Evaluate state string
1926:
1927: sub evalstate {
1928: my $fn=$env{'request.course.fn'}.'.state';
1929: my $state='';
1930: if (-e $fn) {
1931: my @conditions=();
1932: {
1933: open(my $fh,"<",$fn);
1934: @conditions=<$fh>;
1935: close($fh);
1936: }
1937: my $safeeval = new Safe;
1938: my $safehole = new Safe::Hole;
1939: $safeeval->permit("entereval");
1940: $safeeval->permit(":base_math");
1941: $safeeval->deny(":base_io");
1942: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1943: foreach my $line (@conditions) {
1944: chomp($line);
1945: my ($condition,$weight)=split(/\:/,$line);
1946: if ($safeeval->reval($condition)) {
1947: if ($weight eq 'force') {
1948: $state.='3';
1949: } else {
1950: $state.='2';
1951: }
1952: } else {
1953: if ($weight eq 'stop') {
1954: $state.='0';
1955: } else {
1956: $state.='1';
1957: }
1958: }
1959: }
1960: }
1961: &Apache::lonnet::appenv({'user.state.'.$env{'request.course.id'} => $state});
1962: return $state;
1963: }
1964:
1965: sub get_mapparam {
1966: my ($uname,$udom,$cnum,$cdom,$rid,$mapname,$what,$recurseupref) = @_;
1967: unless ($mapname) { return; }
1968:
1969: # ------------------------------------------------- Get coursedata (if present)
1970: my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
1971: if (!ref($courseopt)) {
1972: undef($courseopt);
1973: }
1974:
1975: # --------------------------------------------------- Get userdata (if present)
1976: my $useropt=&Apache::lonnet::get_userresdata($uname,$udom);
1977: if (!ref($useropt)) {
1978: undef($useropt);
1979: }
1980:
1981: my @recurseup;
1982: if (ref($recurseupref) eq 'ARRAY') {
1983: @recurseup = @{$recurseupref};
1984: }
1985:
1986: # Get the section if there is one.
1987:
1988: my $cid = $cdom.'_'.$cnum;
1989: my $csec=$env{'request.course.sec'};
1990: my $cgroup='';
1991: my @cgrps=split(/:/,$env{'request.course.groups'});
1992: if (@cgrps > 0) {
1993: @cgrps = sort(@cgrps);
1994: $cgroup = $cgrps[0];
1995: }
1996:
1997: my $rwhat=$what;
1998: $what=~s/^parameter\_//;
1999: $what=~s/\_/\./;
2000:
2001: # Build the hash keys for the lookup:
2002:
2003: my $mapparm=$mapname.'___(all).'.$what;
2004: my $recurseparm=$mapname.'___(rec).'.$what;
2005: my $usercourseprefix=$cid;
2006:
2007: my $grplevelm = "$usercourseprefix.[$cgroup].$mapparm";
2008: my $seclevelm = "$usercourseprefix.[$csec].$mapparm";
2009: my $courselevelm = "$usercourseprefix.$mapparm";
2010:
2011: my $grpleveli = "$usercourseprefix.[$cgroup].$recurseparm";
2012: my $secleveli = "$usercourseprefix.[$csec].$recurseparm";
2013: my $courseleveli = "$usercourseprefix.$recurseparm";
2014:
2015: # Check per user
2016:
2017: if ($uname and defined($useropt)) {
2018: if (defined($$useropt{$courselevelm})) {
2019: return $$useropt{$courselevelm};
2020: }
2021: if (defined($$useropt{$courseleveli})) {
2022: return $$useropt{$courseleveli};
2023: }
2024: foreach my $item (@recurseup) {
2025: my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
2026: if (defined($$useropt{$norecursechk})) {
2027: if ($what =~ /\.(encrypturl|hiddenresource)$/) {
2028: return $$useropt{$norecursechk};
2029: } else {
2030: last;
2031: }
2032: }
2033: }
2034: }
2035:
2036: # Check course -- group
2037:
2038: if ($cgroup ne '' and defined ($courseopt)) {
2039: if (defined($$courseopt{$grplevelm})) {
2040: return $$courseopt{$grplevelm};
2041: }
2042: if (defined($$courseopt{$grpleveli})) {
2043: return $$courseopt{$grpleveli};
2044: }
2045: foreach my $item (@recurseup) {
2046: my $norecursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(all).'.$what;
2047: if (defined($$courseopt{$norecursechk})) {
2048: if ($what =~ /\.(encrypturl|hiddenresource)$/) {
2049: return $$courseopt{$norecursechk};
2050: } else {
2051: last;
2052: }
2053: }
2054: }
2055: }
2056:
2057: # Check course -- section
2058:
2059: if ($csec ne '' and defined($courseopt)) {
2060: if (defined($$courseopt{$seclevelm})) {
2061: return $$courseopt{$seclevelm};
2062: }
2063: if (defined($$courseopt{$secleveli})) {
2064: return $$courseopt{$secleveli};
2065: }
2066: foreach my $item (@recurseup) {
2067: my $norecursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(all).'.$what;
2068: if (defined($$courseopt{$norecursechk})) {
2069: if ($what =~ /\.(encrypturl|hiddenresource)$/) {
2070: return $$courseopt{$norecursechk};
2071: } else {
2072: last;
2073: }
2074: }
2075: }
2076: }
2077:
2078: # Check the map parameters themselves:
2079:
2080: if ($hash{'param_'.$rid}) {
2081: my @items = split(/\&/,$hash{'param_'.$rid});
2082: my $thisparm;
2083: foreach my $item (@items) {
2084: my ($esctype,$escname,$escvalue) = ($item =~ /^([^:]+):([^=]+)=(.*)$/);
2085: my $name = &unescape($escname);
2086: my $value = &unescape($escvalue);
2087: if ($name eq $what) {
2088: $thisparm = $value;
2089: last;
2090: }
2091: }
2092: if (defined($thisparm)) {
2093: return $thisparm;
2094: }
2095: }
2096:
2097: # Additional course parameters:
2098:
2099: if (defined($courseopt)) {
2100: if (defined($$courseopt{$courselevelm})) {
2101: return $$courseopt{$courselevelm};
2102: }
2103:
2104: if (defined($$courseopt{$courseleveli})) {
2105: return $$courseopt{$courseleveli};
2106: }
2107:
2108: if (@recurseup) {
2109: foreach my $item (@recurseup) {
2110: my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
2111: if (defined($$courseopt{$norecursechk})) {
2112: if ($what =~ /\.(encrypturl|hiddenresource)$/) {
2113: return $$courseopt{$norecursechk};
2114: } else {
2115: last;
2116: }
2117: }
2118: }
2119: }
2120: }
2121: return undef;
2122: }
2123:
2124: # This block seems to have code to manage/detect doubly defined
2125: # aliases in maps.
2126:
2127: {
2128: my %mapalias_cache;
2129: sub count_mapalias {
2130: my ($value,$resid) = @_;
2131: push(@{ $mapalias_cache{$value} }, $resid);
2132: }
2133:
2134: sub get_mapalias_errors {
2135: my $error_text;
2136: foreach my $mapalias (sort(keys(%mapalias_cache))) {
2137: next if (scalar(@{ $mapalias_cache{$mapalias} } ) == 1);
2138: my $count;
2139: my $which =
2140: join('</li><li>',
2141: map {
2142: my $id = $_;
2143: if (exists($hash{'src_'.$id})) {
2144: $count++;
2145: }
2146: my ($mapid) = split(/\./,$id);
2147: &mt('Resource [_1][_2]in Map [_3]',
2148: $hash{'title_'.$id},'<br />',
2149: $hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$mapid}}});
2150: } (@{ $mapalias_cache{$mapalias} }));
2151: next if ($count < 2);
2152: $error_text .= '<div class="LC_error">'.
2153: &mt('Error: Found the mapalias "[_1]" defined multiple times.',
2154: $mapalias).
2155: '</div><ul><li>'.$which.'</li></ul>';
2156: }
2157: &clear_mapalias_count();
2158: return $error_text;
2159: }
2160: sub clear_mapalias_count {
2161: undef(%mapalias_cache);
2162: }
2163: }
2164: 1;
2165: __END__
2166:
2167: =head1 NAME
2168:
2169: Apache::lonuserstate - Construct and maintain state and binary representation
2170: of course for user
2171:
2172: =head1 SYNOPSIS
2173:
2174: Invoked by lonroles.pm.
2175:
2176: &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
2177:
2178: =head1 INTRODUCTION
2179:
2180: This module constructs and maintains state and binary representation
2181: of course for user.
2182:
2183: This is part of the LearningOnline Network with CAPA project
2184: described at http://www.lon-capa.org.
2185:
2186: =head1 SUBROUTINES
2187:
2188: =over
2189:
2190: =item loadmap()
2191:
2192: Loads map from disk
2193:
2194: =item simplify()
2195:
2196: Simplify expression
2197:
2198: =item traceroute()
2199:
2200: Build condition hash
2201:
2202: =item accinit()
2203:
2204: Cascading conditions, quick access, parameters
2205:
2206: =item readmap()
2207:
2208: Read map and all submaps
2209:
2210: =item evalstate()
2211:
2212: Evaluate state string
2213:
2214: =back
2215:
2216: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>