File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.169: download - view: text, annotated - select for diffs
Tue Oct 4 20:39:57 2022 UTC (18 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Provide more information to privileged users if map could not be loaded
  during course initialization because file was missing.

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

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