File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.125: download - view: text, annotated - select for diffs
Tue Oct 16 21:14:53 2007 UTC (16 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#5477 - improve error message readability

    1: # The LearningOnline Network with CAPA
    2: # Construct and maintain state and binary representation of course for user
    3: #
    4: # $Id: lonuserstate.pm,v 1.125 2007/10/16 21:14:53 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonuserstate;
   31: 
   32: # ------------------------------------------------- modules used by this module
   33: use strict;
   34: use HTML::TokeParser;
   35: use Apache::lonnet;
   36: use Apache::lonlocal;
   37: use Apache::loncommon();
   38: use GDBM_File;
   39: use Apache::lonmsg;
   40: use Safe;
   41: use Safe::Hole;
   42: use Opcode;
   43: use Apache::lonenc;
   44: use Fcntl qw(:flock);
   45: use LONCAPA;
   46:  
   47: 
   48: # ---------------------------------------------------- Globals for this package
   49: 
   50: my $pc;      # Package counter
   51: my %hash;    # The big tied hash
   52: my %parmhash;# The hash with the parameters
   53: my @cond;    # Array with all of the conditions
   54: my $errtext; # variable with all errors
   55: my $retfrid; # variable with the very first RID in the course
   56: my $retfurl; # first URL
   57: my %randompick; # randomly picked resources
   58: my %randompickseed; # optional seed for randomly picking resources
   59: my %randomorder; # maps to order contents randomly
   60: my %encurl; # URLs in this folder are supposed to be encrypted
   61: my %hiddenurl; # this URL (or complete folder) is supposed to be hidden
   62: 
   63: # ----------------------------------- Remove version from URL and store in hash
   64: 
   65: sub versiontrack {
   66:     my $uri=shift;
   67:     if ($uri=~/\.(\d+)\.\w+$/) {
   68: 	my $version=$1;
   69: 	$uri=~s/\.\d+\.(\w+)$/\.$1/;
   70:         unless ($hash{'version_'.$uri}) {
   71: 	    $hash{'version_'.$uri}=$version;
   72: 	}
   73:     }
   74:     return $uri;
   75: }
   76: 
   77: # -------------------------------------------------------------- Put in version
   78: 
   79: sub putinversion {
   80:     my $uri=shift;
   81:     my $key=$env{'request.course.id'}.'_'.&Apache::lonnet::clutter($uri);
   82:     if ($hash{'version_'.$uri}) {
   83: 	my $version=$hash{'version_'.$uri};
   84: 	if ($version eq 'mostrecent') { return $uri; }
   85: 	if ($version eq &Apache::lonnet::getversion(
   86: 			&Apache::lonnet::filelocation('',$uri))) 
   87: 	             { return $uri; }
   88: 	$uri=~s/\.(\w+)$/\.$version\.$1/;
   89:     }
   90:     &Apache::lonnet::do_cache_new('courseresversion',$key,&Apache::lonnet::declutter($uri),600);
   91:     return $uri;
   92: }
   93: 
   94: # ----------------------------------------- Processing versions file for course
   95: 
   96: sub processversionfile {
   97:     my %cenv=@_;
   98:     my %versions=&Apache::lonnet::dump('resourceversions',
   99: 				       $cenv{'domain'},
  100: 				       $cenv{'num'});
  101:     foreach my $ver (keys(%versions)) {
  102: 	if ($ver=~/^error\:/) { return; }
  103: 	$hash{'version_'.$ver}=$versions{$ver};
  104:     }
  105: }
  106: 
  107: # --------------------------------------------------------- Loads map from disk
  108: 
  109: sub loadmap { 
  110:     my ($uri,$parent_rid)=@_;
  111:     if ($hash{'map_pc_'.$uri}) { 
  112: 	$errtext.='<p class="LC_error">'.
  113: 	    &mt('Multiple use of sequence/page [_1]! The course will not function properly.','<tt>'.$uri.'</tt>').
  114: 	    '</p>';
  115: 	return; 
  116:     }
  117:     $pc++;
  118:     my $lpc=$pc;
  119:     $hash{'map_pc_'.$uri}=$lpc;
  120:     $hash{'map_id_'.$lpc}=$uri;
  121: 
  122: # Determine and check filename
  123:     my $fn=&Apache::lonnet::filelocation('',&putinversion($uri));
  124: 
  125:     my $ispage=($fn=~/\.page$/);
  126: 
  127:     unless (($fn=~/\.sequence$/) ||
  128:             ($fn=~/\.page$/)) { 
  129: 	$errtext.=&mt("<br />Invalid map: <tt>[_1]</tt>",$fn);
  130: 	return; 
  131:     }
  132: 
  133:     my $instr=&Apache::lonnet::getfile($fn);
  134: 
  135:     if ($instr eq -1) {
  136:         $errtext.=&mt('<br />Map not loaded: The file <tt>[_1]</tt> does not exist.',$fn);
  137: 	return;
  138:     }
  139: 
  140: # Successfully got file, parse it
  141: 
  142:     my $parser = HTML::TokeParser->new(\$instr);
  143:     $parser->attr_encoded(1);
  144:     # first get all parameters
  145:     while (my $token = $parser->get_token) {
  146: 	next if ($token->[0] ne 'S');
  147: 	if ($token->[1] eq 'param') {
  148: 	    &parse_param($token,$lpc);
  149: 	} 
  150:     }
  151:     #reset parser
  152:     $parser = HTML::TokeParser->new(\$instr);
  153:     $parser->attr_encoded(1);
  154: 
  155:     my $linkpc=0;
  156: 
  157:     $fn=~/\.(\w+)$/;
  158: 
  159:     $hash{'map_type_'.$lpc}=$1;
  160: 
  161:     my $randomize = ($randomorder{$parent_rid} =~ /^yes$/i);
  162: 
  163:     my @map_ids;
  164:     while (my $token = $parser->get_token) {
  165: 	next if ($token->[0] ne 'S');
  166: 	if ($token->[1] eq 'resource') {
  167: 	    push(@map_ids,&parse_resource($token,$lpc,$ispage,$uri));
  168: 	} elsif ($token->[1] eq 'link' && !$randomize) {
  169: # ----------------------------------------------------------------------- Links
  170: 	    &make_link(++$linkpc,$lpc,$token->[2]->{'to'},
  171: 		       $token->[2]->{'from'},
  172: 		       $token->[2]->{'condition'});
  173: 	} elsif ($token->[1] eq 'condition' && !$randomize) {
  174: 	    &parse_condition($token,$lpc);
  175: 	}
  176:     }
  177: 
  178:     if ($randomize) {
  179: 	if (!$env{'request.role.adv'}) {
  180: 	    my $seed;
  181: 	    if (defined($randompickseed{$parent_rid})) {
  182: 		$seed = $randompickseed{$parent_rid};
  183: 	    } else {
  184: 		my ($mapid,$resid)=split(/\./,$parent_rid);
  185: 		my $symb=
  186: 		    &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
  187: 						 $resid,$hash{'src_'.$parent_rid});
  188: 		
  189: 		$seed = $symb;
  190: 	    }
  191: 	
  192: 	    my $rndseed=&Apache::lonnet::rndseed($seed);
  193: 	    &Apache::lonnet::setup_random_from_rndseed($rndseed);
  194: 	    @map_ids=&Math::Random::random_permutation(@map_ids);
  195: 	}
  196: 	my $from = shift(@map_ids);
  197: 	my $from_rid = $lpc.'.'.$from;
  198: 	$hash{'map_start_'.$uri} = $from_rid;
  199: 	$hash{'type_'.$from_rid}='start';
  200: 
  201: 	while (my $to = shift(@map_ids)) {
  202: 	    &make_link(++$linkpc,$lpc,$to,$from);
  203: 	    my $to_rid =  $lpc.'.'.$to;
  204: 	    $hash{'type_'.$to_rid}='normal';
  205: 	    $from = $to;
  206: 	    $from_rid = $to_rid;
  207: 	}
  208: 
  209: 	$hash{'map_finish_'.$uri}= $from_rid;
  210: 	$hash{'type_'.$from_rid}='finish';
  211:     }
  212: 
  213:     my $parser = HTML::TokeParser->new(\$instr);
  214:     $parser->attr_encoded(1);
  215:     # last parse out the mapalias params so as to ignore anything
  216:     # refering to non-existant resources
  217:     while (my $token = $parser->get_token) {
  218: 	next if ($token->[0] ne 'S');
  219: 	if ($token->[1] eq 'param') {
  220: 	    &parse_mapalias_param($token,$lpc);
  221: 	} 
  222:     }
  223: }
  224: 
  225: 
  226: # -------------------------------------------------------------------- Resource
  227: sub parse_resource {
  228:     my ($token,$lpc,$ispage,$uri) = @_;
  229:     if ($token->[2]->{'type'} eq 'zombie') { next; }
  230:     my $rid=$lpc.'.'.$token->[2]->{'id'};
  231: 	    
  232:     $hash{'kind_'.$rid}='res';
  233:     $hash{'title_'.$rid}=$token->[2]->{'title'};
  234:     my $turi=&versiontrack($token->[2]->{'src'});
  235:     if ($token->[2]->{'version'}) {
  236: 	unless ($hash{'version_'.$turi}) {
  237: 	    $hash{'version_'.$turi}=$1;
  238: 	}
  239:     }
  240:     my $title=$token->[2]->{'title'};
  241:     $title=~s/\&colon\;/\:/gs;
  242: #   my $symb=&Apache::lonnet::encode_symb($uri,
  243: #					  $token->[2]->{'id'},
  244: #					  $turi);
  245: #   &Apache::lonnet::do_cache_new('title',$symb,$title);
  246:     unless ($ispage) {
  247: 	$turi=~/\.(\w+)$/;
  248: 	my $embstyle=&Apache::loncommon::fileembstyle($1);
  249: 	if ($token->[2]->{'external'} eq 'true') { # external
  250: 	    $turi=~s/^http\:\/\//\/adm\/wrapper\/ext\//;
  251: 	} elsif ($turi=~/^\/*uploaded\//) { # uploaded
  252: 	    if (($embstyle eq 'img') 
  253: 		|| ($embstyle eq 'emb')
  254: 		|| ($embstyle eq 'wrp')) {
  255: 		$turi='/adm/wrapper'.$turi;
  256: 	    } elsif ($embstyle eq 'ssi') {
  257: 		#do nothing with these
  258: 	    } elsif ($turi!~/\.(sequence|page)$/) {
  259: 		$turi='/adm/coursedocs/showdoc'.$turi;
  260: 	    }
  261: 	} elsif ($turi=~/\S/) { # normal non-empty internal resource
  262: 	    my $mapdir=$uri;
  263: 	    $mapdir=~s/[^\/]+$//;
  264: 	    $turi=&Apache::lonnet::hreflocation($mapdir,$turi);
  265: 	    if (($embstyle eq 'img') 
  266: 		|| ($embstyle eq 'emb')
  267: 		|| ($embstyle eq 'wrp')) {
  268: 		$turi='/adm/wrapper'.$turi;
  269: 	    }
  270: 	}
  271:     }
  272: # Store reverse lookup, remove query string
  273:     my $idsuri=$turi;
  274:     $idsuri=~s/\?.+$//;
  275:     if (defined($hash{'ids_'.$idsuri})) {
  276: 	$hash{'ids_'.$idsuri}.=','.$rid;
  277:     } else {
  278: 	$hash{'ids_'.$idsuri}=''.$rid;
  279:     }
  280:     
  281:     if ($turi=~/\/(syllabus|aboutme|navmaps|smppg|bulletinboard)$/) {
  282: 	$turi.='?register=1';
  283:     }
  284:     
  285:     $hash{'src_'.$rid}=$turi;
  286:     
  287:     if ($token->[2]->{'external'} eq 'true') {
  288: 	$hash{'ext_'.$rid}='true:';
  289:     } else {
  290: 	$hash{'ext_'.$rid}='false:';
  291:     }
  292:     if ($token->[2]->{'type'}) {
  293: 	$hash{'type_'.$rid}=$token->[2]->{'type'};
  294: 	if ($token->[2]->{'type'} eq 'start') {
  295: 	    $hash{'map_start_'.$uri}="$rid";
  296: 	}
  297: 	if ($token->[2]->{'type'} eq 'finish') {
  298: 	    $hash{'map_finish_'.$uri}="$rid";
  299: 	}
  300:     }  else {
  301: 	$hash{'type_'.$rid}='normal';
  302:     }
  303:     
  304:     if (($turi=~/\.sequence$/) ||
  305: 	($turi=~/\.page$/)) {
  306: 	$hash{'is_map_'.$rid}=1;
  307: 	&loadmap($turi,$rid);
  308:     } 
  309:     return $token->[2]->{'id'};
  310: }
  311: 
  312: sub make_link {
  313:     my ($linkpc,$lpc,$to,$from,$condition) = @_;
  314:     
  315:     my $linkid=$lpc.'.'.$linkpc;
  316:     my $goesto=$lpc.'.'.$to;
  317:     my $comesfrom=$lpc.'.'.$from;
  318:     my $undercond=0;
  319: 
  320:     if ($condition) {
  321: 	$undercond=$lpc.'.'.$condition;
  322:     }
  323: 
  324:     $hash{'goesto_'.$linkid}=$goesto;
  325:     $hash{'comesfrom_'.$linkid}=$comesfrom;
  326:     $hash{'undercond_'.$linkid}=$undercond;
  327: 
  328:     if (defined($hash{'to_'.$comesfrom})) {
  329: 	$hash{'to_'.$comesfrom}.=','.$linkid;
  330:     } else {
  331: 	$hash{'to_'.$comesfrom}=''.$linkid;
  332:     }
  333:     if (defined($hash{'from_'.$goesto})) {
  334: 	$hash{'from_'.$goesto}.=','.$linkid;
  335:     } else {
  336: 	$hash{'from_'.$goesto}=''.$linkid;
  337:     }
  338: }
  339: 
  340: # ------------------------------------------------------------------- Condition
  341: sub parse_condition {
  342:     my ($token,$lpc) = @_;
  343:     my $rid=$lpc.'.'.$token->[2]->{'id'};
  344:     
  345:     $hash{'kind_'.$rid}='cond';
  346: 
  347:     my $condition = $token->[2]->{'value'};
  348:     $condition =~ s/[\n\r]+/ /gs;
  349:     push(@cond, $condition);
  350:     $hash{'condid_'.$rid}=$#cond;
  351:     if ($token->[2]->{'type'}) {
  352: 	$cond[$#cond].=':'.$token->[2]->{'type'};
  353:     }  else {
  354: 	$cond[$#cond].=':normal';
  355:     }
  356: }
  357: 
  358: # ------------------------------------------------------------------- Parameter
  359: 
  360: sub parse_param {
  361:     my ($token,$lpc) = @_;
  362:     my $referid=$lpc.'.'.$token->[2]->{'to'};
  363:     my $name=$token->[2]->{'name'};
  364:     my $part;
  365:     if ($name=~/^parameter_(.*)_/) {
  366: 	$part=$1;
  367:     } else {
  368: 	$part=0;
  369:     }
  370:     $name=~s/^.*_([^_]*)$/$1/;
  371:     my $newparam=
  372: 	&escape($token->[2]->{'type'}).':'.
  373: 	&escape($part.'.'.$name).'='.
  374: 	&escape($token->[2]->{'value'});
  375:     if (defined($hash{'param_'.$referid})) {
  376: 	$hash{'param_'.$referid}.='&'.$newparam;
  377:     } else {
  378: 	$hash{'param_'.$referid}=''.$newparam;
  379:     }
  380:     if ($token->[2]->{'name'}=~/^parameter_(0_)*randompick$/) {
  381: 	$randompick{$referid}=$token->[2]->{'value'};
  382:     }
  383:     if ($token->[2]->{'name'}=~/^parameter_(0_)*randompickseed$/) {
  384: 	$randompickseed{$referid}=$token->[2]->{'value'};
  385:     }
  386:     if ($token->[2]->{'name'}=~/^parameter_(0_)*randomorder$/) {
  387: 	$randomorder{$referid}=$token->[2]->{'value'};
  388:     }
  389:     if ($token->[2]->{'name'}=~/^parameter_(0_)*encrypturl$/) {
  390: 	if ($token->[2]->{'value'}=~/^yes$/i) {
  391: 	    $encurl{$referid}=1;
  392: 	}
  393:     }
  394:     if ($token->[2]->{'name'}=~/^parameter_(0_)*hiddenresource$/) {
  395: 	if ($token->[2]->{'value'}=~/^yes$/i) {
  396: 	    $hiddenurl{$referid}=1;
  397: 	}
  398:     }
  399: }
  400: 
  401: sub parse_mapalias_param {
  402:     my ($token,$lpc) = @_;
  403:     my $referid=$lpc.'.'.$token->[2]->{'to'};
  404:     return if (!exists($hash{'src_'.$referid}));
  405: 
  406:     if ($token->[2]->{'name'}=~/^parameter_(0_)*mapalias$/) {
  407: 	&count_mapalias($token->[2]->{'value'},$referid);
  408: 	$hash{'mapalias_'.$token->[2]->{'value'}}=$referid;
  409:     }
  410: }
  411: 
  412: # --------------------------------------------------------- Simplify expression
  413: 
  414: sub simplify {
  415:     my $expression=shift;
  416: # (0&1) = 1
  417:     $expression=~s/\(0\&([_\.\d]+)\)/$1/g;
  418: # (8)=8
  419:     $expression=~s/\(([_\.\d]+)\)/$1/g;
  420: # 8&8=8
  421:     $expression=~s/([^_\.\d])([_\.\d]+)\&\2([^_\.\d])/$1$2$3/g;
  422: # 8|8=8
  423:     $expression=~s/([^_\.\d])([_\.\d]+)\|\2([^_\.\d])/$1$2$3/g;
  424: # (5&3)&4=5&3&4
  425:     $expression=~s/\(([_\.\d]+)((?:\&[_\.\d]+)+)\)\&([_\.\d]+[^_\.\d])/$1$2\&$3/g;
  426: # (((5&3)|(4&6)))=((5&3)|(4&6))
  427:     $expression=~
  428: 	s/\((\(\([_\.\d]+(?:\&[_\.\d]+)*\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+\))\)/$1/g;
  429: # ((5&3)|(4&6))|(1&2)=(5&3)|(4&6)|(1&2)
  430:     $expression=~
  431: 	s/\((\([_\.\d]+(?:\&[_\.\d]+)*\))((?:\|\([_\.\d]+(?:\&[_\.\d]+)*\))+)\)\|(\([_\.\d]+(?:\&[_\.\d]+)*\))/\($1$2\|$3\)/g;
  432:     return $expression;
  433: }
  434: 
  435: # -------------------------------------------------------- Build condition hash
  436: 
  437: sub traceroute {
  438:     my ($sofar,$rid,$beenhere,$encflag,$hdnflag)=@_;
  439:     my $newsofar=$sofar=simplify($sofar);
  440:     unless ($beenhere=~/\&\Q$rid\E\&/) {
  441: 	$beenhere.=$rid.'&';  
  442: 	my ($mapid,$resid)=split(/\./,$rid);
  443: 	my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$rid});
  444: 	my $hidden=&Apache::lonnet::EXT('resource.0.hiddenresource',$symb);
  445: 
  446: 	if ($hdnflag || lc($hidden) eq 'yes') {
  447: 	    $hiddenurl{$rid}=1;
  448: 	}
  449: 	if (!$hdnflag && lc($hidden) eq 'no') {
  450: 	    delete($hiddenurl{$rid});
  451: 	}
  452: 
  453: 	my $encrypt=&Apache::lonnet::EXT('resource.0.encrypturl',$symb);
  454: 	if ($encflag || lc($encrypt) eq 'yes') { $encurl{$rid}=1; }
  455: 	if (($retfrid eq '') && ($hash{'src_'.$rid})
  456: 	    && ($hash{'src_'.$rid}!~/\.sequence$/)) {
  457: 	    $retfrid=$rid;
  458: 	}
  459: 	if (defined($hash{'conditions_'.$rid})) {
  460: 	    $hash{'conditions_'.$rid}=simplify(
  461:            '('.$hash{'conditions_'.$rid}.')|('.$sofar.')');
  462: 	} else {
  463: 	    $hash{'conditions_'.$rid}=$sofar;
  464: 	}
  465: 
  466: 	# if the expression is just the 0th condition keep it
  467: 	# otherwise leave a pointer to this condition expression
  468: 	$newsofar = ($sofar eq '0') ? $sofar : '_'.$rid;
  469: 
  470: 	if (defined($hash{'is_map_'.$rid})) {
  471: 	    if (defined($hash{'map_start_'.$hash{'src_'.$rid}})) {
  472: 		$sofar=$newsofar=
  473: 		    &traceroute($sofar,
  474: 				$hash{'map_start_'.$hash{'src_'.$rid}},'&',
  475: 				$encflag || $encurl{$rid},
  476: 				$hdnflag || $hiddenurl{$rid});
  477: 	    }
  478: 	}
  479: 	if (defined($hash{'to_'.$rid})) {
  480: 	    foreach my $id (split(/\,/,$hash{'to_'.$rid})) {
  481: 		my $further=$sofar;
  482:                 if ($hash{'undercond_'.$id}) {
  483: 		    if (defined($hash{'condid_'.$hash{'undercond_'.$id}})) {
  484: 			$further=simplify('('.'_'.$rid.')&('.
  485: 					  $hash{'condid_'.$hash{'undercond_'.$id}}.')');
  486: 		    } else {
  487: 			$errtext.=&mt('<br />Undefined condition ID: [_1]',$hash{'undercond_'.$id});
  488: 		    }
  489:                 }
  490:                 $newsofar=&traceroute($further,$hash{'goesto_'.$id},$beenhere,
  491: 				      $encflag,$hdnflag);
  492: 	    }
  493: 	}
  494:     }
  495:     return $newsofar;
  496: }
  497: 
  498: # ------------------------------ Cascading conditions, quick access, parameters
  499: 
  500: sub accinit {
  501:     my ($uri,$short,$fn)=@_;
  502:     my %acchash=();
  503:     my %captured=();
  504:     my $condcounter=0;
  505:     $acchash{'acc.cond.'.$short.'.0'}=0;
  506:     foreach my $key (keys(%hash)) {
  507: 	if ($key=~/^conditions/) {
  508: 	    my $expr=$hash{$key};
  509: 	    # try to find and factor out common sub-expressions
  510: 	    foreach my $sub ($expr=~m/(\(\([_\.\d]+(?:\&[_\.\d]+)+\)(?:\|\([_\.\d]+(?:\&[_\.\d]+)+\))+\))/g) {
  511: 		my $orig=$sub;
  512: 
  513: 		my ($factor) = ($sub=~/\(\(([_\.\d]+\&(:?[_\.\d]+\&)*)(?:[_\.\d]+\&*)+\)(?:\|\(\1(?:[_\.\d]+\&*)+\))+\)/);
  514: 		next if (!defined($factor));
  515: 
  516: 		$sub=~s/\Q$factor\E//g;
  517: 		$sub=~s/^\(/\($factor\(/;
  518: 		$sub.=')';
  519: 		$sub=simplify($sub);
  520: 		$expr=~s/\Q$orig\E/$sub/;
  521: 	    }
  522: 	    $hash{$key}=$expr;
  523: 	    unless (defined($captured{$expr})) {
  524: 		$condcounter++;
  525: 		$captured{$expr}=$condcounter;
  526: 		$acchash{'acc.cond.'.$short.'.'.$condcounter}=$expr;
  527: 	    } 
  528: 	} elsif ($key=~/^param_(\d+)\.(\d+)/) {
  529: 	    my $prefix=&Apache::lonnet::encode_symb($hash{'map_id_'.$1},$2,
  530: 						    $hash{'src_'.$1.'.'.$2});
  531: 	    foreach my $param (split(/\&/,$hash{$key})) {
  532: 		my ($typename,$value)=split(/\=/,$param);
  533: 		my ($type,$name)=split(/\:/,$typename);
  534: 		$parmhash{$prefix.'.'.&unescape($name)}=
  535: 		    &unescape($value);
  536: 		$parmhash{$prefix.'.'.&unescape($name).'.type'}=
  537: 		    &unescape($type);
  538: 	    }
  539: 	}
  540:     }
  541:     foreach my $key (keys(%hash)) {
  542: 	if ($key=~/^ids/) {
  543: 	    foreach my $resid (split(/\,/,$hash{$key})) {
  544: 		my $uri=$hash{'src_'.$resid};
  545: 		my ($uripath,$urifile) =
  546: 		    &Apache::lonnet::split_uri_for_cond($uri);
  547: 		if ($uripath) {
  548: 		    my $uricond='0';
  549: 		    if (defined($hash{'conditions_'.$resid})) {
  550: 			$uricond=$captured{$hash{'conditions_'.$resid}};
  551: 		    }
  552: 		    if (defined($acchash{'acc.res.'.$short.'.'.$uripath})) {
  553: 			if ($acchash{'acc.res.'.$short.'.'.$uripath}=~
  554: 			    /(\&\Q$urifile\E\:[^\&]*)/) {
  555: 			    my $replace=$1;
  556: 			    my $regexp=$replace;
  557: 			    #$regexp=~s/\|/\\\|/g;
  558: 			    $acchash{'acc.res.'.$short.'.'.$uripath} =~
  559: 				s/\Q$regexp\E/$replace\|$uricond/;
  560: 			} else {
  561: 			    $acchash{'acc.res.'.$short.'.'.$uripath}.=
  562: 				$urifile.':'.$uricond.'&';
  563: 			}
  564: 		    } else {
  565: 			$acchash{'acc.res.'.$short.'.'.$uripath}=
  566: 			    '&'.$urifile.':'.$uricond.'&';
  567: 		    }
  568: 		} 
  569: 	    }
  570: 	}
  571:     }
  572:     $acchash{'acc.res.'.$short.'.'}='&:0&';
  573:     my $courseuri=$uri;
  574:     $courseuri=~s/^\/res\///;
  575:     &Apache::lonnet::delenv('(acc\.|httpref\.)');
  576:     &Apache::lonnet::appenv(%acchash);
  577: }
  578: 
  579: # ---------------- Selectively delete from randompick maps and hidden url parms
  580: 
  581: sub hiddenurls {
  582:     my $randomoutentry='';
  583:     foreach my $rid (keys %randompick) {
  584:         my $rndpick=$randompick{$rid};
  585:         my $mpc=$hash{'map_pc_'.$hash{'src_'.$rid}};
  586: # ------------------------------------------- put existing resources into array
  587:         my @currentrids=();
  588:         foreach my $key (sort(keys(%hash))) {
  589: 	    if ($key=~/^src_($mpc\.\d+)/) {
  590: 		if ($hash{'src_'.$1}) { push @currentrids, $1; }
  591:             }
  592:         }
  593: 	# rids are number.number and we want to numercially sort on 
  594:         # the second number
  595: 	@currentrids=sort {
  596: 	    my (undef,$aid)=split(/\./,$a);
  597: 	    my (undef,$bid)=split(/\./,$b);
  598: 	    $aid <=> $bid;
  599: 	} @currentrids;
  600:         next if ($#currentrids<$rndpick);
  601: # -------------------------------- randomly eliminate the ones that should stay
  602: 	my (undef,$id)=split(/\./,$rid);
  603:         if ($randompickseed{$rid}) { $id=$randompickseed{$rid}; }
  604: 	my $rndseed=&Apache::lonnet::rndseed($id); # use id instead of symb
  605: 	&Apache::lonnet::setup_random_from_rndseed($rndseed);
  606: 	my @whichids=&Math::Random::random_permuted_index($#currentrids+1);
  607:         for (my $i=1;$i<=$rndpick;$i++) { $currentrids[$whichids[$i]]=''; }
  608: 	#&Apache::lonnet::logthis("$id,$rndseed,".join(':',@whichids));
  609: # -------------------------------------------------------- delete the leftovers
  610:         for (my $k=0; $k<=$#currentrids; $k++) {
  611:             if ($currentrids[$k]) {
  612: 		$hash{'randomout_'.$currentrids[$k]}=1;
  613:                 my ($mapid,$resid)=split(/\./,$currentrids[$k]);
  614:                 $randomoutentry.='&'.
  615: 		    &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},
  616: 						 $resid,
  617: 						 $hash{'src_'.$currentrids[$k]}
  618: 						 ).'&';
  619:             }
  620:         }
  621:     }
  622: # ------------------------------ take care of explicitly hidden urls or folders
  623:     foreach my $rid (keys %hiddenurl) {
  624: 	$hash{'randomout_'.$rid}=1;
  625: 	my ($mapid,$resid)=split(/\./,$rid);
  626: 	$randomoutentry.='&'.
  627: 	    &Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,
  628: 					 $hash{'src_'.$rid}).'&';
  629:     }
  630: # --------------------------------------- append randomout entry to environment
  631:     if ($randomoutentry) {
  632: 	&Apache::lonnet::appenv('acc.randomout' => $randomoutentry);
  633:     }
  634: }
  635: 
  636: # ---------------------------------------------------- Read map and all submaps
  637: 
  638: sub readmap {
  639:     my $short=shift;
  640:     $short=~s/^\///;
  641:     my %cenv=&Apache::lonnet::coursedescription($short,{'freshen_cache'=>1});
  642:     my $fn=$cenv{'fn'};
  643:     my $uri;
  644:     $short=~s/\//\_/g;
  645:     unless ($uri=$cenv{'url'}) { 
  646: 	&Apache::lonnet::logthis("<font color=blue>WARNING: ".
  647: 				 "Could not load course $short.</font>"); 
  648: 	return ('',&mt('No course data available.'));;
  649:     }
  650:     @cond=('true:normal');
  651: 
  652:     open(LOCKFILE,">$fn.db.lock");
  653:     my $lock=0;
  654:     if (flock(LOCKFILE,LOCK_EX|LOCK_NB)) {
  655: 	$lock=1;
  656: 	unlink($fn.'.db');
  657: 	unlink($fn.'_symb.db');
  658: 	unlink($fn.'.state');
  659: 	unlink($fn.'parms.db');
  660:     }
  661:     undef %randompick;
  662:     undef %hiddenurl;
  663:     undef %encurl;
  664:     $retfrid='';
  665:     if ($lock && (tie(%hash,'GDBM_File',"$fn.db",&GDBM_WRCREAT(),0640)) &&
  666: 	(tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_WRCREAT(),0640))) {
  667: 	%hash=();
  668: 	%parmhash=();
  669: 	$errtext='';
  670: 	$pc=0;
  671: 	&clear_mapalias_count();
  672: 	&processversionfile(%cenv);
  673: 	my $furi=&Apache::lonnet::clutter($uri);
  674: 	$hash{'src_0.0'}=&versiontrack($furi);
  675: 	$hash{'title_0.0'}=&Apache::lonnet::metadata($uri,'title');
  676: 	$hash{'ids_'.$furi}='0.0';
  677: 	$hash{'is_map_0.0'}=1;
  678: 	loadmap($uri,'0.0');
  679: 	if (defined($hash{'map_start_'.$uri})) {
  680: 	    &Apache::lonnet::appenv("request.course.id"  => $short,
  681: 				    "request.course.fn"  => $fn,
  682: 				    "request.course.uri" => $uri);
  683: 	    $env{'request.course.id'}=$short;
  684: 	    &traceroute('0',$hash{'map_start_'.$uri},'&');
  685: 	    &accinit($uri,$short,$fn);
  686: 	    &hiddenurls();
  687: 	}
  688: 	$errtext .= &get_mapalias_errors();
  689: # ------------------------------------------------------- Put versions into src
  690: 	foreach my $key (keys(%hash)) {
  691: 	    if ($key=~/^src_/) {
  692: 		$hash{$key}=&putinversion($hash{$key});
  693: 	    } elsif ($key =~ /^(map_(?:start|finish|pc)_)(.*)/) {
  694: 		my ($type, $url) = ($1,$2);
  695: 		my $value = $hash{$key};
  696: 		$hash{$type.&putinversion($url)}=$value;
  697: 	    }
  698: 	}
  699: # ---------------------------------------------------------------- Encrypt URLs
  700: 	foreach my $id (keys(%encurl)) {
  701: #	    $hash{'src_'.$id}=&Apache::lonenc::encrypted($hash{'src_'.$id});
  702: 	    $hash{'encrypted_'.$id}=1;
  703: 	}
  704: # ----------------------------------------------- Close hashes to finally store
  705: # --------------------------------- Routine must pass this point, no early outs
  706: 	$hash{'first_rid'}=$retfrid;
  707: 	my ($mapid,$resid)=split(/\./,$retfrid);
  708: 	$hash{'first_mapurl'}=$hash{'map_id_'.$mapid};
  709: 	my $symb=&Apache::lonnet::encode_symb($hash{'map_id_'.$mapid},$resid,$hash{'src_'.$retfrid});
  710: 	$retfurl=&add_get_param($hash{'src_'.$retfrid},{ 'symb' => $symb });
  711: 	if ($hash{'encrypted_'.$retfrid}) {
  712: 	    $retfurl=&Apache::lonenc::encrypted($retfurl,(&Apache::lonnet::allowed('adv') ne 'F'));
  713: 	}
  714: 	$hash{'first_url'}=$retfurl;
  715: 	unless ((untie(%hash)) && (untie(%parmhash))) {
  716: 	    &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  717: 				     "Could not untie coursemap $fn for $uri.</font>"); 
  718: 	}
  719: # ---------------------------------------------------- Store away initial state
  720: 	{
  721: 	    my $cfh;
  722: 	    if (open($cfh,">$fn.state")) {
  723: 		print $cfh join("\n",@cond);
  724: 	    } else {
  725: 		&Apache::lonnet::logthis("<font color=blue>WARNING: ".
  726: 					 "Could not write statemap $fn for $uri.</font>"); 
  727: 	    }
  728: 	}
  729: 	flock(LOCKFILE,LOCK_UN);
  730: 	close(LOCKFILE);
  731:     } else {
  732: 	# if we are here it is likely because we are already trying to 
  733: 	# initialize the course in another child, busy wait trying to 
  734: 	# tie the hashes for the next 90 seconds, if we succeed forward 
  735: 	# them on to navmaps, if we fail, throw up the Could not init 
  736: 	# course screen
  737: 	if ($lock) {
  738: 	    # Got the lock but not the DB files
  739: 	    flock(LOCKFILE,LOCK_UN);
  740: 	}
  741: 	untie(%hash);
  742: 	untie(%parmhash);
  743: 	&Apache::lonnet::logthis("<font color=blue>WARNING: ".
  744: 				 "Could not tie coursemap $fn for $uri.</font>"); 
  745: 	my $i=0;
  746: 	while($i<90) {
  747: 	    $i++;
  748: 	    sleep(1);
  749: 	    if (flock(LOCKFILE,LOCK_EX|LOCK_NB) &&
  750: 		(tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640))) {
  751: 		if (tie(%parmhash,'GDBM_File',$fn.'_parms.db',&GDBM_READER(),0640)) {
  752: 		    $retfurl='/adm/navmaps';
  753: 		    &Apache::lonnet::appenv("request.course.id"  => $short,
  754: 					    "request.course.fn"  => $fn,
  755: 					    "request.course.uri" => $uri);
  756: 		    untie(%hash);
  757: 		    untie(%parmhash);
  758: 		    last;
  759: 		}
  760: 	    }
  761: 	    untie(%hash);
  762: 	    untie(%parmhash);
  763: 	}
  764: 	flock(LOCKFILE,LOCK_UN);
  765: 	close(LOCKFILE);
  766:     }
  767:     &Apache::lonmsg::author_res_msg($env{'request.course.uri'},$errtext);
  768: # ------------------------------------------------- Check for critical messages
  769: 
  770:     my @what=&Apache::lonnet::dump('critical',$env{'user.domain'},
  771: 				   $env{'user.name'});
  772:     if ($what[0]) {
  773: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
  774: 	    $retfurl='/adm/email?critical=display';
  775:         }
  776:     }
  777:     return ($retfurl,$errtext);
  778: }
  779: 
  780: # ------------------------------------------------------- Evaluate state string
  781: 
  782: sub evalstate {
  783:     my $fn=$env{'request.course.fn'}.'.state';
  784:     my $state='';
  785:     if (-e $fn) {
  786: 	my @conditions=();
  787: 	{
  788: 	    open(my $fh,"<$fn");
  789: 	    @conditions=<$fh>;
  790:             close($fh);
  791: 	}  
  792: 	my $safeeval = new Safe;
  793: 	my $safehole = new Safe::Hole;
  794: 	$safeeval->permit("entereval");
  795: 	$safeeval->permit(":base_math");
  796: 	$safeeval->deny(":base_io");
  797: 	$safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  798: 	foreach my $line (@conditions) {
  799: 	    chomp($line);
  800: 	    my ($condition,$weight)=split(/\:/,$line);
  801: 	    if ($safeeval->reval($condition)) {
  802: 		if ($weight eq 'force') {
  803: 		    $state.='3';
  804: 		} else {
  805: 		    $state.='2';
  806: 		}
  807: 	    } else {
  808: 		if ($weight eq 'stop') {
  809: 		    $state.='0';
  810: 		} else {
  811: 		    $state.='1';
  812: 		}
  813: 	    }
  814: 	}
  815:     }
  816:     &Apache::lonnet::appenv('user.state.'.$env{'request.course.id'} => $state);
  817:     return $state;
  818: }
  819: 
  820: {
  821:     my %mapalias_cache;
  822:     sub count_mapalias {
  823: 	my ($value,$resid) = @_;
  824:  	push(@{ $mapalias_cache{$value} }, $resid);
  825:     }
  826: 
  827:     sub get_mapalias_errors {
  828: 	my $error_text;
  829: 	foreach my $mapalias (sort(keys(%mapalias_cache))) {
  830: 	    next if (scalar(@{ $mapalias_cache{$mapalias} } ) == 1);
  831: 	    my $count;
  832: 	    my $which =
  833: 		join('</li><li>', 
  834: 		     map {
  835: 			 my $id = $_;
  836: 			 if (exists($hash{'src_'.$id})) {
  837: 			     $count++;
  838: 			 }
  839: 			 my ($mapid) = split(/\./,$id);
  840:                          &mt('Resource "[_1]" <br /> in Map "[_2]"',
  841: 			     $hash{'title_'.$id},
  842: 			     $hash{'title_'.$hash{'ids_'.$hash{'map_id_'.$mapid}}});
  843: 		     } (@{ $mapalias_cache{$mapalias} }));
  844: 	    next if ($count < 2);
  845: 	    $error_text .= '<div class="LC_error">'.
  846: 		&mt('Error: Found the mapalias "[_1]" defined multiple times.',
  847: 		    $mapalias).
  848: 		'</div><ul><li>'.$which.'</li></ul>';
  849: 	}
  850: 	&clear_mapalias_count();
  851: 	return $error_text;
  852:     }
  853:     sub clear_mapalias_count {
  854: 	undef(%mapalias_cache);
  855:     }
  856: }
  857: 1;
  858: __END__
  859: 
  860: =head1 NAME
  861: 
  862: Apache::lonuserstate - Construct and maintain state and binary representation
  863: of course for user
  864: 
  865: =head1 SYNOPSIS
  866: 
  867: Invoked by lonroles.pm.
  868: 
  869: &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
  870: 
  871: =head1 INTRODUCTION
  872: 
  873: This module constructs and maintains state and binary representation
  874: of course for user.
  875: 
  876: This is part of the LearningOnline Network with CAPA project
  877: described at http://www.lon-capa.org.
  878: 
  879: =head1 HANDLER SUBROUTINE
  880: 
  881: There is no handler subroutine.
  882: 
  883: =head1 OTHER SUBROUTINES
  884: 
  885: =over 4
  886: 
  887: =item *
  888: 
  889: loadmap() : Loads map from disk
  890: 
  891: =item *
  892: 
  893: simplify() : Simplify expression
  894: 
  895: =item *
  896: 
  897: traceroute() : Build condition hash
  898: 
  899: =item *
  900: 
  901: accinit() : Cascading conditions, quick access, parameters
  902: 
  903: =item *
  904: 
  905: readmap() : Read map and all submaps
  906: 
  907: =item *
  908: 
  909: evalstate() : Evaluate state string
  910: 
  911: =back
  912: 
  913: =cut

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