File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.147: download - view: text, annotated - select for diffs
Fri Aug 16 01:41:05 2013 UTC (10 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC2, version_2_11_0_RC1, HEAD
- Exclude HTML tags from translation phrases.
 (Corresponding German translation file phrases and translations previously
  updated in rev 1.514).

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

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