Annotation of rat/lonuserstate.pm, revision 1.149.2.4

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

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