Annotation of rat/lonuserstate.pm, revision 1.142

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

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