File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.149.2.6: download - view: text, annotated - select for diffs
Wed Jul 3 02:16:44 2024 UTC (3 weeks, 3 days ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_5
Diff to branchpoint 1.149: preferred, unified
- For 2.11
  Backport 1.150 (part), 1.169 (part), 1.170

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

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