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