File:  [LON-CAPA] / rat / lonuserstate.pm
Revision 1.120: download - view: text, annotated - select for diffs
Tue Aug 28 01:06:15 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- xhtml
- protect the rig in the regexp

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

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