Annotation of rat/lonuserstate.pm, revision 1.149.2.5.2.4

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

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