Annotation of rat/lonuserstate.pm, revision 1.153

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

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