Annotation of rat/lonuserstate.pm, revision 1.171

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

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