Annotation of rat/lonuserstate.pm, revision 1.170

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

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