File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.157: download - view: text, annotated - select for diffs
Tue Nov 13 03:59:17 2018 UTC (5 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6400
  - deeplink parameter determines whether deep-linked items are listed in
    and/or linked to in Course Contents and student's view of Grades

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

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