Annotation of rat/lonuserstate.pm, revision 1.118.2.2

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

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