Annotation of rat/lonuserstate.pm, revision 1.149.2.2

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>