1: # The LearningOnline Network with CAPA
2: # Navigate Maps Handler
3: #
4: # $Id: lonnavmaps.pm,v 1.58 2002/10/01 07:20:31 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: # (Page Handler
29: #
30: # (TeX Content Handler
31: #
32: # 05/29/00,05/30 Gerd Kortemeyer)
33: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
34: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
35: #
36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
37: # YEAR=2002
38: # 1/1 Gerd Kortemeyer
39: #
40:
41: package Apache::lonnavmaps;
42:
43: use strict;
44: use Apache::Constants qw(:common :http);
45: use Apache::lonnet();
46: use Apache::loncommon();
47: use HTML::TokeParser;
48: use GDBM_File;
49:
50: # -------------------------------------------------------------- Module Globals
51: my %hash;
52: my @rows;
53:
54: #
55: # These cache hashes need to be independent of user, resource and course
56: # (user and course can/should be in the keys)
57: #
58:
59: my %courserdatas;
60: my %userrdatas;
61:
62: #
63: # These global hashes are dependent on user, course and resource,
64: # and need to be initialized every time when a sheet is calculated
65: #
66: my %courseopt;
67: my %useropt;
68: my %parmhash;
69:
70: # This parameter keeps track of whether obtaining the user's information
71: # failed, which the colorizer in astatus can use
72: my $networkFailedFlag = 0;
73:
74: # ------------------------------------------------------------------ Euclid gcd
75:
76: sub euclid {
77: my ($e,$f)=@_;
78: my $a; my $b; my $r;
79: if ($e>$f) { $b=$e; $r=$f; } else { $r=$e; $b=$f; }
80: while ($r!=0) {
81: $a=$b; $b=$r;
82: $r=$a%$b;
83: }
84: return $b;
85: }
86:
87: # --------------------------------------------------------------------- Parmval
88:
89: # -------------------------------------------- Figure out a cascading parameter
90: #
91: # For this function to work
92: #
93: # * parmhash needs to be tied
94: # * courseopt and useropt need to be initialized for this user and course
95: #
96:
97: sub parmval {
98: my ($what,$symb)=@_;
99: my $cid=$ENV{'request.course.id'};
100: my $csec=$ENV{'request.course.sec'};
101: my $uname=$ENV{'user.name'};
102: my $udom=$ENV{'user.domain'};
103:
104: unless ($symb) { return ''; }
105: my $result='';
106:
107: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
108:
109: # ----------------------------------------------------- Cascading lookup scheme
110: my $rwhat=$what;
111: $what=~s/^parameter\_//;
112: $what=~s/\_/\./;
113:
114: my $symbparm=$symb.'.'.$what;
115: my $mapparm=$mapname.'___(all).'.$what;
116: my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
117:
118: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
119: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
120: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
121:
122: my $courselevel= $usercourseprefix.'.'.$what;
123: my $courselevelr=$usercourseprefix.'.'.$symbparm;
124: my $courselevelm=$usercourseprefix.'.'.$mapparm;
125:
126: # ---------------------------------------------------------- first, check user
127: if (defined($uname)) {
128: if (defined($useropt{$courselevelr})) { return $useropt{$courselevelr}; }
129: if (defined($useropt{$courselevelm})) { return $useropt{$courselevelm}; }
130: if (defined($useropt{$courselevel})) { return $useropt{$courselevel}; }
131: }
132:
133: # ------------------------------------------------------- second, check course
134: if (defined($csec)) {
135: if (defined($courseopt{$seclevelr})) { return $courseopt{$seclevelr}; }
136: if (defined($courseopt{$seclevelm})) { return $courseopt{$seclevelm}; }
137: if (defined($courseopt{$seclevel})) { return $courseopt{$seclevel}; }
138: }
139:
140: if (defined($courseopt{$courselevelr})) { return $courseopt{$courselevelr}; }
141: if (defined($courseopt{$courselevelm})) { return $courseopt{$courselevelm}; }
142: if (defined($courseopt{$courselevel})) { return $courseopt{$courselevel}; }
143:
144: # ----------------------------------------------------- third, check map parms
145:
146: my $thisparm=$parmhash{$symbparm};
147: if (defined($thisparm)) { return $thisparm; }
148:
149: # ----------------------------------------------------- fourth , check default
150:
151: my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
152: if (defined($default)) { return $default}
153:
154: # --------------------------------------------------- fifth , cascade up parts
155:
156: my ($space,@qualifier)=split(/\./,$rwhat);
157: my $qualifier=join('.',@qualifier);
158: unless ($space eq '0') {
159: my ($part,$id)=split(/\_/,$space);
160: if ($id) {
161: my $partgeneral=&parmval($part.".$qualifier",$symb);
162: if (defined($partgeneral)) { return $partgeneral; }
163: } else {
164: my $resourcegeneral=&parmval("0.$qualifier",$symb);
165: if (defined($resourcegeneral)) { return $resourcegeneral; }
166: }
167: }
168: return '';
169: }
170:
171:
172:
173: # ------------------------------------------------------------- Find out status
174: # return codes
175: # tcode (timecode)
176: # 1: will open later
177: # 2: is open and not past due yet
178: # 3: is past due date
179: # 4: due in the next 24 hours
180: #
181: # code (curent solved status)
182: # 1: not attempted
183: # 2: attempted but wrong, or incorrect by instructor
184: # 3: solved or correct by instructor
185: # 4: partially correct (one or more parts correct)
186: # "excused" needs to be supported, but is not yet.
187: sub astatus {
188: my $rid=shift;
189: my $code=0;
190: my $ctext='';
191: $rid=~/(\d+)\.(\d+)/;
192: my $symb=&Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.
193: &Apache::lonnet::declutter($hash{'src_'.$rid});
194: my %duedate=();
195: my %opendate=();
196: my %answerdate=();
197: # need to always check part 0's open/due/answer status
198: foreach (sort(split(/\,/,&Apache::lonnet::metadata($hash{'src_'.$rid},'allpo\ssiblekeys')))) {
199: if ($_=~/^parameter\_(.*)\_opendate$/) {
200: my $part=$1;
201: $duedate{$part}=&parmval($part.'.duedate',$symb);
202: $opendate{$part}=&parmval($part.'.opendate',$symb);
203: $answerdate{$part}=&parmval($part.'.answerdate',$symb);
204: if (&parmval($part.'.opendate.type',$symb) eq 'date_interval') {
205: $opendate{$part}=$duedate{$part}-$opendate{$part};
206: }
207: if (&parmval($part.'.answerdate.type',$symb) eq 'date_interval') {
208: $answerdate{$part}=$duedate{$part}+$answerdate{$part};
209: }
210: }
211: }
212: my $now=time;
213: my $tcode=0;
214:
215: my %returnhash=&Apache::lonnet::restore($symb);
216:
217: foreach (sort(keys(%opendate))) {
218: my $duedate=$duedate{$_};
219: my $opendate=$opendate{$_};
220: my $answerdate=$answerdate{$_};
221: my $preface='';
222: unless ($_ eq '0') { $preface=' Part: '.$_.' '; }
223: if ($opendate) {
224: if ($now<$duedate || (!$duedate)) {
225: unless ($tcode==4) { $tcode=2; }
226: if ($duedate) {
227: $ctext.=$preface.'Due: '.localtime($duedate);
228: } else {
229: $ctext.=$preface.'No Due Date';
230: }
231: if ($now<$opendate) {
232: unless ($tcode) { $tcode=1; }
233: $ctext.=$preface.'Open: '.localtime($opendate);
234: }
235: if ($duedate && $duedate-$now<86400) {
236: $tcode=4;
237: $ctext.=$preface.'Due: '.localtime($duedate);
238: }
239: } else {
240: unless (($tcode==4) || ($tcode eq 2)) { $tcode=3; }
241: if ($now<$answerdate) {
242: $ctext.='Answer: '.localtime($duedate);
243: }
244: }
245: } else {
246: unless (($tcode==2) || ($tcode==4)) { $tcode=1; }
247: }
248:
249: my $status=$returnhash{'resource.'.$_.'.solved'};
250:
251: if ($status eq 'correct_by_student') {
252: if ($code==0||$code==3) { $code=3; } else { $code=4; }
253: $ctext.=' solved';
254: } elsif ($status eq 'correct_by_override') {
255: if ($code==0||$code==3) { $code=3; } else { $code=4; }
256: $ctext.=' override';
257: } elsif ($status eq 'incorrect_attempted') {
258: if ($code!=4 && $code!=3) { $code=2; }
259: if ($code==3) { $code=4; }
260: $ctext.=' ('.
261: ($returnhash{'resource.'.$_.'.tries'}?
262: $returnhash{'resource.'.$_.'.tries'}:'0');
263: my $numtries = &parmval($_.'.maxtries',$symb);
264: if ($numtries) { $ctext.='/'.$numtries.' tries'; }
265: $ctext.=')';
266: } elsif ($status eq 'incorrect_by_override') {
267: if ($code!=4 && $code!=3) { $code=2; }
268: if ($code==3) { $code=4; }
269: $ctext.=' override';
270: } elsif ($status eq 'excused') {
271: if ($code==0||$code==3) { $code=3; } else { $code=4; }
272: $ctext.=' excused';
273: } else {
274: if ($code==0) { $code=1; }
275: }
276: }
277:
278: return 'p'.$code.$tcode.'"'.$ctext.'"';
279: }
280:
281:
282: sub addresource {
283: my ($resource,$sofar,$rid,$showtypes,$indent,$linkid)=@_;
284: if ($showtypes eq 'problems') {
285: if ($resource!~/\.(problem|exam|quiz|assess|survey|form)$/) {
286: return;
287: }
288: }
289: my $brepriv=&Apache::lonnet::allowed('bre',$resource);
290: if ($hash{'src_'.$rid}) {
291: if (($brepriv eq '2') || ($brepriv eq 'F')) {
292: my $pprefix='';
293: if ($resource=~/\.(problem|exam|quiz|assess|survey|form)$/) {
294: $pprefix=&astatus($rid);
295: }
296: $$sofar++;
297: if ($indent) { $pprefix='i'.$indent.','.$pprefix; }
298: if ($linkid) { $pprefix='l'.$linkid.','.$pprefix; }
299: if (defined($rows[$$sofar])) {
300: $rows[$$sofar].='&'.$pprefix.$rid;
301: } else {
302: $rows[$$sofar]=$pprefix.$rid;
303: }
304: }
305: }
306: }
307:
308: sub followlinks () {
309: my ($rid,$sofar,$beenhere,$further,$showtypes,$indent,$linkid)=@_;
310: my $mincond=1;
311: my $next='';
312: foreach (split(/\,/,$hash{'to_'.$rid})) {
313: my $thiscond=
314: &Apache::lonnet::directcondval($hash{'condid_'.$hash{'undercond_'.$_}});
315: if ($thiscond>=$mincond) {
316: if ($next) {
317: $next.=','.$_.':'.$thiscond;
318: } else {
319: $next=$_.':'.$thiscond;
320: }
321: if ($thiscond>$mincond) { $mincond=$thiscond; }
322: }
323: }
324: my $col=0;
325: &Apache::lonxml::debug("following links -$next-");
326: foreach (split(/\,/,$next)) {
327: my ($nextlinkid,$condval)=split(/\:/,$_);
328: if ($condval>=$mincond) {
329: my $now=&tracetable($sofar,$hash{'goesto_'.$nextlinkid},
330: $beenhere,$showtypes,$indent,$linkid);
331: if ($now>$further) {
332: if ($col>0) {
333: my $string;
334: for(my $i=0;$i<$col;$i++) { $string.='&'; }
335: for(my $i=$further+1;$now-1>$i;$i++) {
336: $rows[$i]=$string.$rows[$i];
337: }
338: }
339: $further=$now;
340: }
341: }
342: $col++;
343: }
344: return $further;
345: }
346: # ------------------------------------------------------------ Build page table
347:
348: sub tracetable {
349: my ($sofar,$rid,$beenhere,$showtypes,$indent,$linkid)=@_;
350: my $newshowtypes=$showtypes;
351: my $further=$sofar;
352: # $Apache::lonxml::debug=1;
353: &Apache::lonxml::debug("$rid ; $linkid ; $sofar ; $beenhere ; ".$hash{'src_'.$rid});
354: if ($beenhere=~/\&$rid\&/) { return $further; }
355: $beenhere.=$rid.'&';
356:
357: if (defined($hash{'is_map_'.$rid})) {
358: $sofar++;
359: my $tprefix='';
360: if ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
361: eq 'sequence') {
362: $tprefix='h';
363: } elsif ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
364: eq 'page') {
365: $tprefix='j';
366: if ($indent) { $tprefix='i'.$indent.','.$tprefix; }
367: if ($linkid) { $tprefix='l'.$linkid.','.$tprefix; }
368: $newshowtypes='problems';
369: $indent++;
370: #if in a .page continue to link the encompising .page
371: if (!$linkid) { $linkid=$rid; }
372: }
373: if (defined($rows[$sofar])) {
374: $rows[$sofar].='&'.$tprefix.$rid;
375: } else {
376: $rows[$sofar]=$tprefix.$rid;
377: }
378: if ((defined($hash{'map_start_'.$hash{'src_'.$rid}})) &&
379: (defined($hash{'map_finish_'.$hash{'src_'.$rid}}))) {
380: my $frid=$hash{'map_finish_'.$hash{'src_'.$rid}};
381: $sofar=&tracetable($sofar,$hash{'map_start_'.$hash{'src_'.$rid}},
382: '&'.$frid.'&',$newshowtypes,$indent,$linkid);
383: &addresource($hash{'src_'.$frid},\$sofar,$frid,$newshowtypes,
384: $indent,$linkid);
385: if ($tprefix =~ /j$/) { $indent--; $linkid=''; }
386: }
387: } else {
388: &addresource($hash{'src_'.$rid},\$sofar,$rid,$showtypes,
389: $indent,$linkid);
390: }
391:
392: if (defined($hash{'to_'.$rid})) {
393: $further=&followlinks($rid,$sofar,$beenhere,$further,$showtypes,
394: $indent,$linkid);
395: }
396:
397: return $further;
398: }
399:
400: # ================================================================ Main Handler
401:
402: sub handler {
403: my $r=shift;
404:
405: &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
406:
407: if ($ENV{'form.jtest'} ne "1")
408: {
409: return new_handle($r);
410: }
411:
412: # ------------------------------------------- Set document type for header only
413:
414: if ($r->header_only) {
415: if ($ENV{'browser.mathml'}) {
416: $r->content_type('text/xml');
417: } else {
418: $r->content_type('text/html');
419: }
420: $r->send_http_header;
421: return OK;
422: }
423: my $requrl=$r->uri;
424: my $hashtied;
425: # ----------------------------------------------------------------- Tie db file
426: my $fn;
427: if ($ENV{'request.course.fn'}) {
428: $fn=$ENV{'request.course.fn'};
429: if (-e "$fn.db") {
430: if ((tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) &&
431: (tie(%parmhash,'GDBM_File',
432: $ENV{'request.course.fn'}.'_parms.db',
433: &GDBM_READER(),0640))) {
434: $hashtied=1;
435: }
436: }
437: }
438: if (!$hashtied) {
439: $ENV{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
440: return HTTP_NOT_ACCEPTABLE;
441: }
442:
443: # ------------------------------------------------------------------- Hash tied
444:
445: if ($ENV{'browser.mathml'}) {
446: $r->content_type('text/xml');
447: } else {
448: $r->content_type('text/html');
449: }
450: &Apache::loncommon::no_cache($r);
451: $r->send_http_header;
452:
453: my $firstres=$hash{'map_start_'.
454: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
455: my $lastres=$hash{'map_finish_'.
456: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
457: if (!(($firstres) && ($lastres))) {
458: $r->print('<html><body>Coursemap undefined.</body></html>');
459: } else {
460:
461: # ----------------------------------------------------------------- Render page
462: # -------------------------------------------------------------- Set parameters
463:
464:
465: # ---------------------------- initialize coursedata and userdata for this user
466: undef %courseopt;
467: undef %useropt;
468:
469: my $uname=$ENV{'user.name'};
470: my $udom=$ENV{'user.domain'};
471: my $uhome=$ENV{'user.home'};
472: my $cid=$ENV{'request.course.id'};
473: my $chome=$ENV{'course.'.$cid.'.home'};
474: my ($cdom,$cnum)=split(/\_/,$cid);
475:
476: my $userprefix=$uname.'_'.$udom.'_';
477:
478: unless ($uhome eq 'no_host') {
479: # ------------------------------------------------- Get coursedata (if present)
480: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
481: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
482: ':resourcedata',$chome);
483: if ($reply!~/^error\:/) {
484: $courserdatas{$cid}=$reply;
485: $courserdatas{$cid.'.last_cache'}=time;
486: }
487: # check to see if network failed
488: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
489: {
490: $networkFailedFlag = 1;
491: }
492: }
493: foreach (split(/\&/,$courserdatas{$cid})) {
494: my ($name,$value)=split(/\=/,$_);
495: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
496: &Apache::lonnet::unescape($value);
497: }
498: # --------------------------------------------------- Get userdata (if present)
499: unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
500: my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
501: if ($reply!~/^error\:/) {
502: $userrdatas{$uname.'___'.$udom}=$reply;
503: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
504: }
505: }
506: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
507: my ($name,$value)=split(/\=/,$_);
508: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
509: &Apache::lonnet::unescape($value);
510: }
511: }
512:
513: @rows=();
514:
515: &tracetable(0,$firstres,'&','',0);
516:
517: # ------------------------------------------------------------------ Page parms
518:
519: my $j;
520: my $i;
521: my $lcm=1;
522: my $contents=0;
523:
524: # ---------------------------------------------- Go through table to get layout
525:
526: for ($i=0;$i<=$#rows;$i++) {
527: if ($rows[$i]) {
528: &Apache::lonxml::debug("Row $i is:".$rows[$i]);
529: $contents++;
530: my @colcont=split(/\&/,$rows[$i]);
531: $lcm*=($#colcont+1)/euclid($lcm,($#colcont+1));
532: }
533: }
534:
535:
536: unless ($contents) {
537: $r->print('<html><body>Empty Map.</body></html>');
538: } else {
539:
540: # ------------------------------------------------------------------ Build page
541:
542: my $currenturl=$ENV{'form.postdata'};
543: $currenturl=~s/^http\:\/\///;
544: $currenturl=~s/^[^\/]+//;
545:
546: # ---------------------------------------------------------------- Send headers
547:
548: my $date=localtime;
549: my $now=time;
550: # ----------------------------------------- Get email status and discussiontime
551:
552: my %emailstatus=&Apache::lonnet::dump('email_status');
553: my $logouttime=$emailstatus{'logout'};
554: my $courseleave=$emailstatus{'logout_'.$ENV{'request.course.id'}};
555: my $lastcheck=($courseleave>$logouttime?$courseleave:$logouttime);
556:
557: my %discussiontimes=&Apache::lonnet::dump('discussiontimes',
558: $cdom,$cnum);
559:
560: my %feedback=();
561: my %error=();
562: foreach my $msgid (split(/\&/,&Apache::lonnet::reply('keys:'.
563: $ENV{'user.domain'}.':'.
564: $ENV{'user.name'}.':nohist_email',
565: $ENV{'user.home'}))) {
566: $msgid=&Apache::lonnet::unescape($msgid);
567: my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
568: if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
569: my ($what,$url)=($1,$2);
570: my %status=
571: &Apache::lonnet::get('email_status',[$msgid]);
572: if ($status{$msgid}=~/^error\:/) {
573: $status{$msgid}='';
574: }
575:
576: if (($status{$msgid} eq 'new') ||
577: (!$status{$msgid})) {
578: if ($what eq 'Error') {
579: $error{$url}.=','.$msgid;
580: } else {
581: $feedback{$url}.=','.$msgid;
582: }
583: }
584: }
585: }
586: # ----------------------------------------------------------- Start Page Output
587: my $bodytagadd='';
588: $r->print(
589: '<html><head><title>Navigate Course Map</title></head>');
590: if (($currenturl=~/^\/res/) &&
591: ($currenturl!~/^\/res\/adm/)) {
592: $bodytagadd='onLoad="window.location.hash='."'curloc'".'"';
593: }
594: $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
595: $bodytagadd));
596: $r->print('<script>window.focus();</script>');
597: my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
598: if (defined($desc)) { $r->print("<h2>$desc</h2>\n"); }
599: $r->print("<h3>$date</h3>\n");
600: $r->rflush();
601: $r->print('<img src="/adm/lonMisc/chat.gif"> New discussion since '.
602: localtime($lastcheck).
603: '<br><img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>');
604: if (($currenturl=~/^\/res/) &&
605: ($currenturl!~/^\/res\/adm/)) {
606: $r->print('<a href="#curloc">Current Location</a><p>');
607: }
608:
609: # Handle a network error
610:
611: if ($networkFailedFlag)
612: {
613: $r->print('<H2>LON-CAPA network failure.</H2>'."\n");
614: $r->print("<p>LON-CAPA's network is having difficulties, some problem" .
615: " information, such as due dates, will not be available.");
616: }
617: # ----------------------------------------------------- The little content list
618: for ($i=0;$i<=$#rows;$i++) {
619: if ($rows[$i]) {
620: my @colcont=split(/\&/,$rows[$i]);
621: my $avespan=$lcm/($#colcont+1);
622: for ($j=0;$j<=$#colcont;$j++) {
623: my $rid=$colcont[$j];
624: if ($rid=~/^h(.+)/) {
625: $rid=$1;
626: $r->print(' <a href="#'.
627: $rid.'">'.$hash{'title_'.$rid}.
628: '</a><br>');
629: }
630: }
631: }
632: }
633: # ----------------------------------------------------------------- Start table
634: $r->print('<hr><table cols="'.$lcm.'" border="0">');
635: for ($i=0;$i<=$#rows;$i++) {
636: if ($rows[$i]) {
637: $r->print("\n<tr>");
638: my @colcont=split(/\&/,$rows[$i]);
639: my $avespan=$lcm/($#colcont+1);
640:
641: # for each item I wish to print on this row...
642: for ($j=0;$j<=$#colcont;$j++) {
643: my $indent;my $indentstr;
644: my $linkid;
645: my $rid=$colcont[$j];
646: $rid=~/(\d+)\.(\d+)$/;
647: my $src=
648: &Apache::lonnet::declutter($hash{'src_'.$1.'.'.$2});
649: my $symb=
650: &Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.$src;
651: my $add='<td>';
652: my $adde='</td>';
653: my $hwk='<font color="#223322">';
654: my $hwke='</font>';
655: if ($rid=~/^l(\d+\.\d+),(.+)/) { $linkid=$1; $rid=$2; }
656: if ($rid=~/^i(\d+),(.+)/) { $indent=$1; $rid=$2; }
657: if ($rid=~/^h(.+)/) {
658: $rid=$1;
659: $add='<th bgcolor="#AAFF55"><a name="'.$rid.'">';
660: $adde='</th>';
661: if (($ENV{'user.adv'}) &&
662: ($parmhash{$symb.'.0.parameter_randompick'})) {
663: $adde=' (randomly select '.
664: $parmhash{$symb.'.0.parameter_randompick'}.
665: ')</th>';
666: }
667: }
668: if ($rid=~/^j(.+)/) { $rid=$1; }
669: if ($rid=~/^p(\d)(\d)\"([\w\: \(\)\/\,]*)\"(.+)/) {
670: # sub astatus describes what code/tcode mean
671: my $code=$1;
672: my $tcode=$2;
673: my $ctext=$3;
674: $rid=$4;
675:
676: # will open later
677: if ($tcode eq '1') {
678: $add='<td bgcolor="#AAAAAA">';
679: }
680:
681: # solved/correct
682: if ($code eq '3') {
683: $add='<td bgcolor="#AAFFAA">';
684: } elsif ($code eq '4') { # partially correct
685: $add='<td bgcolor="#E0FFAA">';
686: } else {
687: # not attempted
688:
689: # we end up here on network failure, so pick a neutral
690: # color if the network failed instead of bright red.
691: if ( $networkFailedFlag )
692: {
693: $add = '<td bgcolor="#AAAAAA">';
694: }
695: else
696: {
697: $add='<td bgcolor="#FFAAAA">';
698: }
699:
700: if ($tcode eq '2') { # open, not past due
701: $add='<td bgcolor="#FFFFAA">';
702: }
703:
704: if ($tcode eq '4') { # due in next 24 hours
705: $add='<td bgcolor="#FFFF33">';
706: $adde='</td>';
707: }
708: }
709: $hwk='<font color="#888811"><b>';
710: $hwke='</b></font>';
711: if ($code eq '1') {
712: $hwke='</b> ('.$ctext.')</font>';
713: }
714: if ($code eq '2' || $code eq '4') {
715: $hwk='<font color="#992222"><b>';
716: $hwke='</b> ('.$ctext.')</font>';
717: }
718: if ($code eq '3') {
719: $hwk='<font color="#229922"><b>';
720: $hwke='</b> ('.$ctext.')</font>';
721: }
722: if ($networkFailedFlag)
723: {
724: $hwke='</b> (status unavailable)</font>';
725: }
726: }
727: if ($rid && $hash{'src_'.$rid} eq $currenturl) {
728: $add=$add.'<a name="curloc"></a>'.
729: '<font color=red size=+2><b>> </b></font>';
730: $adde=
731: '<font color=red size=+2><b> <</b></font>'.$adde;
732: }
733: if ($discussiontimes{$symb}>$lastcheck) {
734: $adde=
735: '<img border=0 src="/adm/lonMisc/chat.gif">'.
736: $adde;
737: }
738: if ($error{$src}) {
739: foreach (split(/\,/,$error{$src})) {
740: if ($_) {
741: $adde=
742: ' <a href="/adm/email?display='.
743: &Apache::lonnet::escape($_).
744: '"><img src="/adm/lonMisc/bomb.gif" border=0></a>'
745: .$adde;
746: }
747: }
748: }
749: if ($feedback{$src}) {
750: foreach (split(/\,/,$feedback{$src})) {
751: if ($_) {
752: $adde=
753: ' <a href="/adm/email?display='.
754: &Apache::lonnet::escape($_).
755: '"><img src="/adm/lonMisc/feedback.gif" border=0></a>'
756: .$adde;
757: }
758: }
759: }
760: if ($indent) {
761: my $is=" ";
762: for(my $i=-1;$i<$indent;$i++) { $indentstr.=$is; }
763: }
764: if (!$linkid) { $linkid=$rid; }
765: if ($hash{'randomout_'.$rid}) {
766: $adde=' <i>(hidden)</i>'.$adde;
767: }
768: $r->print($add.$indentstr);
769: if ($rid) {
770: $r->print('<a href="'.$hash{'src_'.$linkid}.
771: (($hash{'src_'.$linkid}=~/\?/)?'&':'?').
772: 'symb='.&Apache::lonnet::escape($symb)
773: .'">'.
774: $hwk.$hash{'title_'.$rid}.$hwke.'</a>');
775: }
776: $r->print($adde);
777: }
778: $r->print('</tr>');
779: }
780: }
781: $r->print("\n</table>");
782: $r->print('</body></html>');
783: # -------------------------------------------------------------------- End page
784: }
785: # ------------------------------------------------------------- End render page
786: }
787: # ------------------------------------------------------------------ Untie hash
788: unless (untie(%hash)) {
789: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
790: "Could not untie coursemap $fn (browse).</font>");
791: }
792: unless (untie(%parmhash)) {
793: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
794: "Could not untie parmhash (browse).</font>");
795: }
796: return OK;
797: }
798:
799: sub new_handle {
800: my $r = shift;
801:
802: # Handle header-only request
803: if ($r->header_only) {
804: if ($ENV{'browser.mathml'}) {
805: $r->content_type('text/xml');
806: } else {
807: $r->content_type('text/html');
808: }
809: $r->send_http_header;
810: return OK;
811: }
812:
813: # Send header, don't cache this page
814: if ($ENV{'browser.mathml'}) {
815: $r->content_type('text/xml');
816: } else {
817: $r->content_type('text/html');
818: }
819: &Apache::loncommon::no_cache($r);
820: $r->send_http_header;
821:
822: # Header
823: $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
824: ''));
825: # Initialize the nav map
826: my $navmap = Apache::lonnavmaps::navmap->new(
827: $ENV{"request.course.fn"}.".db",
828: $ENV{"request.course.fn"}."_parms.db", 1);
829:
830:
831: if (!defined($navmap)) {
832: my $requrl = $r->uri;
833: $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
834: return HTTP_NOT_ACCEPTABLE;
835: }
836:
837: # Check that it's defined
838: if (!($navmap->courseMapDefined())) {
839: $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
840: '</body></html>');
841: return OK;
842: }
843:
844: # Grab a resource object so we have access to the constants; this
845: # is technically not proper, but should be harmless
846: my $res = $navmap->firstResource();
847:
848: # Defines a status->color mapping, null string means don't color
849: my %colormap =
850: ( $res->NETWORK_FAILURE => '',
851: $res->CORRECT => '#BBFFBB',
852: $res->EXCUSED => '#BBBBFF',
853: $res->PAST_DUE_ANSWER_LATER => '#FFAA00',
854: $res->PAST_DUE_NO_ANSWER => '#FFAA00',
855: $res->ANSWER_OPEN => '#FF00AA',
856: $res->OPEN_LATER => '',
857: $res->TRIES_LEFT => '#FFFF00',
858: $res->INCORRECT => '#FFAA00',
859: $res->OPEN => '#FFFF88',
860: $res->NOTHING_SET => '' );
861:
862: my %filterHash;
863: # Figure out what we're not displaying
864: foreach (split(/\,/, $ENV{"form.filter"})) {
865: if ($_) {
866: $filterHash{$_} = "1";
867: }
868: }
869:
870: # Begin the HTML table
871: # two columns: the title/icon on the left, the info on the right
872: $r->print('<table cellspacing="3" cellpadding="0" bgcolor="#FFFFFF">' ."\n");
873:
874: my $mapIterator = $navmap->getIterator(undef, undef, \%filterHash);
875: my $curRes = $mapIterator->next();
876: undef $res; # so we don't accidentally use it later
877: my $indentLevel = -1;
878: my $indentString = " ";
879:
880: my $isNewBranch = 0;
881:
882: while ($curRes != $mapIterator->END_NAV_MAP) {
883: if ($curRes == $mapIterator->BEGIN_MAP() ||
884: $curRes == $mapIterator->BEGIN_BRANCH()) {
885: $indentLevel++;
886: }
887: if ($curRes == $mapIterator->END_MAP() ||
888: $curRes == $mapIterator->END_BRANCH()) {
889: $indentLevel--;
890: }
891: if ($curRes == $mapIterator->BEGIN_BRANCH()) {
892: $isNewBranch = 1;
893: }
894:
895: if (ref($curRes) && $curRes->src()) {
896:
897: my @parts;
898: if ($curRes->is_problem()) {
899: @parts = @{$curRes->parts()};
900: if (scalar(@parts) > 1) { shift(@parts); }
901: } else {
902: @parts[0] = "0"; # this is to get past foreach loop below
903: # you can consider a non-problem resource as a resource
904: # with only one part without loss
905: }
906:
907: foreach my $part (@parts) {
908:
909: # For each thing we're displaying...
910:
911: my $stack = $mapIterator->getStack();
912: my $src = getLinkForResource($stack);
913:
914: my $srcHasQuestion = $src =~ /\?/;
915: my $link = $src.
916: ($srcHasQuestion?'&':'?') .
917: 'symb='.&Apache::lonnet::escape($curRes->symb()).
918: '"';
919: my $title = $curRes->title();
920: my $partLabel = "";
921: my $newBranchText = "";
922:
923: # If this is a new branch, label it so
924: # (temporary, this should be an icon w/ alt text)
925: if ($isNewBranch) {
926: $newBranchText = "NB -> ";
927: $isNewBranch = 0;
928: }
929:
930: # links to open and close the folders
931: my $linkopen = "<a href=\"$link\">";
932: my $linkclose = "</a>";
933:
934: my $icon = "html.gif";
935: if ($curRes->is_problem()) {
936: $icon = "problem.gif";
937: }
938:
939: # Display the correct icon, link to open or shut map
940: if ($curRes->is_map()) {
941: my $mapId = $curRes->map_pc();
942: my $nowOpen = !defined($filterHash{$mapId});
943: $icon = $nowOpen ?
944: "folder_opened.gif" : "folder_closed.gif";
945: $linkopen = "<a href=\"/adm/navmaps?filter=";
946: $linkopen .= $nowOpen ?
947: addToFilter(\%filterHash, $mapId) :
948: removeFromFilter(\%filterHash, $mapId);
949: $linkopen .= "\">";
950: $linkclose = "</a>";
951:
952: }
953:
954: my $colorizer = "";
955: if ($curRes->is_problem()) {
956: my $status = $curRes->status($part);
957: my $color = $colormap{$status};
958: if ($color ne "") {
959: $colorizer = "bgcolor=\"$color\"";
960: }
961: }
962:
963: $r->print(" <tr><td align=\"left\" valign=\"top\">\n");
964:
965: # print indentation
966: for (my $i = 0; $i < $indentLevel; $i++) {
967: $r->print($indentString);
968: }
969:
970: $r->print(" ${newBranchText}${linkopen}<img border=\"0\" src=\"" .
971: "/adm/lonIcons/$icon\" alt=\"\">${linkclose}\n");
972:
973: if ($curRes->is_problem() && $part != "0") { $partLabel = " (Part $part)"; }
974:
975: $r->print(" <a href=\"$link\">$title$partLabel</a></td>".
976: "<td $colorizer align=\"right\">\n");
977:
978: if ($curRes->kind() eq "res" and
979: $curRes->is_problem() ) {
980: $r->print (getDescription($curRes, $part));
981: }
982: }
983: }
984: $curRes = $mapIterator->next();
985: }
986:
987: $r->print("</table></body></html>");
988:
989: return OK;
990: }
991:
992: # Convenience functions: Returns a string that adds or subtracts
993: # the second argument from the first hash, appropriate for the
994: # query string that determines which folders to recurse on
995: sub addToFilter {
996: my $hashIn = shift;
997: my $addition = shift;
998: my %hash = %$hashIn;
999: $hash{$addition} = 1;
1000:
1001: return join (",", keys(%hash));
1002: }
1003:
1004: sub removeFromFilter {
1005: my $hashIn = shift;
1006: my $subtraction = shift;
1007: my %hash = %$hashIn;
1008:
1009: delete $hash{$subtraction};
1010: return join(",", keys(%hash));
1011: }
1012:
1013: # Convenience function: Given a stack returned from getStack on the iterator,
1014: # return the correct src() value.
1015: # Later, this should add an anchor when we start putting anchors in pages.
1016: sub getLinkForResource {
1017: my $stack = shift;
1018: my $res;
1019:
1020: # Check to see if there are any pages in the stack
1021: foreach $res (@$stack) {
1022: if (defined($res) && $res->is_page()) {
1023: return $res->src();
1024: }
1025: }
1026:
1027: # Failing that, return the src of the last resource that is defined
1028: # (when we first recurse on a map, it puts an undefined resource
1029: # on the bottom because $self->{HERE} isn't defined yet, and we
1030: # want the src for the map anyhow)
1031: foreach (@$stack) {
1032: if (defined($_)) { $res = $_; }
1033: }
1034:
1035: return $res->src();
1036: }
1037:
1038: # Convenience function: This seperates the logic of how to create
1039: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
1040: # etc.) into a seperate function. It takes a resource object as the
1041: # first parameter, and the part number of the resource as the second.
1042: # It's basically a big switch statement on the status of the resource.
1043:
1044: sub getDescription {
1045: my $res = shift;
1046: my $part = shift;
1047: my $status = $res->getDateStatus();
1048:
1049: if ($status == $res->NETWORK_FAILURE) { return ""; }
1050: if ($status == $res->NOTHING_SET) {
1051: return "Not currently assigned.";
1052: }
1053: if ($status == $res->OPEN_LATER) {
1054: return "Opens: " . timeToHumanString($res->opendate($part));
1055: }
1056: if ($status == $res->OPEN) {
1057: return "Due: $status " . timeToHumanString($res->duedate($part));
1058: }
1059: if ($status == $res->PAST_DUE_ANSWER_LATER) {
1060: return "Answer: " . timeToHumanString($res->answerdate($part));
1061: }
1062: if ($status == $res->PAST_DUE_NO_ANSWER) {
1063: return "Was Due: " . timeToHumanString($res->duedate($part));
1064: }
1065: if ($status == $res->ANSWER_OPEN) {
1066: return "Answer available";
1067: }
1068: }
1069:
1070: # I want to change this into something more human-friendly. For
1071: # now, this is a simple call to localtime. The final function
1072: # probably belongs in loncommon.
1073: sub timeToHumanString {
1074: my ($time) = @_;
1075: # zero, '0' and blank are bad times
1076: if ($time) {
1077: return localtime($time);
1078: } else {
1079: return 'Never';
1080: }
1081: }
1082:
1083: 1;
1084:
1085: package Apache::lonnavmaps::navmap;
1086:
1087: # LEFT:
1088: # * Actual handler code (multi-part)
1089: # * Branches (aieee!) (and conditionals)
1090:
1091: =pod
1092:
1093: lonnavmaps provides functions and objects for dealing with the compiled course hashes generated when a user enters the course, and also provides the Apache handler for the "Navigation Map" button.
1094:
1095: =head1 navmap object: Encapsulating the compiled nav map
1096:
1097: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
1098:
1099: Most notably it provides a way to navigate the map sensibly and a flexible iterator that makes it easy to write various renderers based on nav maps.
1100:
1101: You must obtain resource objects through the navmap object.
1102:
1103: =head2 Methods
1104:
1105: =over 4
1106:
1107: =item * B<new>(filename, parmHashFile, genCourseAndUserOptions, genMailDiscussStatus): Binds a new navmap object to the compiled course representation and parmHashFile. genCourseAndUserOptions is a flag saying whether the course options and user options hash should be generated. This is for when you are using the parameters of the resources that require them; see documentation in resource object documentation. genMailDiscussStatus causes the nav map to retreive information about the email and discussion status of resources. Returns the navmap object if this is successful, or B<undef> if not. You must check for undef; errors will occur when you try to use the other methods otherwise.
1108:
1109: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
1110:
1111: =cut
1112:
1113: use strict;
1114: use GDBM_File;
1115:
1116: sub new {
1117: # magic invocation to create a class instance
1118: my $proto = shift;
1119: my $class = ref($proto) || $proto;
1120: my $self = {};
1121:
1122: $self->{NAV_HASH_FILE} = shift;
1123: $self->{PARM_HASH_FILE} = shift;
1124: $self->{GENERATE_COURSE_USER_OPT} = shift;
1125: $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
1126:
1127: # Resource cache stores navmapresource's as we reference them. We generate
1128: # them on-demand so we don't pay for creating resources unless we use them.
1129: $self->{RESOURCE_CACHE} = {};
1130:
1131: # Network failure flag, if we accessed the course or user opt and
1132: # failed
1133: $self->{NETWORK_FAILURE} = 0;
1134:
1135: # tie the nav hash
1136: my %navmaphash;
1137: if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
1138: &GDBM_READER(), 0640))) {
1139: return undef;
1140: }
1141: $self->{NAV_HASH} = \%navmaphash;
1142:
1143: my %parmhash;
1144: if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
1145: &GDBM_READER(), 0640)))
1146: {
1147: return undef;
1148: }
1149: $self->{PARM_HASH} = \%parmhash;
1150: $self->{HASH_TIED} = 1;
1151:
1152: # If the course opt hash and the user opt hash should be generated,
1153: # generate them
1154: if ($self->{GENERATE_COURSE_USER_OPT}) {
1155: my $uname=$ENV{'user.name'};
1156: my $udom=$ENV{'user.domain'};
1157: my $uhome=$ENV{'user.home'};
1158: my $cid=$ENV{'request.course.id'};
1159: my $chome=$ENV{'course.'.$cid.'.home'};
1160: my ($cdom,$cnum)=split(/\_/,$cid);
1161:
1162: my $userprefix=$uname.'_'.$udom.'_';
1163:
1164: my %courserdatas; my %useropt; my %courseopt;
1165: unless ($uhome eq 'no_host') {
1166: # ------------------------------------------------- Get coursedata (if present)
1167: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
1168: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
1169: ':resourcedata',$chome);
1170: if ($reply!~/^error\:/) {
1171: $courserdatas{$cid}=$reply;
1172: $courserdatas{$cid.'.last_cache'}=time;
1173: }
1174: # check to see if network failed
1175: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
1176: {
1177: $self->{NETWORK_FAILURE} = 1;
1178: }
1179: }
1180: foreach (split(/\&/,$courserdatas{$cid})) {
1181: my ($name,$value)=split(/\=/,$_);
1182: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
1183: &Apache::lonnet::unescape($value);
1184: }
1185: # --------------------------------------------------- Get userdata (if present)
1186: unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
1187: my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
1188: if ($reply!~/^error\:/) {
1189: $userrdatas{$uname.'___'.$udom}=$reply;
1190: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
1191: }
1192: # check to see if network failed
1193: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
1194: {
1195: $self->{NETWORK_FAILURE} = 1;
1196: }
1197: }
1198: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
1199: my ($name,$value)=split(/\=/,$_);
1200: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
1201: &Apache::lonnet::unescape($value);
1202: }
1203: $self->{COURSE_OPT} = \%courseopt;
1204: $self->{USER_OPT} = \%useropt;
1205: }
1206: }
1207:
1208: if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
1209: my $cid=$ENV{'request.course.id'};
1210: my ($cdom,$cnum)=split(/\_/,$cid);
1211:
1212: my %emailstatus = &Apache::lonnet::dump('email_status');
1213: my $logoutTime = $emailstatus{'logout'};
1214: my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
1215: $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
1216: $courseLeaveTime : $logoutTime);
1217: my %discussiontime = &Apache::lonnet::dump('discussiontimes',
1218: $cdom, $cnum);
1219: my %feedback=();
1220: my %error=();
1221: my $keys = &Apache::lonnet::reply('keys:'.
1222: $ENV{'user.domain'}.':'.
1223: $ENV{'user.name'}.':nohist_email',
1224: $ENV{'user.home'});
1225:
1226: foreach my $msgid (split(/\&/, $keys)) {
1227: $msgid=&Apache::lonnet::unescape($msgid);
1228: my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
1229: if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
1230: my ($what,$url)=($1,$2);
1231: my %status=
1232: &Apache::lonnet::get('email_status',[$msgid]);
1233: if ($status{$msgid}=~/^error\:/) {
1234: $status{$msgid}='';
1235: }
1236:
1237: if (($status{$msgid} eq 'new') ||
1238: (!$status{$msgid})) {
1239: if ($what eq 'Error') {
1240: $error{$url}.=','.$msgid;
1241: } else {
1242: $feedback{$url}.=','.$msgid;
1243: }
1244: }
1245: }
1246: }
1247:
1248: $self->{FEEDBACK} = \%feedback;
1249: $self->{ERROR_MSG} = \%error; # what is this? JB
1250: $self->{DISCUSSION_TIME} = \%discussiontime;
1251: $self->{EMAIL_STATUS} = \%emailstatus;
1252:
1253: }
1254:
1255: bless($self);
1256:
1257: return $self;
1258: }
1259:
1260: # Checks to see if coursemap is defined, matching test in old lonnavmaps
1261: sub courseMapDefined {
1262: my $self = shift;
1263: my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
1264:
1265: my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
1266: my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
1267: return $firstres && $lastres;
1268: }
1269:
1270: sub getIterator {
1271: my $self = shift;
1272: my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
1273: shift, shift);
1274: return $iterator;
1275: }
1276:
1277: # unties the hash when done
1278: sub untieHashes {
1279: my $self = shift;
1280: untie $self->{NAV_HASH} if ($self->{HASH_TIED});
1281: untie $self->{PARM_HASH} if ($self->{HASH_TIED});
1282: $self->{HASH_TIED} = 0;
1283: }
1284:
1285: # when the object is destroyed, be sure to untie all the hashes we tied.
1286: sub DESTROY {
1287: my $self = shift;
1288: $self->untieHashes();
1289: }
1290:
1291: =pod
1292:
1293: =item * B<getById>(id): Based on the ID of the resource (1.1, 3.2, etc.), get a resource object for that resource. This method, or other methods that use it (as in the resource object) is the only proper way to obtain a resource object.
1294:
1295: =cut
1296:
1297: # The strategy here is to cache the resource objects, and only construct them
1298: # as we use them. The real point is to prevent reading any more from the tied
1299: # hash then we have to, which should hopefully alleviate speed problems.
1300: # Caching is just an incidental detail I throw in because it makes sense.
1301:
1302: sub getById {
1303: my $self = shift;
1304: my $id = shift;
1305:
1306: if (defined ($self->{RESOURCE_CACHE}->{$id}))
1307: {
1308: return $self->{RESOURCE_CACHE}->{$id};
1309: }
1310:
1311: # resource handles inserting itself into cache.
1312: return Apache::lonnavmaps::resource->new($self, $id);
1313: }
1314:
1315: =pod
1316:
1317: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
1318:
1319: =cut
1320:
1321: sub firstResource {
1322: my $self = shift;
1323: my $firstResource = $self->{NAV_HASH}->{'map_start_' .
1324: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
1325: return $self->getById($firstResource);
1326: }
1327:
1328: =pod
1329:
1330: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
1331:
1332: =cut
1333:
1334: sub finishResource {
1335: my $self = shift;
1336: my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
1337: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
1338: return $self->getById($firstResource);
1339: }
1340:
1341: # -------------------------------------------- Figure out a cascading parameter
1342: #
1343: # For this function to work
1344: #
1345: # * parmhash needs to be tied
1346: # * courseopt and useropt need to be initialized for this user and course
1347: #
1348:
1349: sub parmval {
1350: my $self = shift;
1351: my ($what,$symb)=@_;
1352: my $cid=$ENV{'request.course.id'};
1353: my $csec=$ENV{'request.course.sec'};
1354: my $uname=$ENV{'user.name'};
1355: my $udom=$ENV{'user.domain'};
1356:
1357: unless ($symb) { return ''; }
1358: my $result='';
1359:
1360: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1361:
1362: # ----------------------------------------------------- Cascading lookup scheme
1363: my $rwhat=$what;
1364: $what=~s/^parameter\_//;
1365: $what=~s/\_/\./;
1366:
1367: my $symbparm=$symb.'.'.$what;
1368: my $mapparm=$mapname.'___(all).'.$what;
1369: my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
1370:
1371: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
1372: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
1373: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
1374:
1375: my $courselevel= $usercourseprefix.'.'.$what;
1376: my $courselevelr=$usercourseprefix.'.'.$symbparm;
1377: my $courselevelm=$usercourseprefix.'.'.$mapparm;
1378:
1379: my $useropt = $self->{USER_OPT};
1380: my $courseopt = $self->{COURSE_OPT};
1381: my $parmhash = $self->{PARM_HASH};
1382:
1383: # ---------------------------------------------------------- first, check user
1384: if ($uname and defined($useropt)) {
1385: if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
1386: if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
1387: if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
1388: }
1389:
1390: # ------------------------------------------------------- second, check course
1391: if ($csec and defined($courseopt)) {
1392: if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
1393: if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
1394: if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
1395: }
1396:
1397: if (defined($courseopt)) {
1398: if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
1399: if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
1400: if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
1401: }
1402:
1403: # ----------------------------------------------------- third, check map parms
1404:
1405: my $thisparm=$$parmhash{$symbparm};
1406: if (defined($thisparm)) { return $thisparm; }
1407:
1408: # ----------------------------------------------------- fourth , check default
1409:
1410: my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
1411: if (defined($default)) { return $default}
1412:
1413: # --------------------------------------------------- fifth , cascade up parts
1414:
1415: my ($space,@qualifier)=split(/\./,$rwhat);
1416: my $qualifier=join('.',@qualifier);
1417: unless ($space eq '0') {
1418: my ($part,$id)=split(/\_/,$space);
1419: if ($id) {
1420: my $partgeneral=$self->parmval($part.".$qualifier",$symb);
1421: if (defined($partgeneral)) { return $partgeneral; }
1422: } else {
1423: my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
1424: if (defined($resourcegeneral)) { return $resourcegeneral; }
1425: }
1426: }
1427: return '';
1428: }
1429:
1430:
1431: 1;
1432:
1433: package Apache::lonnavmaps::iterator;
1434:
1435: # This package must precede "navmap" because "navmap" uses it. In
1436: # order to keep the documentation order straight, the iterator is documented
1437: # after the navmap object.
1438:
1439: =pod
1440:
1441: =back
1442:
1443: =head1 navmap Iterator
1444:
1445: An I<iterator> encapsulates the logic required to traverse a data structure. navmap uses an iterator to traverse the course map according to the criteria you wish to use.
1446:
1447: To obtain an iterator, call the B<getIterator>() function of a B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator directly.) This will return a reference to the iterator:
1448:
1449: C<my $resourceIterator = $navmap-E<gt>getIterator();>
1450:
1451: To get the next thing from the iterator, call B<next>:
1452:
1453: C<my $nextThing = $resourceIterator-E<gt>next()>
1454:
1455: getIterator behaves as follows:
1456:
1457: =over 4
1458:
1459: =item B<getIterator>(nav_map, firstResource, finishResource, filterHash): All parameters are optional. firstResource is a resource reference corresponding to where the iterator should start. It defaults to navmap->firstResource() for the corresponding nav map. finishResource corresponds to where you want the iterator to end, defaulting to navmap->finishResource(). It is your responsibility to ensure that the iterator will actually get there. filterHash is a hash used as a set containing strings representing the resource IDs, defaulting to empty. Condition is a 1 or 0 that sets what to do with the filter hash: If a 1, then only resource that exist IN the filterHash will be recursed on. If it is a 0, only resources NOT in the filterHash will be recursed on. Defaults to 0.
1460:
1461: Thus, by default, all resources will be shown. Change the condition to a 1 without changing the hash, and only the top level of the map will be shown. Changing the condition to 1 and including some values in the hash will allow you to selectively examine parts of the navmap, while leaving it on 0 and adding things to the hash will allow you to selectively ignore parts of the nav map. See the handler code for examples.
1462:
1463: The iterator will return either a reference to a resource object, or a token representing something in the map, such as the beginning of a new branch. The possible tokens are:
1464:
1465: =over 4
1466:
1467: =item * some list of tokens here
1468:
1469: =back
1470:
1471: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_NAV_MAP. (Perl will automatically optimize these into constants.
1472:
1473: =cut
1474:
1475: # Here are the tokens for the iterator:
1476:
1477: sub END_NAV_MAP { return 0; } # Represents end of entire nav map
1478: sub BEGIN_MAP { return 1; } # begining of a new map
1479: sub END_MAP { return 2; } # end of the map
1480: sub BEGIN_BRANCH { return 3; } # beginning of a branch
1481: sub END_BRANCH { return 4; } # end of a branch
1482:
1483: # Params: nav map, start resource, end resource, filter, condition,
1484: # already seen hash ref
1485:
1486: sub new {
1487: # magic invocation to create a class instance
1488: my $proto = shift;
1489: my $class = ref($proto) || $proto;
1490: my $self = {};
1491:
1492: $self->{NAV_MAP} = shift;
1493: return undef unless ($self->{NAV_MAP});
1494:
1495: # Handle the parameters
1496: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
1497: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
1498:
1499: # If the given resources are just the ID of the resource, get the
1500: # objects
1501: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
1502: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
1503: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
1504: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
1505:
1506: $self->{FILTER} = shift;
1507:
1508: # A hash, used as a set, of resource already seen
1509: $self->{ALREADY_SEEN} = shift;
1510: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1511:
1512: # Flag: Have we started yet? If not, the first action is to return BEGIN_MAP.
1513: $self->{STARTED} = 0;
1514:
1515: # Should we continue calling the recursive iterator, if any?
1516: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1517: # The recursive iterator, if any
1518: $self->{RECURSIVE_ITERATOR} = undef;
1519: # Are we recursing on a map, or a branch?
1520: $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
1521: # And the count of how deep it is, so that this iterator can keep track of
1522: # when to pick back up again.
1523: $self->{RECURSIVE_DEPTH} = 0;
1524:
1525: # For keeping track of our branches, we maintain our own stack
1526: $self->{BRANCH_STACK} = [];
1527: # If the size shrinks, we exhausted a branch
1528: $self->{BRANCH_STACK_SIZE} = 0;
1529: $self->{BRANCH_DEPTH} = 0;
1530:
1531: # For returning two things in a forced sequence
1532: $self->{FORCE_NEXT} = undef;
1533:
1534: # Start with the first resource
1535: push @{$self->{BRANCH_STACK}}, $self->{FIRST_RESOURCE};
1536: $self->{BRANCH_STACK_SIZE} = 1;
1537:
1538: bless($self);
1539: return $self;
1540: }
1541:
1542: # Note... this function is *touchy*. I strongly recommend tracing
1543: # through it with the debugger a few times on a non-trivial map before
1544: # modifying it. Order is *everything*.
1545: sub next {
1546: my $self = shift;
1547:
1548: # Iterator logic goes here
1549:
1550: # Is this return value pre-determined?
1551: if (defined($self->{FORCE_NEXT})) {
1552: my $tmp = $self->{FORCE_NEXT};
1553: $self->{FORCE_NEXT} = undef;
1554: return $tmp;
1555: }
1556:
1557: # Are we using a recursive iterator? If so, pull from that and
1558: # watch the depth; we want to resume our level at the correct time.
1559: if ($self->{RECURSIVE_ITERATOR_FLAG})
1560: {
1561: # grab the next from the recursive iterator
1562: my $next = $self->{RECURSIVE_ITERATOR}->next();
1563:
1564: # is it a begin or end map? Update depth if so
1565: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
1566: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
1567:
1568: # Are we back at depth 0? If so, stop recursing.
1569: if ($self->{RECURSIVE_DEPTH} == 0) {
1570: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1571: }
1572:
1573: return $next;
1574: }
1575:
1576: # Is there a current resource to grab? If not, then return
1577: # END_BRANCH and END_MAP in succession.
1578: if (scalar(@{$self->{BRANCH_STACK}}) == 0) {
1579: if ($self->{BRANCH_DEPTH} > 0) {
1580: $self->{FORCE_NEXT} = $self->END_MAP();
1581: $self->{BRANCH_DEPTH}--;
1582: return $self->END_BRANCH();
1583: } else {
1584: return $self->END_MAP();
1585: }
1586: }
1587:
1588: # Have we not yet begun? If not, return BEGIN_MAP and
1589: # remember that we've started.
1590: if ( !$self->{STARTED} ) {
1591: $self->{STARTED} = 1;
1592: return $self->BEGIN_MAP;
1593: }
1594:
1595: # Did the branch stack shrink since last run? If so,
1596: # we exhausted a branch last time, therefore, we're about
1597: # to start a new one. (We know because we already checked to see
1598: # if the stack was empty.)
1599: if ( scalar (@{$self->{BRANCH_STACK}}) < $self->{BRANCH_STACK_SIZE}) {
1600: $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
1601: $self->{BRANCH_DEPTH}++;
1602: return $self->BEGIN_BRANCH();
1603: }
1604:
1605: # Remember the size for comparision next time.
1606: $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
1607:
1608: # If the next resource we mean to return is going to need
1609: # a lower branch level, terminate branches until we get
1610: # there.
1611:
1612: # Get the next resource in the branch
1613: $self->{HERE} = pop @{$self->{BRANCH_STACK}};
1614:
1615: # Are we at the right depth? If not, close a branch and return
1616: # the current resource onto the branch stack
1617: if (defined($self->{HERE}->{DATA}->{ITERATOR_DEPTH})
1618: && $self->{HERE}->{DATA}->{ITERATOR_DEPTH} <
1619: $self->{BRANCH_DEPTH} ) {
1620: $self->{BRANCH_DEPTH}--;
1621: # return it so we can pick it up eventually
1622: push @{$self->{BRANCH_STACK}}, $self->{HERE};
1623: return $self->END_BRANCH();
1624: }
1625:
1626: # We always return it after this point and never before
1627: # (proof: look at just the return statements), so we
1628: # remember that we've seen this.
1629: $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
1630:
1631: # Are we at the utter end? If so, return the END_NAV_MAP marker.
1632: if ($self->{HERE} == $self->{NAV_MAP}->finishResource() ) {
1633: $self->{FORCE_NEXT} = $self->END_NAV_MAP;
1634: return $self->{HERE};
1635: }
1636:
1637: # Get the next possible resources
1638: my $nextUnfiltered = $self->{HERE}->getNext();
1639: my $next = [];
1640:
1641: # filter the next possibilities to remove things we've
1642: # already seen. Also, remember what branch depth they should
1643: # be displayed at, since there's no other reliable way to tell.
1644: foreach (@$nextUnfiltered) {
1645: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1646: push @$next, $_;
1647: $_->{DATA}->{ITERATOR_DEPTH} =
1648: $self->{BRANCH_DEPTH} + 1;
1649: }
1650: }
1651:
1652: # Handle branch cases:
1653: # Nothing is available next: BRANCH_END
1654: # 1 thing next: standard non-branch
1655: # 2+ things next: have some branches
1656: my $nextCount = scalar(@$next);
1657: if ($nextCount == 0) {
1658: # Return this and on the next run, close the branch up if we're
1659: # in a branch
1660: if ($self->{BRANCH_DEPTH} > 0 ) {
1661: $self->{FORCE_NEXT} = $self->END_BRANCH();
1662: $self->{BRANCH_DEPTH}--;
1663: }
1664: return $self->{HERE};
1665: }
1666:
1667: while (@$next) {
1668: # copy the next possibilities over to the branch stack
1669: # in the right order
1670: push @{$self->{BRANCH_STACK}}, shift @$next;
1671: }
1672:
1673: if ($nextCount >= 2) {
1674: $self->{FORCE_NEXT} = $self->BEGIN_BRANCH();
1675: $self->{BRANCH_DEPTH}++;
1676: return $self->{HERE};
1677: }
1678:
1679: # If this is a map and we want to recurse down it... (not filtered out)
1680: if ($self->{HERE}->is_map() &&
1681: !defined($self->{FILTER}->{$self->{HERE}->map_pc()})) {
1682: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
1683: my $firstResource = $self->{HERE}->map_start();
1684: my $finishResource = $self->{HERE}->map_finish();
1685:
1686: # Odd perl syntax here; $self->new allows one to create a new iterator
1687: # can't figure out how to ref this package directly correctly
1688: # isn't MAIN::new, __PACKAGE__::new or Apache::lonnavmaps::iterator->new
1689: $self->{RECURSIVE_ITERATOR} =
1690: Apache::lonnavmaps::iterator->new ($self->{NAV_MAP}, $firstResource,
1691: $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN});
1692: # prime the new iterator with the first resource
1693: #push @{$self->{RECURSIVE_ITERATOR}->{BRANCH_STACK}}, $firstResource;
1694: }
1695:
1696: return $self->{HERE};
1697: }
1698:
1699: =pod
1700:
1701: The other method available on the iterator is B<getStack>, which returns an array populated with the current 'stack' of maps, as references to the resource objects. Example: This is useful when making the navigation map, as we need to check whether we are under a page map to see if we need to link directly to the resource, or to the page. The first elements in the array will correspond to the top of the stack (most inclusive map).
1702:
1703: =cut
1704:
1705: sub getStack {
1706: my $self=shift;
1707:
1708: my @stack;
1709:
1710: $self->populateStack(\@stack);
1711:
1712: return \@stack;
1713: }
1714:
1715: # Private method: Calls the iterators recursively to populate the stack.
1716: sub populateStack {
1717: my $self=shift;
1718: my $stack = shift;
1719:
1720: push @$stack, $self->{HERE};
1721:
1722: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1723: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
1724: }
1725: }
1726:
1727: 1;
1728:
1729: package Apache::lonnavmaps::resource;
1730:
1731: use Apache::lonnet;
1732:
1733: =pod
1734:
1735: =head1 Object: resource
1736:
1737: A resource object encapsulates a resource in a resource map, allowing easy manipulation of the resource, querying the properties of the resource (including user properties), and represents a reference that can be used as the canonical representation of the resource by lonnavmap clients like renderers.
1738:
1739: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
1740:
1741: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
1742:
1743: =head2 Public Members
1744:
1745: resource objects have a hash called DATA ($resourceRef->{DATA}) that you can store whatever you want in. This allows you to easily do two-pass algorithms without worrying about managing your own resource->data hash.
1746:
1747: =head2 Methods
1748:
1749: =over 4
1750:
1751: =item * B<new>($navmapRef, $idString): The first arg is a reference to the parent navmap object. The second is the idString of the resource itself.
1752:
1753: =cut
1754:
1755: sub new {
1756: # magic invocation to create a class instance
1757: my $proto = shift;
1758: my $class = ref($proto) || $proto;
1759: my $self = {};
1760:
1761: $self->{NAV_MAP} = shift;
1762: $self->{ID} = shift;
1763:
1764: # Store this new resource in the parent nav map's cache.
1765: $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1766:
1767: # A hash that can be used by two-pass algorithms to store data
1768: # about this resource in. Not used by the resource object
1769: # directly.
1770: $self->{DATA} = {};
1771:
1772: bless($self);
1773:
1774: return $self;
1775: }
1776:
1777: =pod
1778:
1779: =item * B<is_map>: Returns true if this is a map, false otherwise.
1780:
1781: =item * B<title>: Returns title.
1782:
1783: =item * B<type>: Returns the type of the resource, "start", "normal", or "finish".
1784:
1785: =item * B<problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field.)
1786:
1787: =back
1788:
1789: =cut
1790:
1791: # private function: simplify the NAV_HASH lookups we keep doing
1792: # pass the name, and to automatically append my ID, pass a true val on the
1793: # second param
1794: sub navHash {
1795: my $self = shift;
1796: my $param = shift;
1797: my $id = shift;
1798: return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
1799: }
1800:
1801: # These info functions can be used directly, as they don't return
1802: # resource information.
1803: sub title { my $self=shift; return $self->navHash("title_", 1); }
1804: sub type { my $self=shift; return $self->navHash("type_", 1); }
1805: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
1806: # "to" can return a comma seperated list for branches
1807: sub to { my $self=shift; return $self->navHash("to_", 1); }
1808: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1809: sub src {
1810: my $self=shift;
1811: return $self->navHash("src_", 1);
1812: }
1813: sub symb {
1814: my $self=shift;
1815: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
1816: my $symbSrc = &Apache::lonnet::declutter($self->src());
1817: return &Apache::lonnet::declutter(
1818: $self->navHash('map_id_'.$first))
1819: . '___' . $second . '___' . $symbSrc;
1820: }
1821: sub is_problem {
1822: my $self=shift;
1823: my $src = $self->src();
1824: return ($src =~ /problem$/);
1825: }
1826: sub is_html {
1827: my $self=shift;
1828: my $src = $self->src();
1829: return ($src =~ /html$/);
1830: }
1831: sub is_sequence {
1832: my $self=shift;
1833: my $src = $self->src();
1834: return ($src =~ /sequence$/);
1835: }
1836: sub is_page {
1837: my $self=shift;
1838: my $src = $self->src();
1839: return ($src =~ /page$/);
1840: }
1841:
1842:
1843:
1844:
1845: # Move this into POD: In order to use these correctly, courseopt
1846: # and useropt need to be generated
1847: sub parmval {
1848: my $self = shift;
1849: my $what = shift;
1850: my $part = shift || "0";
1851: return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
1852: }
1853:
1854: #####
1855: # Map Queries
1856: #####
1857:
1858: # These methods relate to whether or not the resource is a map, and the
1859: # attributes of that map.
1860:
1861: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
1862: sub map_finish {
1863: my $self = shift;
1864: my $src = $self->src();
1865: my $res = $self->navHash("map_finish_$src", 0);
1866: $res = $self->{NAV_MAP}->getById($res);
1867: return $res;
1868: }
1869: sub map_start {
1870: my $self = shift;
1871: my $src = $self->src();
1872: my $res = $self->navHash("map_start_$src", 0);
1873: $res = $self->{NAV_MAP}->getById($res);
1874: return $res;
1875: }
1876: sub map_pc {
1877: my $self = shift;
1878: my $src = $self->src();
1879: return $self->navHash("map_pc_$src", 0);
1880: }
1881: sub map_type {
1882: my $self = shift;
1883: my $pc = $self->map_pc();
1884: return $self->navHash("map_type_$pc", 0);
1885: }
1886:
1887:
1888:
1889: #####
1890: # Property queries
1891: #####
1892:
1893: # These functions will be responsible for returning the CORRECT
1894: # VALUE for the parameter, no matter what. So while they may look
1895: # like direct calls to parmval, they can be more then that.
1896: # So, for instance, the duedate function should use the "duedatetype"
1897: # information, rather then the resource object user.
1898:
1899: =pod
1900:
1901: =head2 Resource Parameters
1902:
1903: In order to use the resource parameters correctly, the nav map must have been instantiated with genCourseAndUserOptions set to true, so the courseopt and useropt is read correctly. Then, you can call these functions to get the relevant parameters for the resource. Each function defaults to "part 0", but can be directed to another part by passing the part as the second parameter.
1904:
1905: These methods are responsible for getting the parameter correct, not merely reflecting the contents of the GDBM hashes. As we move towards dates relative to other dates, these methods should be updated to reflect that. (Then, anybody using these methods won't have to update their code.)
1906:
1907: =over 4
1908:
1909: =item * B<acc>: Get the Client IP/Name Access Control information.
1910:
1911: =item * B<answerdate>: Get the answer-reveal date for the problem.
1912:
1913: =item * B<duedate>: Get the due date for the problem.
1914:
1915: =item * B<tries>: Get the number of tries the student has used on the problem.
1916:
1917: =item * B<maxtries>: Get the number of max tries allowed.
1918:
1919: =item * B<opendate>: Get the open date for the problem.
1920:
1921: =item * B<sig>: Get the significant figures setting.
1922:
1923: =item * B<tol>: Get the tolerance for the problem.
1924:
1925: =item * B<type>: Get the question type for the problem.
1926:
1927: =item * B<weight>: Get the weight for the problem.
1928:
1929: =back
1930:
1931: =cut
1932:
1933: sub acc {
1934: (my $self, my $part) = @_;
1935: return $self->parmval("acc", $part);
1936: }
1937: sub answerdate {
1938: (my $self, my $part) = @_;
1939: # Handle intervals
1940: if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
1941: return $self->duedate($part) +
1942: $self->parmval("answerdate", $part);
1943: }
1944: return $self->parmval("answerdate", $part);
1945: }
1946: sub duedate {
1947: (my $self, my $part) = @_;
1948: return $self->parmval("duedate", $part);
1949: }
1950: sub maxtries {
1951: (my $self, my $part) = @_;
1952: return $self->parmval("maxtries", $part);
1953: }
1954: sub opendate {
1955: (my $self, my $part) = @_;
1956: if ($self->parmval("opendate.type", $part) eq 'date_interval') {
1957: return $self->duedate($part) -
1958: $self->parmval("opendate", $part);
1959: }
1960: return $self->parmval("opendate");
1961: }
1962: sub sig {
1963: (my $self, my $part) = @_;
1964: return $self->parmval("sig", $part);
1965: }
1966: sub tol {
1967: (my $self, my $part) = @_;
1968: return $self->parmval("tol", $part);
1969: }
1970: sub type {
1971: (my $self, my $part) = @_;
1972: return $self->parmval("type", $part);
1973: }
1974: sub weight {
1975: (my $self, my $part) = @_;
1976: return $self->parmval("weight", $part);
1977: }
1978: sub tries {
1979: my $self = shift;
1980: my $part = shift;
1981: $part = '0' if (!defined($part));
1982:
1983: # Make sure return hash is loaded, should error check
1984: $self->getReturnHash();
1985:
1986: my $tries = $self->{RETURN_HASH}->{'resource.'.$part.'.tries'};
1987: if (!defined($tries)) {return '0';}
1988: return $tries;
1989: }
1990:
1991: # Multiple things need this
1992: sub getReturnHash {
1993: my $self = shift;
1994:
1995: if (!defined($self->{RETURN_HASH})) {
1996: my %tmpHash = &Apache::lonnet::restore($self->symb());
1997: $self->{RETURN_HASH} = \%tmpHash;
1998: }
1999: }
2000:
2001: ######
2002: # Status queries
2003: ######
2004:
2005: # These methods query the status of problems.
2006:
2007: # If we need to count parts, this function determines the number of
2008: # parts from the metadata. When called, it returns a reference to a list
2009: # of strings corresponding to the parts. (Thus, using it in a scalar context
2010: # tells you how many parts you have in the problem:
2011: # $partcount = scalar($resource->countParts());
2012: # Don't use $self->{PARTS} directly because you don't know if it's been
2013: # computed yet.
2014:
2015: =pod
2016:
2017: =head2 Resource misc
2018:
2019: Misc. functions for the resource.
2020:
2021: =over 4
2022:
2023: =item * B<parts>(): Returns a list reference containing sorted strings corresponding to each part of the problem. To count the number of parts, use the list in a scalar context, and subtract one if greater then two. (One part problems have a part 0. Multi-parts have a part 0, plus a part for each part. You may or may not wish to filter out part 0.)
2024:
2025: =item * B<countParts>(): Returns the number of parts of the problem a student can answer. Thus, for single part problems, returns 1. For multipart, it returns the number of parts in the problem, not including psuedo-part 0.
2026:
2027: =back
2028:
2029: =cut
2030:
2031: sub parts {
2032: my $self = shift;
2033:
2034: $self->extractParts();
2035: return $self->{PARTS};
2036: }
2037:
2038: sub countParts {
2039: my $self = shift;
2040:
2041: my $parts = $self->parts();
2042:
2043: if (scalar(@{$parts}) == 1) { return 1;}
2044:
2045: return scalar(@{$parts}) - 1;
2046: }
2047:
2048: # Private function: Extracts the parts information and saves it
2049: sub extractParts {
2050: my $self = shift;
2051:
2052: return if ($self->{PARTS});
2053:
2054: $self->{PARTS} = [];
2055:
2056: # Retrieve part count
2057: foreach (split(/\,/,&Apache::lonnet::metadata($self->src(),
2058: 'allpossiblekeys'))) {
2059: if ($_ =~ /^parameter\_(.*)\_opendate$/) {
2060: push @{$self->{PARTS}}, $1;
2061: }
2062: }
2063:
2064: # Is this possible to do in one line? - Jeremy
2065: my @sortedParts = sort @{$self->{PARTS}};
2066: $self->{PARTS} = \@sortedParts;
2067:
2068: return;
2069: }
2070:
2071: =pod
2072:
2073: =head2 Resource Status
2074:
2075: Problem resources have status information, reflecting their various dates and completion statuses. You can obtain this information and import symbolic constants to represent the status.
2076:
2077: There are two aspects to the status: the date-related information and the completion information.
2078:
2079: Idiomatic usage of these two methods would probably look something like
2080:
2081: foreach ($resource->parts()) {
2082: my $dateStatus = $resource->getDateStatus($_);
2083: my $completionStatus = $resource->getCompletionStatus($_);
2084:
2085: ... use it here ...
2086: }
2087:
2088: =over 4
2089:
2090: =item * B<getDateStatus>($part): ($part defaults to 0). A convenience function that returns a symbolic constant telling you about the date status of the part, with the following possible results:
2091:
2092: =back
2093:
2094: B<Date Codes>
2095:
2096: =over 4
2097:
2098: =item * B<OPEN_LATER>: The problem will be opened later.
2099:
2100: =item * B<OPEN>: Open and not yet due.
2101:
2102: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
2103:
2104: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
2105:
2106: =item * B<ANSWER_OPEN>: The answer date is here.
2107:
2108: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
2109:
2110: =back
2111:
2112: =cut
2113:
2114: # Apparently the compiler optimizes these into constants automatically
2115: sub OPEN_LATER { return 0; }
2116: sub OPEN { return 1; }
2117: sub PAST_DUE_NO_ANSWER { return 2; }
2118: sub PAST_DUE_ANSWER_LATER { return 3; }
2119: sub ANSWER_OPEN { return 4; }
2120: sub NOTHING_SET { return 5; }
2121: sub NETWORK_FAILURE { return 100; }
2122:
2123: # getDateStatus gets the date status for a given problem part.
2124: # Because answer date, due date, and open date are fully independent
2125: # (i.e., it is perfectly possible to *only* have an answer date),
2126: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
2127: # (past, future, none given). This function handles this with a decision
2128: # tree. Read the comments to follow the decision tree.
2129:
2130: sub getDateStatus {
2131: my $self = shift;
2132: my $part = shift;
2133: $part = "0" if (!defined($part));
2134:
2135: # Always return network failure if there was one.
2136: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2137:
2138: my $now = time();
2139:
2140: my $open = $self->opendate($part);
2141: my $due = $self->duedate($part);
2142: my $answer = $self->answerdate($part);
2143:
2144: if (!$open && !$due && !$answer) {
2145: # no data on the problem at all
2146: # should this be the same as "open later"? think multipart.
2147: return $self->NOTHING_SET;
2148: }
2149: if (!$open || $now < $open) {return $self->OPEN_LATER};
2150: if (!$due || $now < $due) {return $self->OPEN};
2151: if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER};
2152: if ($answer) { return $self->ANSWER_OPEN; };
2153: return PAST_DUE_NO_ANSWER;
2154: }
2155:
2156: =pod
2157:
2158: B<>
2159:
2160: =over 4
2161:
2162: =item * B<getCompletionStatus>($part): ($part defaults to 0.) A convenience function that returns a symbolic constant telling you about the completion status of the part, with the following possible results:
2163:
2164: =back
2165:
2166: B<Completion Codes>
2167:
2168: =over 4
2169:
2170: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
2171:
2172: =item * B<INCORRECT>: Attempted, but wrong by student.
2173:
2174: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
2175:
2176: =item * B<CORRECT>: Correct or correct by instructor.
2177:
2178: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
2179:
2180: =item * B<EXCUSED>: Excused. Not yet implemented.
2181:
2182: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
2183:
2184: =back
2185:
2186: =cut
2187:
2188: sub NOT_ATTEMPTED { return 10; }
2189: sub INCORRECT { return 11; }
2190: sub INCORRECT_BY_OVERRIDE { return 12; }
2191: sub CORRECT { return 13; }
2192: sub CORRECT_BY_OVERRIDE { return 14; }
2193: sub EXCUSED { return 15; }
2194:
2195: sub getCompletionStatus {
2196: my $self = shift;
2197: my $part = shift;
2198: $part = "0" if (!defined($part));
2199: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2200:
2201: # Make sure return hash exists
2202: $self->getReturnHash();
2203:
2204: my $status = $self->{RETURN_HASH}->{'resource.'.$part.'.solved'};
2205:
2206: # Left as seperate if statements in case we ever do more with this
2207: if ($status eq 'correct_by_student') {return $self->CORRECT;}
2208: if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
2209: if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
2210: if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
2211: if ($status eq 'excused') {return $self->EXCUSED; }
2212: return $self->NOT_ATTEMPTED;
2213: }
2214:
2215: =pod
2216:
2217: B<Composite Status>
2218:
2219: Along with directly returning the date or completion status, the resource object includes a convenience function B<status>() that will combine the two status tidbits into one composite status that can represent the status of the resource as a whole. The precise logic is documented in the comments of the status method. The following results may be returned, all available as methods on the resource object ($res->NETWORK_FAILURE()):
2220:
2221: =over 4
2222:
2223: =item * NETWORK_FAILURE: The network has failed and the information is not available.
2224:
2225: =item * NOTHING_SET: No dates have been set for this problem (part) at all. (Because only certain parts of a multi-part problem may be assigned, this can not be collapsed into "open later", as we don't know a given part will EVER be opened.)
2226:
2227: =item * CORRECT: For any reason at all, the part is considered correct.
2228:
2229: =item * EXCUSED: For any reason at all, the problem is excused.
2230:
2231: =item * PAST_DUE_NO_ANSWER: The problem is past due, not considered correct, and no answer date is set.
2232:
2233: =item * PAST_DUE_ANSWER_LATER: The problem is past due, not considered correct, and an answer date in the future is set.
2234:
2235: =item * ANSWER_OPEN: The problem is past due, not correct, and the answer is now available.
2236:
2237: =item * OPEN_LATER: The problem is not yet open.
2238:
2239: =item * TRIES_LEFT: The problem is open, has been tried, is not correct, but there are tries left.
2240:
2241: =item * INCORRECT: The problem is open, and all tries have been used without getting the correct answer.
2242:
2243: =item * OPEN: The item is open and not yet tried.
2244:
2245: =back
2246:
2247: =cut
2248:
2249: sub TRIES_LEFT { return 10; }
2250:
2251: sub status {
2252: my $self = shift;
2253: my $part = shift;
2254: if (!defined($part)) { $part = "0"; }
2255: my $completionStatus = $self->getCompletionStatus($part);
2256: my $dateStatus = $self->getDateStatus($part);
2257:
2258: # What we have is a two-dimensional matrix with 4 entries on one
2259: # dimension and 5 entries on the other, which we want to colorize,
2260: # plus network failure and "no date data at all".
2261:
2262: if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
2263:
2264: # There are a few whole rows we can dispose of:
2265: if ($completionStatus == CORRECT ||
2266: $completionStatus == CORRECT_BY_OVERRIDE ) {
2267: return CORRECT();
2268: }
2269:
2270: # If it's EXCUSED, then return that no matter what
2271: if ($completionStatus == EXCUSED) {
2272: return EXCUSED;
2273: }
2274:
2275: if ($dateStatus == NOTHING_SET) {
2276: return NOTHING_SET;
2277: }
2278:
2279: # Now we're down to a 3 (incorrect, incorrect_override, not_attempted)
2280: # by 4 matrix (date status).
2281:
2282: if ($dateStatus == PAST_DUE_ANSWER_LATER ||
2283: $dateStatus == PAST_DUE_NO_ANSWER) {
2284: return $dateStatus;
2285: }
2286:
2287: if ($dateStatus == ANSWER_OPEN) {
2288: return ANSWER_OPEN;
2289: }
2290:
2291: # Now: (incorrect, incorrect_override, not_attempted) x
2292: # (open_later), (open)
2293:
2294: if ($dateStatus == OPEN_LATER) {
2295: return OPEN_LATER;
2296: }
2297:
2298: # If it's WRONG...
2299: if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
2300: # and there are TRIES LEFT:
2301: if ($self->tries() < $self->maxtries()) {
2302: return TRIES_LEFT;
2303: }
2304: return INCORRECT; # otherwise, return orange; student can't fix this
2305: }
2306:
2307: # Otherwise, it's untried and open
2308: return OPEN;
2309: }
2310:
2311: =pod
2312:
2313: =head2 Resource/Nav Map Navigation
2314:
2315: =over 4
2316:
2317: =item * B<getNext>(): Gets the next resource in the navmap after this one.
2318:
2319: =cut
2320:
2321: # For the simple single-link case, to get from a resource to the next
2322: # resource, you need to look up the "to_" link in the nav hash, then
2323: # follow that with the "goesto_" link.
2324:
2325: sub getNext {
2326: my $self = shift;
2327: my $alreadySeenHash = shift;
2328: my @branches;
2329: my $to = $self->to();
2330: foreach my $branch ( split(/\,/, $to) ) {
2331: my $choice = $self->{NAV_MAP}->getById($branch);
2332: my $next = $choice->goesto();
2333: $next = $self->{NAV_MAP}->getById($next);
2334:
2335: # Don't remember it if we've already seen it
2336: if (!defined($alreadySeenHash) ||
2337: !defined($alreadySeenHash->{$next->{ID}})) {
2338: push @branches, $next;
2339: }
2340: }
2341: return \@branches;
2342: }
2343:
2344: =pod
2345:
2346: =back
2347:
2348: =cut
2349:
2350: 1;
2351:
2352: __END__
2353:
2354:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>