1: # The LearningOnline Network with CAPA
2: # Navigate Maps Handler
3: #
4: # $Id: lonnavmaps.pm,v 1.402 2007/10/05 18:48:20 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: package Apache::lonnavmaps;
31:
32: use strict;
33: use GDBM_File;
34: use Apache::loncommon();
35: use Apache::lonenc();
36: use Apache::lonlocal;
37: use Apache::lonnet;
38: use POSIX qw (floor strftime);
39: use Data::Dumper; # for debugging, not always
40: use Time::HiRes qw( gettimeofday tv_interval );
41: use LONCAPA;
42:
43: # symbolic constants
44: sub SYMB { return 1; }
45: sub URL { return 2; }
46: sub NOTHING { return 3; }
47:
48: # Some data
49:
50: my $resObj = "Apache::lonnavmaps::resource";
51:
52: # Keep these mappings in sync with lonquickgrades, which uses the colors
53: # instead of the icons.
54: my %statusIconMap =
55: (
56: $resObj->CLOSED => '',
57: $resObj->OPEN => 'navmap.open.gif',
58: $resObj->CORRECT => 'navmap.correct.gif',
59: $resObj->PARTIALLY_CORRECT => 'navmap.partial.gif',
60: $resObj->INCORRECT => 'navmap.wrong.gif',
61: $resObj->ATTEMPTED => 'navmap.ellipsis.gif',
62: $resObj->ERROR => ''
63: );
64:
65: my %iconAltTags =
66: ( 'navmap.correct.gif' => 'Correct',
67: 'navmap.wrong.gif' => 'Incorrect',
68: 'navmap.open.gif' => 'Open' );
69:
70: # Defines a status->color mapping, null string means don't color
71: my %colormap =
72: ( $resObj->NETWORK_FAILURE => '',
73: $resObj->CORRECT => '',
74: $resObj->EXCUSED => '#3333FF',
75: $resObj->PAST_DUE_ANSWER_LATER => '',
76: $resObj->PAST_DUE_NO_ANSWER => '',
77: $resObj->ANSWER_OPEN => '#006600',
78: $resObj->OPEN_LATER => '',
79: $resObj->TRIES_LEFT => '',
80: $resObj->INCORRECT => '',
81: $resObj->OPEN => '',
82: $resObj->NOTHING_SET => '',
83: $resObj->ATTEMPTED => '',
84: $resObj->ANSWER_SUBMITTED => '',
85: $resObj->PARTIALLY_CORRECT => '#006600'
86: );
87: # And a special case in the nav map; what to do when the assignment
88: # is not yet done and due in less than 24 hours
89: my $hurryUpColor = "#FF0000";
90:
91: sub close {
92: if ($env{'environment.remotenavmap'} ne 'on') { return ''; }
93: return(<<ENDCLOSE);
94: <script type="text/javascript">
95: window.status='Accessing Nav Control';
96: menu=window.open("/adm/rat/empty.html","loncapanav",
97: "height=600,width=400,scrollbars=1");
98: window.status='Closing Nav Control';
99: menu.close();
100: window.status='Done.';
101: </script>
102: ENDCLOSE
103: }
104:
105: sub update {
106: if ($env{'environment.remotenavmap'} ne 'on') { return ''; }
107: if (!$env{'request.course.id'}) { return ''; }
108: if ($ENV{'REQUEST_URI'}=~m|^/adm/navmaps|) { return ''; }
109: return(<<ENDUPDATE);
110: <form name="navform"></form>
111: <script type="text/javascript">
112: this.document.navform.action='/adm/navmaps#curloc';
113: this.document.navform.target='loncapanav';
114: this.document.navform.submit();
115: </script>
116: ENDUPDATE
117: }
118:
119: # Convenience functions: Returns a string that adds or subtracts
120: # the second argument from the first hash, appropriate for the
121: # query string that determines which folders to recurse on
122: sub addToFilter {
123: my $hashIn = shift;
124: my $addition = shift;
125: my %hash = %$hashIn;
126: $hash{$addition} = 1;
127:
128: return join (",", keys(%hash));
129: }
130:
131: sub removeFromFilter {
132: my $hashIn = shift;
133: my $subtraction = shift;
134: my %hash = %$hashIn;
135:
136: delete $hash{$subtraction};
137: return join(",", keys(%hash));
138: }
139:
140: # Convenience function: Given a stack returned from getStack on the iterator,
141: # return the correct src() value.
142: sub getLinkForResource {
143: my $stack = shift;
144: my $res;
145:
146: # Check to see if there are any pages in the stack
147: foreach $res (@$stack) {
148: if (defined($res)) {
149: my $anchor;
150: if ($res->is_page()) {
151: foreach my $item (@$stack) { if (defined($item)) { $anchor = $item; } }
152: $anchor=&escape($anchor->shown_symb());
153: return ($res->link(),$res->shown_symb(),$anchor);
154: }
155: # in case folder was skipped over as "only sequence"
156: my ($map,$id,$src)=&Apache::lonnet::decode_symb($res->symb());
157: if ($map=~/\.page$/) {
158: my $url=&Apache::lonnet::clutter($map);
159: $anchor=&escape($src->shown_symb());
160: return ($url,$res->shown_symb(),$anchor);
161: }
162: }
163: }
164:
165: # Failing that, return the src of the last resource that is defined
166: # (when we first recurse on a map, it puts an undefined resource
167: # on the bottom because $self->{HERE} isn't defined yet, and we
168: # want the src for the map anyhow)
169: foreach my $item (@$stack) {
170: if (defined($item)) { $res = $item; }
171: }
172:
173: if ($res) {
174: return ($res->link(),$res->shown_symb());
175: }
176: return;
177: }
178:
179: # Convenience function: This separates the logic of how to create
180: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
181: # etc.) into a separate function. It takes a resource object as the
182: # first parameter, and the part number of the resource as the second.
183: # It's basically a big switch statement on the status of the resource.
184:
185: sub getDescription {
186: my $res = shift;
187: my $part = shift;
188: my $status = $res->status($part);
189:
190: if ($status == $res->NETWORK_FAILURE) {
191: return &mt("Having technical difficulties; please check status later");
192: }
193: if ($status == $res->NOTHING_SET) {
194: return &mt("Not currently assigned.");
195: }
196: if ($status == $res->OPEN_LATER) {
197: return "Open " . timeToHumanString($res->opendate($part),'start');
198: }
199: if ($status == $res->OPEN) {
200: if ($res->duedate($part)) {
201: if ($res->is_practice()) {
202: return &mt("Closes ")." " .timeToHumanString($res->duedate($part),'start');
203: } else {
204: return &mt("Due")." " .timeToHumanString($res->duedate($part),'end');
205: }
206: } else {
207: return &mt("Open, no due date");
208: }
209: }
210: if ($status == $res->PAST_DUE_ANSWER_LATER) {
211: return &mt("Answer open")." " . timeToHumanString($res->answerdate($part),'start');
212: }
213: if ($status == $res->PAST_DUE_NO_ANSWER) {
214: if ($res->is_practice()) {
215: return &mt("Closed")." " . timeToHumanString($res->duedate($part),'start');
216: } else {
217: return &mt("Was due")." " . timeToHumanString($res->duedate($part),'end');
218: }
219: }
220: if (($status == $res->ANSWER_OPEN || $status == $res->PARTIALLY_CORRECT)
221: && $res->handgrade($part) ne 'yes') {
222: return &mt("Answer available");
223: }
224: if ($status == $res->EXCUSED) {
225: return &mt("Excused by instructor");
226: }
227: if ($status == $res->ATTEMPTED) {
228: return &mt("Answer submitted, not yet graded");
229: }
230: if ($status == $res->TRIES_LEFT) {
231: my $tries = $res->tries($part);
232: my $maxtries = $res->maxtries($part);
233: my $triesString = "";
234: if ($tries && $maxtries) {
235: $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
236: if ($maxtries > 1 && $maxtries - $tries == 1) {
237: $triesString = "<b>$triesString</b>";
238: }
239: }
240: if ($res->duedate($part)) {
241: return &mt("Due")." " . timeToHumanString($res->duedate($part),'end') .
242: " $triesString";
243: } else {
244: return &mt("No due date")." $triesString";
245: }
246: }
247: if ($status == $res->ANSWER_SUBMITTED) {
248: return &mt('Answer submitted');
249: }
250: }
251:
252: # Convenience function, so others can use it: Is the problem due in less than
253: # 24 hours, and still can be done?
254:
255: sub dueInLessThan24Hours {
256: my $res = shift;
257: my $part = shift;
258: my $status = $res->status($part);
259:
260: return ($status == $res->OPEN() ||
261: $status == $res->TRIES_LEFT()) &&
262: $res->duedate($part) && $res->duedate($part) < time()+(24*60*60) &&
263: $res->duedate($part) > time();
264: }
265:
266: # Convenience function, so others can use it: Is there only one try remaining for the
267: # part, with more than one try to begin with, not due yet and still can be done?
268: sub lastTry {
269: my $res = shift;
270: my $part = shift;
271:
272: my $tries = $res->tries($part);
273: my $maxtries = $res->maxtries($part);
274: return $tries && $maxtries && $maxtries > 1 &&
275: $maxtries - $tries == 1 && $res->duedate($part) &&
276: $res->duedate($part) > time();
277: }
278:
279: # This puts a human-readable name on the env variable.
280:
281: sub advancedUser {
282: return $env{'request.role.adv'};
283: }
284:
285:
286: # timeToHumanString takes a time number and converts it to a
287: # human-readable representation, meant to be used in the following
288: # manner:
289: # print "Due $timestring"
290: # print "Open $timestring"
291: # print "Answer available $timestring"
292: # Very, very, very, VERY English-only... goodness help a localizer on
293: # this func...
294:
295:
296: sub timeToHumanString {
297: my ($time,$type,$format) = @_;
298:
299: # zero, '0' and blank are bad times
300: if (!$time) {
301: return &mt('never');
302: }
303: unless (&Apache::lonlocal::current_language()=~/^en/) {
304: return &Apache::lonlocal::locallocaltime($time);
305: }
306: my $now = time();
307:
308: my @time = localtime($time);
309: my @now = localtime($now);
310:
311: # Positive = future
312: my $delta = $time - $now;
313:
314: my $minute = 60;
315: my $hour = 60 * $minute;
316: my $day = 24 * $hour;
317: my $week = 7 * $day;
318: my $inPast = 0;
319:
320: # Logic in comments:
321: # Is it now? (extremely unlikely)
322: if ( $delta == 0 ) {
323: return "this instant";
324: }
325:
326: if ($delta < 0) {
327: $inPast = 1;
328: $delta = -$delta;
329: }
330:
331: if ( $delta > 0 ) {
332:
333: my $tense = $inPast ? " ago" : "";
334: my $prefix = $inPast ? "" : "in ";
335:
336: # Less than a minute
337: if ( $delta < $minute ) {
338: if ($delta == 1) { return "${prefix}1 second$tense"; }
339: return "$prefix$delta seconds$tense";
340: }
341:
342: # Less than an hour
343: if ( $delta < $hour ) {
344: # If so, use minutes
345: my $minutes = floor($delta / 60);
346: if ($minutes == 1) { return "${prefix}1 minute$tense"; }
347: return "$prefix$minutes minutes$tense";
348: }
349:
350: # Is it less than 24 hours away? If so,
351: # display hours + minutes
352: if ( $delta < $hour * 24) {
353: my $hours = floor($delta / $hour);
354: my $minutes = floor(($delta % $hour) / $minute);
355: my $hourString = "$hours hours";
356: my $minuteString = ", $minutes minutes";
357: if ($hours == 1) {
358: $hourString = "1 hour";
359: }
360: if ($minutes == 1) {
361: $minuteString = ", 1 minute";
362: }
363: if ($minutes == 0) {
364: $minuteString = "";
365: }
366: return "$prefix$hourString$minuteString$tense";
367: }
368:
369: # If there's a caller supplied format, use it.
370:
371: if($format ne '') {
372: my $timeStr = strftime($format, localtime($time));
373: return $timeStr.&Apache::lonlocal::gettimezone($time);
374: }
375:
376: # Less than 5 days away, display day of the week and
377: # HH:MM
378:
379: if ( $delta < $day * 5 ) {
380: my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
381: $timeStr =~ s/12:00 am/00:00/;
382: $timeStr =~ s/12:00 pm/noon/;
383: return ($inPast ? "last " : "this ") .
384: $timeStr.&Apache::lonlocal::gettimezone($time);
385: }
386:
387: my $conjunction='on';
388: if ($type eq 'start') {
389: $conjunction='at';
390: } elsif ($type eq 'end') {
391: $conjunction='by';
392: }
393: # Is it this year?
394: if ( $time[5] == $now[5]) {
395: # Return on Month Day, HH:MM meridian
396: my $timeStr = strftime("$conjunction %A, %b %e at %I:%M %P", localtime($time));
397: $timeStr =~ s/12:00 am/00:00/;
398: $timeStr =~ s/12:00 pm/noon/;
399: return $timeStr.&Apache::lonlocal::gettimezone($time);
400: }
401:
402: # Not this year, so show the year
403: my $timeStr = strftime("$conjunction %A, %b %e %Y at %I:%M %P", localtime($time));
404: $timeStr =~ s/12:00 am/00:00/;
405: $timeStr =~ s/12:00 pm/noon/;
406: return $timeStr.&Apache::lonlocal::gettimezone($time);
407: }
408: }
409:
410:
411: =pod
412:
413: =head1 NAME
414:
415: Apache::lonnavmap - Subroutines to handle and render the navigation
416: maps
417:
418: =head1 SYNOPSIS
419:
420: The main handler generates the navigational listing for the course,
421: the other objects export this information in a usable fashion for
422: other modules.
423:
424: =head1 OVERVIEW
425:
426: X<lonnavmaps, overview> When a user enters a course, LON-CAPA examines the
427: course structure and caches it in what is often referred to as the
428: "big hash" X<big hash>. You can see it if you are logged into
429: LON-CAPA, in a course, by going to /adm/test. (You may need to
430: tweak the /home/httpd/lonTabs/htpasswd file to view it.) The
431: content of the hash will be under the heading "Big Hash".
432:
433: Big Hash contains, among other things, how resources are related
434: to each other (next/previous), what resources are maps, which
435: resources are being chosen to not show to the student (for random
436: selection), and a lot of other things that can take a lot of time
437: to compute due to the amount of data that needs to be collected and
438: processed.
439:
440: Apache::lonnavmaps provides an object model for manipulating this
441: information in a higher-level fashion than directly manipulating
442: the hash. It also provides access to several auxilary functions
443: that aren't necessarily stored in the Big Hash, but are a per-
444: resource sort of value, like whether there is any feedback on
445: a given resource.
446:
447: Apache::lonnavmaps also abstracts away branching, and someday,
448: conditions, for the times where you don't really care about those
449: things.
450:
451: Apache::lonnavmaps also provides fairly powerful routines for
452: rendering navmaps, and last but not least, provides the navmaps
453: view for when the user clicks the NAV button.
454:
455: B<Note>: Apache::lonnavmaps I<only> works for the "currently
456: logged in user"; if you want things like "due dates for another
457: student" lonnavmaps can not directly retrieve information like
458: that. You need the EXT function. This module can still help,
459: because many things, such as the course structure, are constant
460: between users, and Apache::lonnavmaps can help by providing
461: symbs for the EXT call.
462:
463: The rest of this file will cover the provided rendering routines,
464: which can often be used without fiddling with the navmap object at
465: all, then documents the Apache::lonnavmaps::navmap object, which
466: is the key to accessing the Big Hash information, covers the use
467: of the Iterator (which provides the logic for traversing the
468: somewhat-complicated Big Hash data structure), documents the
469: Apache::lonnavmaps::Resource objects that are returned by
470:
471: =head1 Subroutine: render
472:
473: The navmap renderer package provides a sophisticated rendering of the
474: standard navigation maps interface into HTML. The provided nav map
475: handler is actually just a glorified call to this.
476:
477: Because of the large number of parameters this function accepts,
478: instead of passing it arguments as is normal, pass it in an anonymous
479: hash with the desired options.
480:
481: The package provides a function called 'render', called as
482: Apache::lonnavmaps::render({}).
483:
484: =head2 Overview of Columns
485:
486: The renderer will build an HTML table for the navmap and return
487: it. The table consists of several columns, and a row for each
488: resource (or possibly each part). You tell the renderer how many
489: columns to create and what to place in each column, optionally using
490: one or more of the prepared columns, and the renderer will assemble
491: the table.
492:
493: Any additional generally useful column types should be placed in the
494: renderer code here, so anybody can use it anywhere else. Any code
495: specific to the current application (such as the addition of <input>
496: elements in a column) should be placed in the code of the thing using
497: the renderer.
498:
499: At the core of the renderer is the array reference COLS (see Example
500: section below for how to pass this correctly). The COLS array will
501: consist of entries of one of two types of things: Either an integer
502: representing one of the pre-packaged column types, or a sub reference
503: that takes a resource reference, a part number, and a reference to the
504: argument hash passed to the renderer, and returns a string that will
505: be inserted into the HTML representation as it.
506:
507: All other parameters are ways of either changing how the columns
508: are printing, or which rows are shown.
509:
510: The pre-packaged column names are refered to by constants in the
511: Apache::lonnavmaps namespace. The following currently exist:
512:
513: =over 4
514:
515: =item * B<Apache::lonnavmaps::resource>:
516:
517: The general info about the resource: Link, icon for the type, etc. The
518: first column in the standard nav map display. This column provides the
519: indentation effect seen in the B<NAV> screen. This column also accepts
520: the following parameters in the renderer hash:
521:
522: =over 4
523:
524: =item * B<resource_nolink>: default false
525:
526: If true, the resource will not be linked. By default, all non-folder
527: resources are linked.
528:
529: =item * B<resource_part_count>: default true
530:
531: If true, the resource will show a part count B<if> the full
532: part list is not displayed. (See "condense_parts" later.) If false,
533: the resource will never show a part count.
534:
535: =item * B<resource_no_folder_link>:
536:
537: If true, the resource's folder will not be clickable to open or close
538: it. Default is false. True implies printCloseAll is false, since you
539: can't close or open folders when this is on anyhow.
540:
541: =back
542:
543: =item * B<Apache::lonnavmaps::communication_status>:
544:
545: Whether there is discussion on the resource, email for the user, or
546: (lumped in here) perl errors in the execution of the problem. This is
547: the second column in the main nav map.
548:
549: =item * B<Apache::lonnavmaps::quick_status>:
550:
551: An icon for the status of a problem, with five possible states:
552: Correct, incorrect, open, awaiting grading (for a problem where the
553: computer's grade is suppressed, or the computer can't grade, like
554: essay problem), or none (not open yet, not a problem). The
555: third column of the standard navmap.
556:
557: =item * B<Apache::lonnavmaps::long_status>:
558:
559: A text readout of the details of the current status of the problem,
560: such as "Due in 22 hours". The fourth column of the standard navmap.
561:
562: =item * B<Apache::lonnavmaps::part_status_summary>:
563:
564: A text readout summarizing the status of the problem. If it is a
565: single part problem, will display "Correct", "Incorrect",
566: "Not yet open", "Open", "Attempted", or "Error". If there are
567: multiple parts, this will output a string that in HTML will show a
568: status of how many parts are in each status, in color coding, trying
569: to match the colors of the icons within reason.
570:
571: Note this only makes sense if you are I<not> showing parts. If
572: C<showParts> is true (see below), this column will not output
573: anything.
574:
575: =back
576:
577: If you add any others please be sure to document them here.
578:
579: An example of a column renderer that will show the ID number of a
580: resource, along with the part name if any:
581:
582: sub {
583: my ($resource, $part, $params) = @_;
584: if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
585: return '<td>' . $resource->{ID} . '</td>';
586: }
587:
588: Note these functions are responsible for the TD tags, which allow them
589: to override vertical and horizontal alignment, etc.
590:
591: =head2 Parameters
592:
593: Minimally, you should be
594: able to get away with just using 'cols' (to specify the columns
595: shown), 'url' (necessary for the folders to link to the current screen
596: correctly), and possibly 'queryString' if your app calls for it. In
597: that case, maintaining the state of the folders will be done
598: automatically.
599:
600: =over 4
601:
602: =item * B<iterator>: default: constructs one from %env
603:
604: A reference to a fresh ::iterator to use from the navmaps. The
605: rendering will reflect the options passed to the iterator, so you can
606: use that to just render a certain part of the course, if you like. If
607: one is not passed, the renderer will attempt to construct one from
608: env{'form.filter'} and env{'form.condition'} information, plus the
609: 'iterator_map' parameter if any.
610:
611: =item * B<iterator_map>: default: not used
612:
613: If you are letting the renderer do the iterator handling, you can
614: instruct the renderer to render only a particular map by passing it
615: the source of the map you want to process, like
616: '/res/103/jerf/navmap.course.sequence'.
617:
618: =item * B<include_top_level_map>: default: false
619:
620: If you need to include the top level map (meaning the course) in the
621: rendered output set this to true
622:
623: =item * B<navmap>: default: constructs one from %env
624:
625: A reference to a navmap, used only if an iterator is not passed in. If
626: this is necessary to make an iterator but it is not passed in, a new
627: one will be constructed based on env info. This is useful to do basic
628: error checking before passing it off to render.
629:
630: =item * B<r>: default: must be passed in
631:
632: The standard Apache response object. This must be passed to the
633: renderer or the course hash will be locked.
634:
635: =item * B<cols>: default: empty (useless)
636:
637: An array reference
638:
639: =item * B<showParts>:default true
640:
641: A flag. If true, a line for the resource itself, and a line
642: for each part will be displayed. If not, only one line for each
643: resource will be displayed.
644:
645: =item * B<condenseParts>: default true
646:
647: A flag. If true, if all parts of the problem have the same
648: status and that status is Nothing Set, Correct, or Network Failure,
649: then only one line will be displayed for that resource anyhow. If no,
650: all parts will always be displayed. If showParts is 0, this is
651: ignored.
652:
653: =item * B<jumpCount>: default: determined from %env
654:
655: A string identifying the URL to place the anchor 'curloc' at.
656: It is the responsibility of the renderer user to
657: ensure that the #curloc is in the URL. By default, determined through
658: the use of the env{} 'jump' information, and should normally "just
659: work" correctly.
660:
661: =item * B<here>: default: empty string
662:
663: A Symb identifying where to place the 'here' marker. The empty
664: string means no marker.
665:
666: =item * B<indentString>: default: 25 pixel whitespace image
667:
668: A string identifying the indentation string to use.
669:
670: =item * B<queryString>: default: empty
671:
672: A string which will be prepended to the query string used when the
673: folders are opened or closed. You can use this to pass
674: application-specific values.
675:
676: =item * B<url>: default: none
677:
678: The url the folders will link to, which should be the current
679: page. Required if the resource info column is shown, and you
680: are allowing the user to open and close folders.
681:
682: =item * B<currentJumpIndex>: default: no jumping
683:
684: Describes the currently-open row number to cause the browser to jump
685: to, because the user just opened that folder. By default, pulled from
686: the Jump information in the env{'form.*'}.
687:
688: =item * B<printKey>: default: false
689:
690: If true, print the key that appears on the top of the standard
691: navmaps.
692:
693: =item * B<printCloseAll>: default: true
694:
695: If true, print the "Close all folders" or "open all folders"
696: links.
697:
698: =item * B<filterFunc>: default: sub {return 1;} (accept everything)
699:
700: A function that takes the resource object as its only parameter and
701: returns a true or false value. If true, the resource is displayed. If
702: false, it is simply skipped in the display.
703:
704: =item * B<suppressEmptySequences>: default: false
705:
706: If you're using a filter function, and displaying sequences to orient
707: the user, then frequently some sequences will be empty. Setting this to
708: true will cause those sequences not to display, so as not to confuse the
709: user into thinking that if the sequence is there there should be things
710: under it; for example, see the "Show Uncompleted Homework" view on the
711: B<NAV> screen.
712:
713: =item * B<suppressNavmaps>: default: false
714:
715: If true, will not display Navigate Content resources.
716:
717: =back
718:
719: =head2 Additional Info
720:
721: In addition to the parameters you can pass to the renderer, which will
722: be passed through unchange to the column renderers, the renderer will
723: generate the following information which your renderer may find
724: useful:
725:
726: =over 4
727:
728: =item * B<counter>:
729:
730: Contains the number of rows printed. Useful after calling the render
731: function, as you can detect whether anything was printed at all.
732:
733: =item * B<isNewBranch>:
734:
735: Useful for renderers: If this resource is currently the first resource
736: of a new branch, this will be true. The Resource column (leftmost in the
737: navmaps screen) uses this to display the "new branch" icon
738:
739: =back
740:
741: =cut
742:
743: sub resource { return 0; }
744: sub communication_status { return 1; }
745: sub quick_status { return 2; }
746: sub long_status { return 3; }
747: sub part_status_summary { return 4; }
748:
749: sub render_resource {
750: my ($resource, $part, $params) = @_;
751:
752: my $nonLinkedText = ''; # stuff after resource title not in link
753:
754: my $link = $params->{"resourceLink"};
755:
756: # The URL part is not escaped at this point, but the symb is...
757: # The stuff to the left of the ? must have ' replaced by \' since
758: # it will be quoted with ' in the href.
759:
760: my ($left,$right) = split(/\?/, $link);
761: $link = $left.'?'.$right;
762:
763: my $src = $resource->src();
764: my $it = $params->{"iterator"};
765: my $filter = $it->{FILTER};
766:
767: my $title = $resource->compTitle();
768:
769: my $partLabel = "";
770: my $newBranchText = "";
771: my $location=&Apache::loncommon::lonhttpdurl("/adm/lonIcons");
772: # If this is a new branch, label it so
773: if ($params->{'isNewBranch'}) {
774: $newBranchText = "<img src='$location/branch.gif' border='0' alt='Branch' />";
775: }
776:
777: # links to open and close the folder
778:
779:
780: my $linkopen = "<a href=\"$link\">";
781:
782:
783: my $linkclose = "</a>";
784:
785: # Default icon: unknown page
786: my $icon = "<img src='$location/unknown.gif' alt='' border='0' alt=' ' ' />";
787:
788: if ($resource->is_problem()) {
789: if ($part eq '0' || $params->{'condensed'}) {
790: $icon = '<img src="'.$location.'/';
791: if ($resource->is_task()) {
792: $icon .= 'task.gif" alt="'.&mt('Task');
793: } else {
794: $icon .= 'problem.gif" alt="'.&mt('Problem');
795: }
796: $icon .='" border="0" />';
797: } else {
798: $icon = $params->{'indentString'};
799: }
800: } else {
801: $icon = "<img src='".&Apache::loncommon::icon($resource->src)."' alt=' ' border='0' />";
802: }
803:
804: # Display the correct map icon to open or shut map
805: if ($resource->is_map()) {
806: my $mapId = $resource->map_pc();
807: my $nowOpen = !defined($filter->{$mapId});
808: if ($it->{CONDITION}) {
809: $nowOpen = !$nowOpen;
810: }
811:
812: my $folderType = $resource->is_sequence() ? 'folder' : 'page';
813: my $title=$resource->title;
814: $title=~s/\"/\"/g;
815: if (!$params->{'resource_no_folder_link'}) {
816: $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
817: $icon = "<img src='$location/$icon' alt=\"".
818: ($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" border='0' />";
819:
820: $linkopen = "<a href=\"" . $params->{'url'} . '?' .
821: $params->{'queryString'} . '&filter=';
822: $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
823: addToFilter($filter, $mapId) :
824: removeFromFilter($filter, $mapId);
825: $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
826: . $params->{'hereType'} . '&here=' .
827: &escape($params->{'here'}) .
828: '&jump=' .
829: &escape($resource->symb()) .
830: "&folderManip=1\">";
831:
832: } else {
833: # Don't allow users to manipulate folder
834: $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') .
835: '.nomanip.gif';
836: $icon = "<img src='$location/$icon' alt=\"".
837: ($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" border='0' />";
838:
839: $linkopen = "";
840: $linkclose = "";
841: }
842: }
843:
844: if ($resource->randomout()) {
845: $nonLinkedText .= ' <i>('.&mt('hidden').')</i> ';
846: }
847: if (!$resource->condval()) {
848: $nonLinkedText .= ' <i>('.&mt('conditionally hidden').')</i> ';
849: }
850:
851: # We're done preparing and finally ready to start the rendering
852: my $result = "<td align='left' valign='middle'>";
853:
854: my $indentLevel = $params->{'indentLevel'};
855: if ($newBranchText) { $indentLevel--; }
856:
857: # print indentation
858: for (my $i = 0; $i < $indentLevel; $i++) {
859: $result .= $params->{'indentString'};
860: }
861:
862: # Decide what to display
863:
864: $result .= "$newBranchText$linkopen$icon$linkclose";
865:
866: my $curMarkerBegin = '';
867: my $curMarkerEnd = '';
868:
869: # Is this the current resource?
870: if (!$params->{'displayedHereMarker'} &&
871: $resource->symb() eq $params->{'here'} ) {
872: $curMarkerBegin = '<font color="red" size="+2">></font>';
873: $curMarkerEnd = '<font color="red" size="+2"><</font>';
874: $params->{'displayedHereMarker'} = 1;
875: }
876:
877: if ($resource->is_problem() && $part ne '0' &&
878: !$params->{'condensed'}) {
879: my $displaypart=$resource->part_display($part);
880: $partLabel = " (".&mt('Part: [_1]', $displaypart).")";
881: if ($link!~/\#/) { $link.='#'.&escape($part); }
882: $title = "";
883: }
884:
885: if ($params->{'condensed'} && $resource->countParts() > 1) {
886: $nonLinkedText .= ' ('.&mt('[_1] parts', $resource->countParts()).')';
887: }
888:
889: my $target;
890: if ($env{'environment.remotenavmap'} eq 'on') {
891: $target=' target="loncapaclient" ';
892: }
893: if (!$params->{'resource_nolink'} && !$resource->is_sequence() && !$resource->is_empty_sequence) {
894: $result .= " $curMarkerBegin<a $target href=\"$link\">$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
895: } else {
896: $result .= " $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
897: }
898:
899: return $result;
900: }
901:
902: sub render_communication_status {
903: my ($resource, $part, $params) = @_;
904: my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
905:
906: my $link = $params->{"resourceLink"};
907: my $target;
908: if ($env{'environment.remotenavmap'} eq 'on') {
909: $target=' target="loncapaclient" ';
910: }
911: my $linkopen = "<a $target href=\"$link\">";
912: my $linkclose = "</a>";
913: my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc");
914: if ($resource->hasDiscussion()) {
915: $discussionHTML = $linkopen .
916: '<img alt="'.&mt('New Discussion').'" border="0" src="'.$location.'/chat.gif" />' .
917: $linkclose;
918: }
919:
920: if ($resource->getFeedback()) {
921: my $feedback = $resource->getFeedback();
922: foreach my $msgid (split(/\,/, $feedback)) {
923: if ($msgid) {
924: $feedbackHTML .= ' <a '.$target.' href="/adm/email?display='
925: . &escape($msgid) . '">'
926: . '<img alt="'.&mt('New Email').'" src="'.$location.'/feedback.gif" '
927: . 'border="0" /></a>';
928: }
929: }
930: }
931:
932: if ($resource->getErrors()) {
933: my $errors = $resource->getErrors();
934: my $errorcount = 0;
935: foreach my $msgid (split(/,/, $errors)) {
936: last if ($errorcount>=10); # Only output 10 bombs maximum
937: if ($msgid) {
938: $errorcount++;
939: $errorHTML .= ' <a '.$target.' href="/adm/email?display='
940: . &escape($msgid) . '">'
941: . '<img alt="'.&mt('New Error').'" src="'.$location.'/bomb.gif" '
942: . 'border="0" /></a>';
943: }
944: }
945: }
946:
947: if ($params->{'multipart'} && $part != '0') {
948: $discussionHTML = $feedbackHTML = $errorHTML = '';
949: }
950:
951: return "<td width=\"75\" align=\"left\" valign=\"middle\">$discussionHTML$feedbackHTML$errorHTML </td>";
952:
953: }
954: sub render_quick_status {
955: my ($resource, $part, $params) = @_;
956: my $result = "";
957: my $firstDisplayed = !$params->{'condensed'} &&
958: $params->{'multipart'} && $part eq "0";
959:
960: my $link = $params->{"resourceLink"};
961: my $target;
962: if ($env{'environment.remotenavmap'} eq 'on') {
963: $target=' target="loncapaclient" ';
964: }
965: my $linkopen = "<a $target href=\"$link\">";
966: my $linkclose = "</a>";
967:
968: if ($resource->is_problem() &&
969: !$firstDisplayed) {
970:
971: my $icon = $statusIconMap{$resource->simpleStatus($part)};
972: my $alt = $iconAltTags{$icon};
973: if ($icon) {
974: my $location=
975: &Apache::loncommon::lonhttpdurl("/adm/lonIcons/$icon");
976: $result .= "<td valign='middle' width='50' align='right'>$linkopen<img width='25' height='25' src='$location' border='0' alt='$alt' />$linkclose</td>\n";
977: } else {
978: $result .= "<td width='30'> </td>\n";
979: }
980: } else { # not problem, no icon
981: $result .= "<td width='30'> </td>\n";
982: }
983:
984: return $result;
985: }
986: sub render_long_status {
987: my ($resource, $part, $params) = @_;
988: my $result = "<td align='right' valign='middle'>\n";
989: my $firstDisplayed = !$params->{'condensed'} &&
990: $params->{'multipart'} && $part eq "0";
991:
992: my $color;
993: if ($resource->is_problem() || $resource->is_practice()) {
994: $color = $colormap{$resource->status};
995:
996: if (dueInLessThan24Hours($resource, $part) ||
997: lastTry($resource, $part)) {
998: $color = $hurryUpColor;
999: }
1000: }
1001:
1002: if ($resource->kind() eq "res" &&
1003: ($resource->is_problem() || $resource->is_practice()) &&
1004: !$firstDisplayed) {
1005: if ($color) {$result .= "<font color=\"$color\"><b>"; }
1006: $result .= getDescription($resource, $part);
1007: if ($color) {$result .= "</b></font>"; }
1008: }
1009: if ($resource->is_map() && &advancedUser() && $resource->randompick()) {
1010: $result .= &mt('(randomly select [_1])', $resource->randompick());
1011: }
1012: if ($resource->is_map() && &advancedUser() && $resource->randomorder()) {
1013: $result .= &mt('(randomly ordered)');
1014: }
1015:
1016: # Debugging code
1017: #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) .
1018: # ' - Part: ' . $part;
1019:
1020: $result .= "</td>\n";
1021:
1022: return $result;
1023: }
1024:
1025: # Colors obtained by taking the icons, matching the colors, and
1026: # possibly reducing the Value (HSV) of the color, if it's too bright
1027: # for text, generally by one third or so.
1028: my %statusColors =
1029: (
1030: $resObj->CLOSED => '#000000',
1031: $resObj->OPEN => '#998b13',
1032: $resObj->CORRECT => '#26933f',
1033: $resObj->INCORRECT => '#c48207',
1034: $resObj->ATTEMPTED => '#a87510',
1035: $resObj->ERROR => '#000000'
1036: );
1037: my %statusStrings =
1038: (
1039: $resObj->CLOSED => 'Not yet open',
1040: $resObj->OPEN => 'Open',
1041: $resObj->CORRECT => 'Correct',
1042: $resObj->INCORRECT => 'Incorrect',
1043: $resObj->ATTEMPTED => 'Attempted',
1044: $resObj->ERROR => 'Network Error'
1045: );
1046: my @statuses = ($resObj->CORRECT, $resObj->ATTEMPTED, $resObj->INCORRECT, $resObj->OPEN, $resObj->CLOSED, $resObj->ERROR);
1047:
1048: use Data::Dumper;
1049: sub render_parts_summary_status {
1050: my ($resource, $part, $params) = @_;
1051: if (!$resource->is_problem() && !$resource->contains_problem) { return '<td></td>'; }
1052: if ($params->{showParts}) {
1053: return '<td></td>';
1054: }
1055:
1056: my $td = "<td align='right'>\n";
1057: my $endtd = "</td>\n";
1058: my @probs;
1059:
1060: if ($resource->contains_problem) {
1061: @probs=$resource->retrieveResources($resource,sub { $_[0]->is_problem() },1,0);
1062: } else {
1063: @probs=($resource);
1064: }
1065: my $return;
1066: my %overallstatus;
1067: my $totalParts;
1068: foreach my $resource (@probs) {
1069: # If there is a single part, just show the simple status
1070: if ($resource->singlepart()) {
1071: my $status = $resource->simpleStatus(${$resource->parts}[0]);
1072: $overallstatus{$status}++;
1073: $totalParts++;
1074: next;
1075: }
1076: # Now we can be sure the $part doesn't really matter.
1077: my $statusCount = $resource->simpleStatusCount();
1078: my @counts;
1079: foreach my $status (@statuses) {
1080: # decouple display order from the simpleStatusCount order
1081: my $slot = Apache::lonnavmaps::resource::statusToSlot($status);
1082: if ($statusCount->[$slot]) {
1083: $overallstatus{$status}+=$statusCount->[$slot];
1084: $totalParts+=$statusCount->[$slot];
1085: }
1086: }
1087: }
1088: $return.= $td . $totalParts . ' parts: ';
1089: foreach my $status (@statuses) {
1090: if ($overallstatus{$status}) {
1091: $return.="<font color='" . $statusColors{$status} .
1092: "'>" . $overallstatus{$status} . ' '
1093: . $statusStrings{$status} . "</font>";
1094: }
1095: }
1096: $return.= $endtd;
1097: return $return;
1098: }
1099:
1100: my @preparedColumns = (\&render_resource, \&render_communication_status,
1101: \&render_quick_status, \&render_long_status,
1102: \&render_parts_summary_status);
1103:
1104: sub setDefault {
1105: my ($val, $default) = @_;
1106: if (!defined($val)) { return $default; }
1107: return $val;
1108: }
1109:
1110: sub cmp_title {
1111: my ($atitle,$btitle) = (lc($_[0]->compTitle),lc($_[1]->compTitle));
1112: $atitle=~s/^\s*//;
1113: $btitle=~s/^\s*//;
1114: return $atitle cmp $btitle;
1115: }
1116:
1117: sub render {
1118: my $args = shift;
1119: &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
1120: my $result = '';
1121: # Configure the renderer.
1122: my $cols = $args->{'cols'};
1123: if (!defined($cols)) {
1124: # no columns, no nav maps.
1125: return '';
1126: }
1127: my $navmap;
1128: if (defined($args->{'navmap'})) {
1129: $navmap = $args->{'navmap'};
1130: }
1131:
1132: my $r = $args->{'r'};
1133: my $queryString = $args->{'queryString'};
1134: my $jump = $args->{'jump'};
1135: my $here = $args->{'here'};
1136: my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1137: my $closeAllPages = setDefault($args->{'closeAllPages'}, 0);
1138: my $currentJumpDelta = 2; # change this to change how many resources are displayed
1139: # before the current resource when using #current
1140:
1141: # If we were passed 'here' information, we are not rendering
1142: # after a folder manipulation, and we were not passed an
1143: # iterator, make sure we open the folders to show the "here"
1144: # marker
1145: my $filterHash = {};
1146: # Figure out what we're not displaying
1147: foreach my $item (split(/\,/, $env{"form.filter"})) {
1148: if ($item) {
1149: $filterHash->{$item} = "1";
1150: }
1151: }
1152:
1153: # Filter: Remember filter function and add our own filter: Refuse
1154: # to show hidden resources unless the user can see them.
1155: my $userCanSeeHidden = advancedUser();
1156: my $filterFunc = setDefault($args->{'filterFunc'},
1157: sub {return 1;});
1158: if (!$userCanSeeHidden) {
1159: # Without renaming the filterfunc, the server seems to go into
1160: # an infinite loop
1161: my $oldFilterFunc = $filterFunc;
1162: $filterFunc = sub { my $res = shift; return !$res->randomout() &&
1163: &$oldFilterFunc($res);};
1164: }
1165:
1166: my $condition = 0;
1167: if ($env{'form.condition'}) {
1168: $condition = 1;
1169: }
1170:
1171: if (!$env{'form.folderManip'} && !defined($args->{'iterator'})) {
1172: # Step 1: Check to see if we have a navmap
1173: if (!defined($navmap)) {
1174: $navmap = Apache::lonnavmaps::navmap->new();
1175: if (!defined($navmap)) {
1176: # no londer in course
1177: return '<span class="LC_error">'.&mt('No course selected').'</span><br />
1178: <a href="/adm/roles">'.&mt('Select a course').'</a><br />';
1179: }
1180: }
1181:
1182: # Step two: Locate what kind of here marker is necessary
1183: # Determine where the "here" marker is and where the screen jumps to.
1184:
1185: if ($env{'form.postsymb'} ne '') {
1186: $here = $jump = &Apache::lonnet::symbclean($env{'form.postsymb'});
1187: } elsif ($env{'form.postdata'} ne '') {
1188: # couldn't find a symb, is there a URL?
1189: my $currenturl = $env{'form.postdata'};
1190: #$currenturl=~s/^http\:\/\///;
1191: #$currenturl=~s/^[^\/]+//;
1192:
1193: $here = $jump = &Apache::lonnet::symbread($currenturl);
1194: }
1195: if ($here eq '') {
1196: my $last;
1197: if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1198: &GDBM_READER(),0640)) {
1199: $last=$hash{'last_known'};
1200: untie(%hash);
1201: }
1202: if ($last) { $here = $jump = $last; }
1203: }
1204:
1205: # Step three: Ensure the folders are open
1206: my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
1207: my $curRes;
1208: my $found = 0;
1209:
1210: # We only need to do this if we need to open the maps to show the
1211: # current position. This will change the counter so we can't count
1212: # for the jump marker with this loop.
1213: while ($here && ($curRes = $mapIterator->next()) && !$found) {
1214: if (ref($curRes) && $curRes->symb() eq $here) {
1215: my $mapStack = $mapIterator->getStack();
1216:
1217: # Ensure the parent maps are open
1218: for my $map (@{$mapStack}) {
1219: if ($condition) {
1220: undef $filterHash->{$map->map_pc()};
1221: } else {
1222: $filterHash->{$map->map_pc()} = 1;
1223: }
1224: }
1225: $found = 1;
1226: }
1227: }
1228: }
1229:
1230: if ( !defined($args->{'iterator'}) && $env{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
1231: # If this is a click on a folder or something, we want to preserve the "here"
1232: # from the querystring, and get the new "jump" marker
1233: $here = $env{'form.here'};
1234: $jump = $env{'form.jump'};
1235: }
1236:
1237: my $it = $args->{'iterator'};
1238: if (!defined($it)) {
1239: # Construct a default iterator based on $env{'form.'} information
1240:
1241: # Step 1: Check to see if we have a navmap
1242: if (!defined($navmap)) {
1243: $navmap = Apache::lonnavmaps::navmap->new();
1244: }
1245:
1246: # See if we're being passed a specific map
1247: if ($args->{'iterator_map'}) {
1248: my $map = $args->{'iterator_map'};
1249: $map = $navmap->getResourceByUrl($map);
1250: my $firstResource = $map->map_start();
1251: my $finishResource = $map->map_finish();
1252:
1253: $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
1254: } else {
1255: $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition,undef,$args->{'include_top_level_map'});
1256: }
1257: }
1258:
1259: # (re-)Locate the jump point, if any
1260: # Note this does not take filtering or hidden into account... need
1261: # to be fixed?
1262: my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
1263: my $curRes;
1264: my $foundJump = 0;
1265: my $counter = 0;
1266:
1267: while (($curRes = $mapIterator->next()) && !$foundJump) {
1268: if (ref($curRes)) { $counter++; }
1269:
1270: if (ref($curRes) && $jump eq $curRes->symb()) {
1271:
1272: # This is why we have to use the main iterator instead of the
1273: # potentially faster DFS: The count has to be the same, so
1274: # the order has to be the same, which DFS won't give us.
1275: $args->{'currentJumpIndex'} = $counter;
1276: $foundJump = 1;
1277: }
1278: }
1279:
1280: my $showParts = setDefault($args->{'showParts'}, 1);
1281: my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1282: # keeps track of when the current resource is found,
1283: # so we can back up a few and put the anchor above the
1284: # current resource
1285: my $printKey = $args->{'printKey'};
1286: my $printCloseAll = $args->{'printCloseAll'};
1287: if (!defined($printCloseAll)) { $printCloseAll = 1; }
1288:
1289: # Print key?
1290: if ($printKey) {
1291: $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1292: my $date=localtime;
1293: $result.='<tr><td align="right" valign="bottom">Key: </td>';
1294: my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc");
1295: if ($navmap->{LAST_CHECK}) {
1296: $result .=
1297: '<img src="'.$location.'/chat.gif"> '.&mt('New discussion since').' '.
1298: strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
1299: '</td><td align="center" valign="bottom"> '.
1300: '<img src="'.$location.'/feedback.gif"> '.&mt('New message (click to open)').'<p>'.
1301: '</td>';
1302: } else {
1303: $result .= '<td align="center" valign="bottom"> '.
1304: '<img src="'.$location.'/chat.gif"> '.&mt('Discussions').'</td><td align="center" valign="bottom">'.
1305: ' <img src="'.$location.'/feedback.gif"> '.&mt('New message (click to open)').
1306: '</td>';
1307: }
1308:
1309: $result .= '</tr></table>';
1310: }
1311:
1312: if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
1313: my ($link,$text);
1314: if ($condition) {
1315: $link='"navmaps?condition=0&filter=&'.$queryString.
1316: '&here='.&escape($here).'"';
1317: $text='Close all folders';
1318: } else {
1319: $link='"navmaps?condition=1&filter=&'.$queryString.
1320: '&here='.&escape($here).'"';
1321: $text='Open all folders';
1322: }
1323: if ($args->{'caller'} eq 'navmapsdisplay') {
1324: &add_linkitem($args->{'linkitems'},'changefolder',
1325: 'location.href='.$link,$text);
1326: } else {
1327: $result.='<a href='.$link.'>'.&mt($text).'</a>';
1328: }
1329: $result .= "\n";
1330: }
1331:
1332: # Check for any unread discussions in all resources.
1333: if ($args->{'caller'} eq 'navmapsdisplay') {
1334: &add_linkitem($args->{'linkitems'},'clearbubbles',
1335: 'document.clearbubbles.submit()',
1336: 'Mark all posts read');
1337: my $time=time;
1338: $result .= (<<END);
1339: <form name="clearbubbles" method="post" action="/adm/feedback">
1340: <input type="hidden" name="navurl" value="$ENV{'QUERY_STRING'}" />
1341: <input type="hidden" name="navtime" value="$time" />
1342: END
1343: if ($args->{'sort'} eq 'discussion') {
1344: my $totdisc = 0;
1345: my $haveDisc = '';
1346: my @allres=$navmap->retrieveResources();
1347: foreach my $resource (@allres) {
1348: if ($resource->hasDiscussion()) {
1349: $haveDisc .= $resource->wrap_symb().':';
1350: $totdisc ++;
1351: }
1352: }
1353: if ($totdisc > 0) {
1354: $haveDisc =~ s/:$//;
1355: $result .= (<<END);
1356: <input type="hidden" name="navmaps" value="$haveDisc" />
1357: </form>
1358: END
1359: }
1360: }
1361: $result.='</form>';
1362: }
1363:
1364: if ($args->{'caller'} eq 'navmapsdisplay') {
1365: $result .= '<table><tr><td>'.
1366: &Apache::loncommon::help_open_menu('Navigation Screen','Navigation_Screen',undef,'RAT').'</td>';
1367: if ($env{'environment.remotenavmap'} ne 'on') {
1368: $result .= '<td> </td>';
1369: } else {
1370: $result .= '</tr><tr>';
1371: }
1372: $result.=&show_linkitems($args->{'linkitems'});
1373: if ($args->{'sort_html'}) {
1374: if ($env{'environment.remotenavmap'} ne 'on') {
1375: $result.='<td> </td><td> </td><td> </td>'.
1376: '<td align="right">'.$args->{'sort_html'}.'</td></tr>';
1377: } else {
1378: $result.='</tr><tr><td align="left"><br />'.
1379: $args->{'sort_html'}.'</td></tr>';
1380: }
1381: }
1382: $result .= '</table>';
1383: } elsif ($args->{'sort_html'}) {
1384: $result.=$args->{'sort_html'};
1385: }
1386:
1387: $result .= "<br />\n";
1388: if ($r) {
1389: $r->print($result);
1390: $r->rflush();
1391: $result = "";
1392: }
1393: # End parameter setting
1394:
1395: # Data
1396: $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1397: my $res = "Apache::lonnavmaps::resource";
1398: my %condenseStatuses =
1399: ( $res->NETWORK_FAILURE => 1,
1400: $res->NOTHING_SET => 1,
1401: $res->CORRECT => 1 );
1402: my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1403:
1404: # Shared variables
1405: $args->{'counter'} = 0; # counts the rows
1406: $args->{'indentLevel'} = 0;
1407: $args->{'isNewBranch'} = 0;
1408: $args->{'condensed'} = 0;
1409: my $location=
1410: &Apache::loncommon::lonhttpdurl("/adm/lonIcons/whitespace1.gif");
1411: $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='$location' width='25' height='1' alt=' ' border='0' />");
1412: $args->{'displayedHereMarker'} = 0;
1413:
1414: # If we're suppressing empty sequences, look for them here. Use DFS for speed,
1415: # since structure actually doesn't matter, except what map has what resources.
1416: if ($args->{'suppressEmptySequences'}) {
1417: my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
1418: $it->{FIRST_RESOURCE},
1419: $it->{FINISH_RESOURCE},
1420: {}, undef, 1);
1421: my $depth = 0;
1422: $dfsit->next();
1423: my $curRes = $dfsit->next();
1424: while ($depth > -1) {
1425: if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
1426: if ($curRes == $dfsit->END_MAP()) { $depth--; }
1427:
1428: if (ref($curRes)) {
1429: # Parallel pre-processing: Do sequences have non-filtered-out children?
1430: if ($curRes->is_map()) {
1431: $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
1432: # Sequences themselves do not count as visible children,
1433: # unless those sequences also have visible children.
1434: # This means if a sequence appears, there's a "promise"
1435: # that there's something under it if you open it, somewhere.
1436: } else {
1437: # Not a sequence: if it's filtered, ignore it, otherwise
1438: # rise up the stack and mark the sequences as having children
1439: if (&$filterFunc($curRes)) {
1440: for my $sequence (@{$dfsit->getStack()}) {
1441: $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
1442: }
1443: }
1444: }
1445: }
1446: } continue {
1447: $curRes = $dfsit->next();
1448: }
1449: }
1450:
1451: my $displayedJumpMarker = 0;
1452: # Set up iteration.
1453: my $now = time();
1454: my $in24Hours = $now + 24 * 60 * 60;
1455: my $rownum = 0;
1456:
1457: # export "here" marker information
1458: $args->{'here'} = $here;
1459:
1460: $args->{'indentLevel'} = -1; # first BEGIN_MAP takes this to 0
1461: my @resources;
1462: my $code='';# sub { !(shift->is_map();) };
1463: if ($args->{'sort'} eq 'title') {
1464: my $oldFilterFunc = $filterFunc;
1465: my $filterFunc=
1466: sub {
1467: my ($res)=@_;
1468: if ($res->is_map()) { return 0;}
1469: return &$oldFilterFunc($res);
1470: };
1471: @resources=$navmap->retrieveResources(undef,$filterFunc);
1472: @resources= sort { &cmp_title($a,$b) } @resources;
1473: } elsif ($args->{'sort'} eq 'duedate') {
1474: my $oldFilterFunc = $filterFunc;
1475: my $filterFunc=
1476: sub {
1477: my ($res)=@_;
1478: if (!$res->is_problem()) { return 0;}
1479: return &$oldFilterFunc($res);
1480: };
1481: @resources=$navmap->retrieveResources(undef,$filterFunc);
1482: @resources= sort {
1483: if ($a->duedate ne $b->duedate) {
1484: return $a->duedate cmp $b->duedate;
1485: }
1486: my $value=&cmp_title($a,$b);
1487: return $value;
1488: } @resources;
1489: } elsif ($args->{'sort'} eq 'discussion') {
1490: my $oldFilterFunc = $filterFunc;
1491: my $filterFunc=
1492: sub {
1493: my ($res)=@_;
1494: if (!$res->hasDiscussion() &&
1495: !$res->getFeedback() &&
1496: !$res->getErrors()) { return 0;}
1497: return &$oldFilterFunc($res);
1498: };
1499: @resources=$navmap->retrieveResources(undef,$filterFunc);
1500: @resources= sort { &cmp_title($a,$b) } @resources;
1501: } else {
1502: #unknow sort mechanism or default
1503: undef($args->{'sort'});
1504: }
1505:
1506:
1507: while (1) {
1508: if ($args->{'sort'}) {
1509: $curRes = shift(@resources);
1510: } else {
1511: $curRes = $it->next($closeAllPages);
1512: }
1513: if (!$curRes) { last; }
1514:
1515: # Maintain indentation level.
1516: if ($curRes == $it->BEGIN_MAP() ||
1517: $curRes == $it->BEGIN_BRANCH() ) {
1518: $args->{'indentLevel'}++;
1519: }
1520: if ($curRes == $it->END_MAP() ||
1521: $curRes == $it->END_BRANCH() ) {
1522: $args->{'indentLevel'}--;
1523: }
1524: # Notice new branches
1525: if ($curRes == $it->BEGIN_BRANCH()) {
1526: $args->{'isNewBranch'} = 1;
1527: }
1528:
1529: # If this isn't an actual resource, continue on
1530: if (!ref($curRes)) {
1531: next;
1532: }
1533:
1534: # If this has been filtered out, continue on
1535: if (!(&$filterFunc($curRes))) {
1536: $args->{'isNewBranch'} = 0; # Don't falsely remember this
1537: next;
1538: }
1539:
1540: # If this is an empty sequence and we're filtering them, continue on
1541: if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
1542: !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
1543: next;
1544: }
1545:
1546: # If we're suppressing navmaps and this is a navmap, continue on
1547: if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
1548: next;
1549: }
1550:
1551: $args->{'counter'}++;
1552:
1553: # Does it have multiple parts?
1554: $args->{'multipart'} = 0;
1555: $args->{'condensed'} = 0;
1556: my @parts;
1557:
1558: # Decide what parts to show.
1559: if ($curRes->is_problem() && $showParts) {
1560: @parts = @{$curRes->parts()};
1561: $args->{'multipart'} = $curRes->multipart();
1562:
1563: if ($condenseParts) { # do the condensation
1564: if (!$args->{'condensed'}) {
1565: # Decide whether to condense based on similarity
1566: my $status = $curRes->status($parts[0]);
1567: my $due = $curRes->duedate($parts[0]);
1568: my $open = $curRes->opendate($parts[0]);
1569: my $statusAllSame = 1;
1570: my $dueAllSame = 1;
1571: my $openAllSame = 1;
1572: for (my $i = 1; $i < scalar(@parts); $i++) {
1573: if ($curRes->status($parts[$i]) != $status){
1574: $statusAllSame = 0;
1575: }
1576: if ($curRes->duedate($parts[$i]) != $due ) {
1577: $dueAllSame = 0;
1578: }
1579: if ($curRes->opendate($parts[$i]) != $open) {
1580: $openAllSame = 0;
1581: }
1582: }
1583: # $*allSame is true if all the statuses were
1584: # the same. Now, if they are all the same and
1585: # match one of the statuses to condense, or they
1586: # are all open with the same due date, or they are
1587: # all OPEN_LATER with the same open date, display the
1588: # status of the first non-zero part (to get the 'correct'
1589: # status right, since 0 is never 'correct' or 'open').
1590: if (($statusAllSame && defined($condenseStatuses{$status})) ||
1591: ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
1592: ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1593: @parts = ($parts[0]);
1594: $args->{'condensed'} = 1;
1595: }
1596: }
1597: # Multipart problem with one part: always "condense" (happens
1598: # to match the desirable behavior)
1599: if ($curRes->countParts() == 1) {
1600: @parts = ($parts[0]);
1601: $args->{'condensed'} = 1;
1602: }
1603: }
1604: }
1605:
1606: # If the multipart problem was condensed, "forget" it was multipart
1607: if (scalar(@parts) == 1) {
1608: $args->{'multipart'} = 0;
1609: } else {
1610: # Add part 0 so we display it correctly.
1611: unshift @parts, '0';
1612: }
1613:
1614: {
1615: my ($src,$symb,$anchor,$stack);
1616: if ($args->{'sort'}) {
1617: my $it = $navmap->getIterator(undef, undef, undef, 1);
1618: while ( my $res=$it->next()) {
1619: if (ref($res) &&
1620: $res->symb() eq $curRes->symb()) { last; }
1621: }
1622: $stack=$it->getStack();
1623: } else {
1624: $stack=$it->getStack();
1625: }
1626: ($src,$symb,$anchor)=getLinkForResource($stack);
1627: if (defined($anchor)) { $anchor='#'.$anchor; }
1628: my $srcHasQuestion = $src =~ /\?/;
1629: $args->{"resourceLink"} = $src.
1630: ($srcHasQuestion?'&':'?') .
1631: 'symb=' . &escape($symb).$anchor;
1632: }
1633: # Now, we've decided what parts to show. Loop through them and
1634: # show them.
1635: foreach my $part (@parts) {
1636: $rownum ++;
1637: my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
1638:
1639: $result .= " <tr bgcolor='$backgroundColor'>\n";
1640:
1641: # Set up some data about the parts that the cols might want
1642: my $filter = $it->{FILTER};
1643:
1644: # Now, display each column.
1645: foreach my $col (@$cols) {
1646: my $colHTML = '';
1647: if (ref($col)) {
1648: $colHTML .= &$col($curRes, $part, $args);
1649: } else {
1650: $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
1651: }
1652:
1653: # If this is the first column and it's time to print
1654: # the anchor, do so
1655: if ($col == $cols->[0] &&
1656: $args->{'counter'} == $args->{'currentJumpIndex'} -
1657: $currentJumpDelta) {
1658: # Jam the anchor after the <td> tag;
1659: # necessary for valid HTML (which Mozilla requires)
1660: $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1661: $displayedJumpMarker = 1;
1662: }
1663: $result .= $colHTML . "\n";
1664: }
1665: $result .= " </tr>\n";
1666: $args->{'isNewBranch'} = 0;
1667: }
1668:
1669: if ($r && $rownum % 20 == 0) {
1670: $r->print($result);
1671: $result = "";
1672: $r->rflush();
1673: }
1674: } continue {
1675: if ($r) {
1676: # If we have the connection, make sure the user is still connected
1677: my $c = $r->connection;
1678: if ($c->aborted()) {
1679: # Who cares what we do, nobody will see it anyhow.
1680: return '';
1681: }
1682: }
1683: }
1684:
1685: # Print out the part that jumps to #curloc if it exists
1686: # delay needed because the browser is processing the jump before
1687: # it finishes rendering, so it goes to the wrong place!
1688: # onload might be better, but this routine has no access to that.
1689: # On mozilla, the 0-millisecond timeout seems to prevent this;
1690: # it's quite likely this might fix other browsers, too, and
1691: # certainly won't hurt anything.
1692: if ($displayedJumpMarker) {
1693: $result .= "
1694: <script>
1695: if (location.href.indexOf('#curloc')==-1) {
1696: setTimeout(\"location += '#curloc';\", 0)
1697: }
1698: </script>";
1699: }
1700:
1701: $result .= "</table>";
1702:
1703: if ($r) {
1704: $r->print($result);
1705: $result = "";
1706: $r->rflush();
1707: }
1708:
1709: return $result;
1710: }
1711:
1712: sub add_linkitem {
1713: my ($linkitems,$name,$cmd,$text)=@_;
1714: $$linkitems{$name}{'cmd'}=$cmd;
1715: $$linkitems{$name}{'text'}=&mt($text);
1716: }
1717:
1718: sub show_linkitems {
1719: my ($linkitems)=@_;
1720: my @linkorder = ("blank","launchnav","closenav","firsthomework",
1721: "everything","uncompleted","changefolder","clearbubbles");
1722:
1723: my $result .= (<<ENDBLOCK);
1724: <td align="left">
1725: <script type="text/javascript">
1726: function changeNavDisplay () {
1727: var navchoice = document.linkitems.toplink[document.linkitems.toplink.selectedIndex].value;
1728: ENDBLOCK
1729: foreach my $link (@linkorder) {
1730: $result.= "if (navchoice == '$link') {".
1731: $linkitems->{$link}{'cmd'}."}\n";
1732: }
1733: $result.='}
1734: </script>
1735: <form name="linkitems" method="post">
1736: <nobr><select name="toplink">'."\n";
1737: foreach my $link (@linkorder) {
1738: if (defined($linkitems->{$link})) {
1739: if ($linkitems->{$link}{'text'} ne '') {
1740: $result .= ' <option value="'.$link.'">'.
1741: $linkitems->{$link}{'text'}."</option>\n";
1742: }
1743: }
1744: }
1745: $result .= '</select> <input type="button" name="chgnav"
1746: value="Go" onClick="javascript:changeNavDisplay()" />
1747: </nobr></form></td>'."\n";
1748:
1749: return $result;
1750: }
1751:
1752: 1;
1753:
1754: package Apache::lonnavmaps::navmap;
1755:
1756: =pod
1757:
1758: =head1 Object: Apache::lonnavmaps::navmap
1759:
1760: =head2 Overview
1761:
1762: The navmap object's job is to provide access to the resources
1763: in the course as Apache::lonnavmaps::resource objects, and to
1764: query and manage the relationship between those resource objects.
1765:
1766: Generally, you'll use the navmap object in one of three basic ways.
1767: In order of increasing complexity and power:
1768:
1769: =over 4
1770:
1771: =item * C<$navmap-E<gt>getByX>, where X is B<Id>, B<Symb> or B<MapPc> and getResourceByUrl. This provides
1772: various ways to obtain resource objects, based on various identifiers.
1773: Use this when you want to request information about one object or
1774: a handful of resources you already know the identities of, from some
1775: other source. For more about Ids, Symbs, and MapPcs, see the
1776: Resource documentation. Note that Url should be a B<last resort>,
1777: not your first choice; it only really works when there is only one
1778: instance of the resource in the course, which only applies to
1779: maps, and even that may change in the future (see the B<getResourceByUrl>
1780: documentation for more details.)
1781:
1782: =item * C<my @resources = $navmap-E<gt>retrieveResources(args)>. This
1783: retrieves resources matching some criterion and returns them
1784: in a flat array, with no structure information. Use this when
1785: you are manipulating a series of resources, based on what map
1786: the are in, but do not care about branching, or exactly how
1787: the maps and resources are related. This is the most common case.
1788:
1789: =item * C<$it = $navmap-E<gt>getIterator(args)>. This allows you traverse
1790: the course's navmap in various ways without writing the traversal
1791: code yourself. See iterator documentation below. Use this when
1792: you need to know absolutely everything about the course, including
1793: branches and the precise relationship between maps and resources.
1794:
1795: =back
1796:
1797: =head2 Creation And Destruction
1798:
1799: To create a navmap object, use the following function:
1800:
1801: =over 4
1802:
1803: =item * B<Apache::lonnavmaps::navmap-E<gt>new>():
1804:
1805: Creates a new navmap object. Returns the navmap object if this is
1806: successful, or B<undef> if not.
1807:
1808: =back
1809:
1810: =head2 Methods
1811:
1812: =over 4
1813:
1814: =item * B<getIterator>(first, finish, filter, condition):
1815:
1816: See iterator documentation below.
1817:
1818: =cut
1819:
1820: use strict;
1821: use GDBM_File;
1822: use Apache::lonnet;
1823: use LONCAPA;
1824:
1825: sub new {
1826: # magic invocation to create a class instance
1827: my $proto = shift;
1828: my $class = ref($proto) || $proto;
1829: my $self = {};
1830:
1831: # Resource cache stores navmap resources as we reference them. We generate
1832: # them on-demand so we don't pay for creating resources unless we use them.
1833: $self->{RESOURCE_CACHE} = {};
1834:
1835: # Network failure flag, if we accessed the course or user opt and
1836: # failed
1837: $self->{NETWORK_FAILURE} = 0;
1838:
1839: # tie the nav hash
1840:
1841: my %navmaphash;
1842: my %parmhash;
1843: my $courseFn = $env{"request.course.fn"};
1844: if (!(tie(%navmaphash, 'GDBM_File', "${courseFn}.db",
1845: &GDBM_READER(), 0640))) {
1846: return undef;
1847: }
1848:
1849: if (!(tie(%parmhash, 'GDBM_File', "${courseFn}_parms.db",
1850: &GDBM_READER(), 0640)))
1851: {
1852: untie %{$self->{PARM_HASH}};
1853: return undef;
1854: }
1855:
1856: $self->{NAV_HASH} = \%navmaphash;
1857: $self->{PARM_HASH} = \%parmhash;
1858: $self->{PARM_CACHE} = {};
1859:
1860: bless($self);
1861:
1862: return $self;
1863: }
1864:
1865: sub generate_course_user_opt {
1866: my $self = shift;
1867: if ($self->{COURSE_USER_OPT_GENERATED}) { return; }
1868:
1869: my $uname=$env{'user.name'};
1870: my $udom=$env{'user.domain'};
1871: my $cid=$env{'request.course.id'};
1872: my $cdom=$env{'course.'.$cid.'.domain'};
1873: my $cnum=$env{'course.'.$cid.'.num'};
1874:
1875: # ------------------------------------------------- Get coursedata (if present)
1876: my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
1877: # Check for network failure
1878: if (!ref($courseopt)) {
1879: if ( $courseopt =~ /no.such.host/i || $courseopt =~ /con_lost/i) {
1880: $self->{NETWORK_FAILURE} = 1;
1881: }
1882: undef($courseopt);
1883: }
1884:
1885: # --------------------------------------------------- Get userdata (if present)
1886:
1887: my $useropt=&Apache::lonnet::get_userresdata($uname,$udom);
1888: # Check for network failure
1889: if (!ref($useropt)) {
1890: if ( $useropt =~ /no.such.host/i || $useropt =~ /con_lost/i) {
1891: $self->{NETWORK_FAILURE} = 1;
1892: }
1893: undef($useropt);
1894: }
1895:
1896: $self->{COURSE_OPT} = $courseopt;
1897: $self->{USER_OPT} = $useropt;
1898:
1899: $self->{COURSE_USER_OPT_GENERATED} = 1;
1900:
1901: return;
1902: }
1903:
1904: sub generate_email_discuss_status {
1905: my $self = shift;
1906: my $symb = shift;
1907: if ($self->{EMAIL_DISCUSS_GENERATED}) { return; }
1908:
1909: my $cid=$env{'request.course.id'};
1910: my $cdom=$env{'course.'.$cid.'.domain'};
1911: my $cnum=$env{'course.'.$cid.'.num'};
1912:
1913: my %emailstatus = &Apache::lonnet::dump('email_status');
1914: my $logoutTime = $emailstatus{'logout'};
1915: my $courseLeaveTime = $emailstatus{'logout_'.$env{'request.course.id'}};
1916: $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
1917: $courseLeaveTime : $logoutTime);
1918: my %discussiontime = &Apache::lonnet::dump('discussiontimes',
1919: $cdom, $cnum);
1920: my %lastread = &Apache::lonnet::dump('nohist_'.$cid.'_discuss',
1921: $env{'user.domain'},$env{'user.name'},'lastread');
1922: my %lastreadtime = ();
1923: foreach my $key (keys %lastread) {
1924: my $shortkey = $key;
1925: $shortkey =~ s/_lastread$//;
1926: $lastreadtime{$shortkey} = $lastread{$key};
1927: }
1928:
1929: my %feedback=();
1930: my %error=();
1931: my @keys = &Apache::lonnet::getkeys('nohist_email',$env{'user.domain'},
1932: $env{'user.name'});
1933:
1934: foreach my $msgid (@keys) {
1935: if ((!$emailstatus{$msgid}) || ($emailstatus{$msgid} eq 'new')) {
1936: my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
1937: $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
1938: &Apache::lonenc::check_decrypt(\$symb);
1939: if (($fromcid ne '') && ($fromcid ne $cid)) {
1940: next;
1941: }
1942: if (defined($symb)) {
1943: if (defined($error) && $error == 1) {
1944: $error{$symb}.=','.$msgid;
1945: } else {
1946: $feedback{$symb}.=','.$msgid;
1947: }
1948: } else {
1949: my $plain=
1950: &LONCAPA::unescape(&LONCAPA::unescape($msgid));
1951: if ($plain=~/ \[([^\]]+)\]\:/) {
1952: my $url=$1;
1953: if ($plain=~/\:Error \[/) {
1954: $error{$url}.=','.$msgid;
1955: } else {
1956: $feedback{$url}.=','.$msgid;
1957: }
1958: }
1959: }
1960: }
1961: }
1962:
1963: #symbs of resources that have feedbacks (will be urls pre-2.3)
1964: $self->{FEEDBACK} = \%feedback;
1965: #or errors (will be urls pre 2.3)
1966: $self->{ERROR_MSG} = \%error;
1967: $self->{DISCUSSION_TIME} = \%discussiontime;
1968: $self->{EMAIL_STATUS} = \%emailstatus;
1969: $self->{LAST_READ} = \%lastreadtime;
1970:
1971: $self->{EMAIL_DISCUSS_GENERATED} = 1;
1972: }
1973:
1974: sub get_user_data {
1975: my $self = shift;
1976: if ($self->{RETRIEVED_USER_DATA}) { return; }
1977:
1978: # Retrieve performance data on problems
1979: my %student_data = Apache::lonnet::currentdump($env{'request.course.id'},
1980: $env{'user.domain'},
1981: $env{'user.name'});
1982: $self->{STUDENT_DATA} = \%student_data;
1983:
1984: $self->{RETRIEVED_USER_DATA} = 1;
1985: }
1986:
1987: sub get_discussion_data {
1988: my $self = shift;
1989: if ($self->{RETRIEVED_DISCUSSION_DATA}) {
1990: return $self->{DISCUSSION_DATA};
1991: }
1992:
1993: $self->generate_email_discuss_status();
1994:
1995: my $cid=$env{'request.course.id'};
1996: my $cdom=$env{'course.'.$cid.'.domain'};
1997: my $cnum=$env{'course.'.$cid.'.num'};
1998: # Retrieve discussion data for resources in course
1999: my %discussion_data = &Apache::lonnet::dumpstore($cid,$cdom,$cnum);
2000:
2001:
2002: $self->{DISCUSSION_DATA} = \%discussion_data;
2003: $self->{RETRIEVED_DISCUSSION_DATA} = 1;
2004: return $self->{DISCUSSION_DATA};
2005: }
2006:
2007:
2008: # Internal function: Takes a key to look up in the nav hash and implements internal
2009: # memory caching of that key.
2010: sub navhash {
2011: my $self = shift; my $key = shift;
2012: return $self->{NAV_HASH}->{$key};
2013: }
2014:
2015: =pod
2016:
2017: =item * B<courseMapDefined>(): Returns true if the course map is defined,
2018: false otherwise. Undefined course maps indicate an error somewhere in
2019: LON-CAPA, and you will not be able to proceed with using the navmap.
2020: See the B<NAV> screen for an example of using this.
2021:
2022: =cut
2023:
2024: # Checks to see if coursemap is defined, matching test in old lonnavmaps
2025: sub courseMapDefined {
2026: my $self = shift;
2027: my $uri = &Apache::lonnet::clutter($env{'request.course.uri'});
2028:
2029: my $firstres = $self->navhash("map_start_$uri");
2030: my $lastres = $self->navhash("map_finish_$uri");
2031: return $firstres && $lastres;
2032: }
2033:
2034: sub getIterator {
2035: my $self = shift;
2036: my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
2037: shift, undef, shift,
2038: shift, shift);
2039: return $iterator;
2040: }
2041:
2042: # Private method: Does the given resource (as a symb string) have
2043: # current discussion? Returns 0 if chat/mail data not extracted.
2044: sub hasDiscussion {
2045: my $self = shift;
2046: my $symb = shift;
2047: $self->generate_email_discuss_status();
2048:
2049: if (!defined($self->{DISCUSSION_TIME})) { return 0; }
2050:
2051: #return defined($self->{DISCUSSION_TIME}->{$symb});
2052:
2053: # backward compatibility (bulletin boards used to be 'wrapped')
2054: my $ressymb = $self->wrap_symb($symb);
2055: if ( defined ( $self->{LAST_READ}->{$ressymb} ) ) {
2056: return $self->{DISCUSSION_TIME}->{$ressymb} > $self->{LAST_READ}->{$ressymb};
2057: } else {
2058: # return $self->{DISCUSSION_TIME}->{$ressymb} > $self->{LAST_CHECK}; # v.1.1 behavior
2059: return $self->{DISCUSSION_TIME}->{$ressymb} > 0; # in 1.2 will display speech bubble icons for all items with posts until marked as read (even if read in v 1.1).
2060: }
2061: }
2062:
2063: sub last_post_time {
2064: my $self = shift;
2065: my $symb = shift;
2066: my $ressymb = $self->wrap_symb($symb);
2067: return $self->{DISCUSSION_TIME}->{$ressymb};
2068: }
2069:
2070: sub discussion_info {
2071: my $self = shift;
2072: my $symb = shift;
2073: my $filter = shift;
2074:
2075: $self->get_discussion_data();
2076:
2077: my $ressymb = $self->wrap_symb($symb);
2078: # keys used to store bulletinboard postings use 'unwrapped' symb.
2079: my $discsymb = &escape($self->unwrap_symb($ressymb));
2080: my $version = $self->{DISCUSSION_DATA}{'version:'.$discsymb};
2081: if (!$version) { return; }
2082:
2083: my $prevread = $self->{LAST_READ}{$ressymb};
2084:
2085: my $count = 0;
2086: my $hiddenflag = 0;
2087: my $deletedflag = 0;
2088: my ($hidden,$deleted,%info);
2089:
2090: for (my $id=$version; $id>0; $id--) {
2091: my $vkeys=$self->{DISCUSSION_DATA}{$id.':keys:'.$discsymb};
2092: my @keys=split(/:/,$vkeys);
2093: if (grep(/^hidden$/ ,@keys)) {
2094: if (!$hiddenflag) {
2095: $hidden = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':hidden'};
2096: $hiddenflag = 1;
2097: }
2098: } elsif (grep(/^deleted$/,@keys)) {
2099: if (!$deletedflag) {
2100: $deleted = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':deleted'};
2101: $deletedflag = 1;
2102: }
2103: } else {
2104: if (($hidden !~/\.$id\./) && ($deleted !~/\.$id\./)) {
2105: if ($filter eq 'unread') {
2106: if ($prevread >= $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'}) {
2107: next;
2108: }
2109: }
2110: $count++;
2111: $info{$count}{'subject'} =
2112: $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':subject'};
2113: $info{$count}{'id'} = $id;
2114: $info{$count}{'timestamp'} = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'};
2115: }
2116: }
2117: }
2118: if (wantarray) {
2119: return ($count,%info);
2120: }
2121: return $count;
2122: }
2123:
2124: sub wrap_symb {
2125: my $self = shift;
2126: my $symb = shift;
2127: if ($symb =~ m-___(adm/[^/]+/[^/]+/)(\d+)(/bulletinboard)$-) {
2128: unless ($symb =~ m|adm/wrapper/adm|) {
2129: $symb = 'bulletin___'.$2.'___adm/wrapper/'.$1.$2.$3;
2130: }
2131: }
2132: return $symb;
2133: }
2134:
2135: sub unwrap_symb {
2136: my $self = shift;
2137: my $ressymb = shift;
2138: my $discsymb = $ressymb;
2139: if ($ressymb =~ m-^(bulletin___\d+___)adm/wrapper/(adm/[^/]+/[^/]+/\d+/bulletinboard)$-) {
2140: $discsymb = $1.$2;
2141: }
2142: return $discsymb;
2143: }
2144:
2145: # Private method: Does the given resource (as a symb string) have
2146: # current feedback? Returns the string in the feedback hash, which
2147: # will be false if it does not exist.
2148:
2149: sub getFeedback {
2150: my $self = shift;
2151: my $symb = shift;
2152: my $source = shift;
2153:
2154: $self->generate_email_discuss_status();
2155:
2156: if (!defined($self->{FEEDBACK})) { return ""; }
2157:
2158: my $feedback;
2159: if ($self->{FEEDBACK}->{$symb}) {
2160: $feedback = $self->{FEEDBACK}->{$symb};
2161: if ($self->{FEEDBACK}->{$source}) {
2162: $feedback .= ','.$self->{FEEDBACK}->{$source};
2163: }
2164: } else {
2165: if ($self->{FEEDBACK}->{$source}) {
2166: $feedback = $self->{FEEDBACK}->{$source};
2167: }
2168: }
2169: return $feedback;
2170: }
2171:
2172: # Private method: Get the errors for that resource (by source).
2173: sub getErrors {
2174: my $self = shift;
2175: my $symb = shift;
2176: my $src = shift;
2177:
2178: $self->generate_email_discuss_status();
2179:
2180: if (!defined($self->{ERROR_MSG})) { return ""; }
2181:
2182: my $errors;
2183: if ($self->{ERROR_MSG}->{$symb}) {
2184: $errors = $self->{ERROR_MSG}->{$symb};
2185: if ($self->{ERROR_MSG}->{$src}) {
2186: $errors .= ','.$self->{ERROR_MSG}->{$src};
2187: }
2188: } else {
2189: if ($self->{ERROR_MSG}->{$src}) {
2190: $errors = $self->{ERROR_MSG}->{$src};
2191: }
2192: }
2193: return $errors;
2194: }
2195:
2196: =pod
2197:
2198: =item * B<getById>(id):
2199:
2200: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
2201: object for that resource. This method, or other methods that use it
2202: (as in the resource object) is the only proper way to obtain a
2203: resource object.
2204:
2205: =item * B<getBySymb>(symb):
2206:
2207: Based on the symb of the resource, get a resource object for that
2208: resource. This is one of the proper ways to get a resource object.
2209:
2210: =item * B<getMapByMapPc>(map_pc):
2211:
2212: Based on the map_pc of the resource, get a resource object for
2213: the given map. This is one of the proper ways to get a resource object.
2214:
2215: =cut
2216:
2217: # The strategy here is to cache the resource objects, and only construct them
2218: # as we use them. The real point is to prevent reading any more from the tied
2219: # hash than we have to, which should hopefully alleviate speed problems.
2220:
2221: sub getById {
2222: my $self = shift;
2223: my $id = shift;
2224:
2225: if (defined ($self->{RESOURCE_CACHE}->{$id}))
2226: {
2227: return $self->{RESOURCE_CACHE}->{$id};
2228: }
2229:
2230: # resource handles inserting itself into cache.
2231: # Not clear why the quotes are necessary, but as of this
2232: # writing it doesn't work without them.
2233: return "Apache::lonnavmaps::resource"->new($self, $id);
2234: }
2235:
2236: sub getBySymb {
2237: my $self = shift;
2238: my $symb = shift;
2239:
2240: my ($mapUrl, $id, $filename) = &Apache::lonnet::decode_symb($symb);
2241: my $map = $self->getResourceByUrl($mapUrl);
2242: my $returnvalue = undef;
2243: if (ref($map)) {
2244: $returnvalue = $self->getById($map->map_pc() .'.'.$id);
2245: }
2246: return $returnvalue;
2247: }
2248:
2249: sub getByMapPc {
2250: my $self = shift;
2251: my $map_pc = shift;
2252: my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
2253: $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
2254: return $self->getById($map_id);
2255: }
2256:
2257: =pod
2258:
2259: =item * B<firstResource>():
2260:
2261: Returns a resource object reference corresponding to the first
2262: resource in the navmap.
2263:
2264: =cut
2265:
2266: sub firstResource {
2267: my $self = shift;
2268: my $firstResource = $self->navhash('map_start_' .
2269: &Apache::lonnet::clutter($env{'request.course.uri'}));
2270: return $self->getById($firstResource);
2271: }
2272:
2273: =pod
2274:
2275: =item * B<finishResource>():
2276:
2277: Returns a resource object reference corresponding to the last resource
2278: in the navmap.
2279:
2280: =cut
2281:
2282: sub finishResource {
2283: my $self = shift;
2284: my $firstResource = $self->navhash('map_finish_' .
2285: &Apache::lonnet::clutter($env{'request.course.uri'}));
2286: return $self->getById($firstResource);
2287: }
2288:
2289: # Parmval reads the parm hash and cascades the lookups. parmval_real does
2290: # the actual lookup; parmval caches the results.
2291: sub parmval {
2292: my $self = shift;
2293: my ($what,$symb,$recurse)=@_;
2294: my $hashkey = $what."|||".$symb;
2295:
2296: if (defined($self->{PARM_CACHE}->{$hashkey})) {
2297: return $self->{PARM_CACHE}->{$hashkey};
2298: }
2299:
2300: my $result = $self->parmval_real($what, $symb, $recurse);
2301: $self->{PARM_CACHE}->{$hashkey} = $result;
2302: return $result;
2303: }
2304:
2305: sub parmval_real {
2306: my $self = shift;
2307: my ($what,$symb,$recurse) = @_;
2308:
2309: # Make sure the {USER_OPT} and {COURSE_OPT} hashes are populated
2310: $self->generate_course_user_opt();
2311:
2312: my $cid=$env{'request.course.id'};
2313: my $csec=$env{'request.course.sec'};
2314: my $cgroup='';
2315: my @cgrps=split(/:/,$env{'request.course.groups'});
2316: if (@cgrps > 0) {
2317: @cgrps = sort(@cgrps);
2318: $cgroup = $cgrps[0];
2319: }
2320: my $uname=$env{'user.name'};
2321: my $udom=$env{'user.domain'};
2322:
2323: unless ($symb) { return ''; }
2324: my $result='';
2325:
2326: my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
2327: $mapname = &Apache::lonnet::deversion($mapname);
2328: # ----------------------------------------------------- Cascading lookup scheme
2329: my $rwhat=$what;
2330: $what=~s/^parameter\_//;
2331: $what=~s/\_/\./;
2332:
2333: my $symbparm=$symb.'.'.$what;
2334: my $mapparm=$mapname.'___(all).'.$what;
2335: my $usercourseprefix=$cid;
2336:
2337: my $grplevel=$usercourseprefix.'.['.$cgroup.'].'.$what;
2338: my $grplevelr=$usercourseprefix.'.['.$cgroup.'].'.$symbparm;
2339: my $grplevelm=$usercourseprefix.'.['.$cgroup.'].'.$mapparm;
2340:
2341: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
2342: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
2343: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
2344:
2345: my $courselevel= $usercourseprefix.'.'.$what;
2346: my $courselevelr=$usercourseprefix.'.'.$symbparm;
2347: my $courselevelm=$usercourseprefix.'.'.$mapparm;
2348:
2349: my $useropt = $self->{USER_OPT};
2350: my $courseopt = $self->{COURSE_OPT};
2351: my $parmhash = $self->{PARM_HASH};
2352:
2353: # ---------------------------------------------------------- first, check user
2354: if ($uname and defined($useropt)) {
2355: if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
2356: if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
2357: if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
2358: }
2359:
2360: # ------------------------------------------------------- second, check course
2361: if ($cgroup ne '' and defined($courseopt)) {
2362: if (defined($$courseopt{$grplevelr})) { return $$courseopt{$grplevelr}; }
2363: if (defined($$courseopt{$grplevelm})) { return $$courseopt{$grplevelm}; }
2364: if (defined($$courseopt{$grplevel})) { return $$courseopt{$grplevel}; }
2365: }
2366:
2367: if ($csec and defined($courseopt)) {
2368: if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
2369: if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
2370: if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
2371: }
2372:
2373: if (defined($courseopt)) {
2374: if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
2375: }
2376:
2377: # ----------------------------------------------------- third, check map parms
2378:
2379: my $thisparm=$$parmhash{$symbparm};
2380: if (defined($thisparm)) { return $thisparm; }
2381:
2382: # ----------------------------------------------------- fourth , check default
2383:
2384: my $meta_rwhat=$rwhat;
2385: $meta_rwhat=~s/\./_/g;
2386: my $default=&Apache::lonnet::metadata($fn,$meta_rwhat);
2387: if (defined($default)) { return $default}
2388: $default=&Apache::lonnet::metadata($fn,'parameter_'.$meta_rwhat);
2389: if (defined($default)) { return $default}
2390:
2391: # --------------------------------------------------- fifth, check more course
2392: if (defined($courseopt)) {
2393: if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
2394: if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
2395: }
2396:
2397: # --------------------------------------------------- sixth , cascade up parts
2398:
2399: my ($space,@qualifier)=split(/\./,$rwhat);
2400: my $qualifier=join('.',@qualifier);
2401: unless ($space eq '0') {
2402: my @parts=split(/_/,$space);
2403: my $id=pop(@parts);
2404: my $part=join('_',@parts);
2405: if ($part eq '') { $part='0'; }
2406: my $partgeneral=$self->parmval($part.".$qualifier",$symb,1);
2407: if (defined($partgeneral)) { return $partgeneral; }
2408: }
2409: if ($recurse) { return undef; }
2410: my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$rwhat);
2411: if (defined($pack_def)) { return $pack_def; }
2412: return '';
2413: }
2414:
2415: =pod
2416:
2417: =item * B<getResourceByUrl>(url,multiple):
2418:
2419: Retrieves a resource object by URL of the resource, unless the optional
2420: multiple parameter is included in which case an array of resource
2421: objects is returned. If passed a resource object, it will simply return
2422: it, so it is safe to use this method in code like
2423: "$res = $navmap->getResourceByUrl($res)"
2424: if you're not sure if $res is already an object, or just a URL. If the
2425: resource appears multiple times in the course, only the first instance
2426: will be returned (useful for maps), unless the multiple parameter has
2427: been included, in which case all instances are returned in an array.
2428:
2429: =item * B<retrieveResources>(map, filterFunc, recursive, bailout, showall):
2430:
2431: The map is a specification of a map to retreive the resources from,
2432: either as a url or as an object. The filterFunc is a reference to a
2433: function that takes a resource object as its one argument and returns
2434: true if the resource should be included, or false if it should not
2435: be. If recursive is true, the map will be recursively examined,
2436: otherwise it will not be. If bailout is true, the function will return
2437: as soon as it finds a resource, if false it will finish. If showall is
2438: true it will not hide maps that contain nothing but one other map. By
2439: default, the map is the top-level map of the course, filterFunc is a
2440: function that always returns 1, recursive is true, bailout is false,
2441: showall is false. The resources will be returned in a list containing
2442: the resource objects for the corresponding resources, with B<no
2443: structure information> in the list; regardless of branching,
2444: recursion, etc., it will be a flat list.
2445:
2446: Thus, this is suitable for cases where you don't want the structure,
2447: just a list of all resources. It is also suitable for finding out how
2448: many resources match a given description; for this use, if all you
2449: want to know is if I<any> resources match the description, the bailout
2450: parameter will allow you to avoid potentially expensive enumeration of
2451: all matching resources.
2452:
2453: =item * B<hasResource>(map, filterFunc, recursive, showall):
2454:
2455: Convenience method for
2456:
2457: scalar(retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0
2458:
2459: which will tell whether the map has resources matching the description
2460: in the filter function.
2461:
2462: =item * B<usedVersion>(url):
2463:
2464: Retrieves version infomation for a url. Returns the version (a number, or
2465: the string "mostrecent") for resources which have version information in
2466: the big hash.
2467:
2468: =cut
2469:
2470:
2471: sub getResourceByUrl {
2472: my $self = shift;
2473: my $resUrl = shift;
2474: my $multiple = shift;
2475:
2476: if (ref($resUrl)) { return $resUrl; }
2477:
2478: $resUrl = &Apache::lonnet::clutter($resUrl);
2479: my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
2480: if (!$resId) { return ''; }
2481: if ($multiple) {
2482: my @resources = ();
2483: my @resIds = split (/,/, $resId);
2484: foreach my $id (@resIds) {
2485: my $resourceId = $self->getById($id);
2486: if ($resourceId) {
2487: push(@resources,$resourceId);
2488: }
2489: }
2490: return @resources;
2491: } else {
2492: if ($resId =~ /,/) {
2493: $resId = (split (/,/, $resId))[0];
2494: }
2495: return $self->getById($resId);
2496: }
2497: }
2498:
2499: sub retrieveResources {
2500: my $self = shift;
2501: my $map = shift;
2502: my $filterFunc = shift;
2503: if (!defined ($filterFunc)) {
2504: $filterFunc = sub {return 1;};
2505: }
2506: my $recursive = shift;
2507: if (!defined($recursive)) { $recursive = 1; }
2508: my $bailout = shift;
2509: if (!defined($bailout)) { $bailout = 0; }
2510: my $showall = shift;
2511: # Create the necessary iterator.
2512: if (!ref($map)) { # assume it's a url of a map.
2513: $map = $self->getResourceByUrl($map);
2514: }
2515:
2516: # If nothing was passed, assume top-level map
2517: if (!$map) {
2518: $map = $self->getById('0.0');
2519: }
2520:
2521: # Check the map's validity.
2522: if (!$map->is_map()) {
2523: # Oh, to throw an exception.... how I'd love that!
2524: return ();
2525: }
2526:
2527: # Get an iterator.
2528: my $it = $self->getIterator($map->map_start(), $map->map_finish(),
2529: undef, $recursive, $showall);
2530:
2531: my @resources = ();
2532:
2533: if (&$filterFunc($map)) {
2534: push(@resources, $map);
2535: }
2536:
2537: # Run down the iterator and collect the resources.
2538: my $curRes;
2539:
2540: while ($curRes = $it->next()) {
2541: if (ref($curRes)) {
2542: if (!&$filterFunc($curRes)) {
2543: next;
2544: }
2545:
2546: push(@resources, $curRes);
2547:
2548: if ($bailout) {
2549: return @resources;
2550: }
2551: }
2552:
2553: }
2554:
2555: return @resources;
2556: }
2557:
2558: sub hasResource {
2559: my $self = shift;
2560: my $map = shift;
2561: my $filterFunc = shift;
2562: my $recursive = shift;
2563: my $showall = shift;
2564:
2565: return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0;
2566: }
2567:
2568: sub usedVersion {
2569: my $self = shift;
2570: my $linkurl = shift;
2571: return $self->navhash("version_$linkurl");
2572: }
2573:
2574: 1;
2575:
2576: package Apache::lonnavmaps::iterator;
2577: use Scalar::Util qw(weaken);
2578: use Apache::lonnet;
2579:
2580: =pod
2581:
2582: =back
2583:
2584: =head1 Object: navmap Iterator
2585:
2586: An I<iterator> encapsulates the logic required to traverse a data
2587: structure. navmap uses an iterator to traverse the course map
2588: according to the criteria you wish to use.
2589:
2590: To obtain an iterator, call the B<getIterator>() function of a
2591: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
2592: directly.) This will return a reference to the iterator:
2593:
2594: C<my $resourceIterator = $navmap-E<gt>getIterator();>
2595:
2596: To get the next thing from the iterator, call B<next>:
2597:
2598: C<my $nextThing = $resourceIterator-E<gt>next()>
2599:
2600: getIterator behaves as follows:
2601:
2602: =over 4
2603:
2604: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
2605:
2606: All parameters are optional. firstResource is a resource reference
2607: corresponding to where the iterator should start. It defaults to
2608: navmap->firstResource() for the corresponding nav map. finishResource
2609: corresponds to where you want the iterator to end, defaulting to
2610: navmap->finishResource(). filterHash is a hash used as a set
2611: containing strings representing the resource IDs, defaulting to
2612: empty. Condition is a 1 or 0 that sets what to do with the filter
2613: hash: If a 0, then only resources that exist IN the filterHash will be
2614: recursed on. If it is a 1, only resources NOT in the filterHash will
2615: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
2616: false (default), the iterator will only return the first level of map
2617: that is not just a single, 'redirecting' map. If true, the iterator
2618: will return all information, starting with the top-level map,
2619: regardless of content. returnTopMap, if true (default false), will
2620: cause the iterator to return the top-level map object (resource 0.0)
2621: before anything else.
2622:
2623: Thus, by default, only top-level resources will be shown. Change the
2624: condition to a 1 without changing the hash, and all resources will be
2625: shown. Changing the condition to 1 and including some values in the
2626: hash will allow you to selectively suppress parts of the navmap, while
2627: leaving it on 0 and adding things to the hash will allow you to
2628: selectively add parts of the nav map. See the handler code for
2629: examples.
2630:
2631: The iterator will return either a reference to a resource object, or a
2632: token representing something in the map, such as the beginning of a
2633: new branch. The possible tokens are:
2634:
2635: =over 4
2636:
2637: =item * B<END_ITERATOR>:
2638:
2639: The iterator has returned all that it's going to. Further calls to the
2640: iterator will just produce more of these. This is a "false" value, and
2641: is the only false value the iterator which will be returned, so it can
2642: be used as a loop sentinel.
2643:
2644: =item * B<BEGIN_MAP>:
2645:
2646: A new map is being recursed into. This is returned I<after> the map
2647: resource itself is returned.
2648:
2649: =item * B<END_MAP>:
2650:
2651: The map is now done.
2652:
2653: =item * B<BEGIN_BRANCH>:
2654:
2655: A branch is now starting. The next resource returned will be the first
2656: in that branch.
2657:
2658: =item * B<END_BRANCH>:
2659:
2660: The branch is now done.
2661:
2662: =back
2663:
2664: The tokens are retreivable via methods on the iterator object, i.e.,
2665: $iterator->END_MAP.
2666:
2667: Maps can contain empty resources. The iterator will automatically skip
2668: over such resources, but will still treat the structure
2669: correctly. Thus, a complicated map with several branches, but
2670: consisting entirely of empty resources except for one beginning or
2671: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
2672: but only one resource will be returned.
2673:
2674: =back
2675:
2676: =head2 Normal Usage
2677:
2678: Normal usage of the iterator object is to do the following:
2679:
2680: my $it = $navmap->getIterator([your params here]);
2681: my $curRes;
2682: while ($curRes = $it->next()) {
2683: [your logic here]
2684: }
2685:
2686: Note that inside of the loop, it's frequently useful to check if
2687: "$curRes" is a reference or not with the reference function; only
2688: resource objects will be references, and any non-references will
2689: be the tokens described above.
2690:
2691: Also note there is some old code floating around that trys to track
2692: the depth of the iterator to see when it's done; do not copy that
2693: code. It is difficult to get right and harder to understand than
2694: this. They should be migrated to this new style.
2695:
2696: =cut
2697:
2698: # Here are the tokens for the iterator:
2699:
2700: sub END_ITERATOR { return 0; }
2701: sub BEGIN_MAP { return 1; } # begining of a new map
2702: sub END_MAP { return 2; } # end of the map
2703: sub BEGIN_BRANCH { return 3; } # beginning of a branch
2704: sub END_BRANCH { return 4; } # end of a branch
2705: sub FORWARD { return 1; } # go forward
2706: sub BACKWARD { return 2; }
2707:
2708: sub min {
2709: (my $a, my $b) = @_;
2710: if ($a < $b) { return $a; } else { return $b; }
2711: }
2712:
2713: sub new {
2714: # magic invocation to create a class instance
2715: my $proto = shift;
2716: my $class = ref($proto) || $proto;
2717: my $self = {};
2718:
2719: weaken($self->{NAV_MAP} = shift);
2720: return undef unless ($self->{NAV_MAP});
2721:
2722: # Handle the parameters
2723: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
2724: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
2725:
2726: # If the given resources are just the ID of the resource, get the
2727: # objects
2728: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
2729: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
2730: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
2731: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
2732:
2733: $self->{FILTER} = shift;
2734:
2735: # A hash, used as a set, of resource already seen
2736: $self->{ALREADY_SEEN} = shift;
2737: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
2738: $self->{CONDITION} = shift;
2739:
2740: # Do we want to automatically follow "redirection" maps?
2741: $self->{FORCE_TOP} = shift;
2742:
2743: # Do we want to return the top-level map object (resource 0.0)?
2744: $self->{RETURN_0} = shift;
2745: # have we done that yet?
2746: $self->{HAVE_RETURNED_0} = 0;
2747:
2748: # Now, we need to pre-process the map, by walking forward and backward
2749: # over the parts of the map we're going to look at.
2750:
2751: # The processing steps are exactly the same, except for a few small
2752: # changes, so I bundle those up in the following list of two elements:
2753: # (direction_to_iterate, VAL_name, next_resource_method_to_call,
2754: # first_resource).
2755: # This prevents writing nearly-identical code twice.
2756: my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext',
2757: 'FIRST_RESOURCE'],
2758: [BACKWARD(), 'BOT_UP_VAL', 'getPrevious',
2759: 'FINISH_RESOURCE'] );
2760:
2761: my $maxDepth = 0; # tracks max depth
2762:
2763: # If there is only one resource in this map, and it's a map, we
2764: # want to remember that, so the user can ask for the first map
2765: # that isn't just a redirector.
2766: my $resource; my $resourceCount = 0;
2767:
2768: # Documentation on this algorithm can be found in the CVS repository at
2769: # /docs/lonnavdocs; these "**#**" markers correspond to documentation
2770: # in that file.
2771: # **1**
2772:
2773: foreach my $pass (@iterations) {
2774: my $direction = $pass->[0];
2775: my $valName = $pass->[1];
2776: my $nextResourceMethod = $pass->[2];
2777: my $firstResourceName = $pass->[3];
2778:
2779: my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP},
2780: $self->{FIRST_RESOURCE},
2781: $self->{FINISH_RESOURCE},
2782: {}, undef, 0, $direction);
2783:
2784: # prime the recursion
2785: $self->{$firstResourceName}->{DATA}->{$valName} = 0;
2786: $iterator->next();
2787: my $curRes = $iterator->next();
2788: my $depth = 1;
2789: while ($depth > 0) {
2790: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
2791: if ($curRes == $iterator->END_MAP()) { $depth--; }
2792:
2793: if (ref($curRes)) {
2794: # If there's only one resource, this will save it
2795: # we have to filter empty resources from consideration here,
2796: # or even "empty", redirecting maps have two (start & finish)
2797: # or three (start, finish, plus redirector)
2798: if($direction == FORWARD && $curRes->src()) {
2799: $resource = $curRes; $resourceCount++;
2800: }
2801: my $resultingVal = $curRes->{DATA}->{$valName};
2802: my $nextResources = $curRes->$nextResourceMethod();
2803: my $nextCount = scalar(@{$nextResources});
2804:
2805: if ($nextCount == 1) { # **3**
2806: my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
2807: $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
2808: }
2809:
2810: if ($nextCount > 1) { # **4**
2811: foreach my $res (@{$nextResources}) {
2812: my $current = $res->{DATA}->{$valName} || 999999999;
2813: $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
2814: }
2815: }
2816: }
2817:
2818: # Assign the final val (**2**)
2819: if (ref($curRes) && $direction == BACKWARD()) {
2820: my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
2821: $curRes->{DATA}->{BOT_UP_VAL});
2822:
2823: $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
2824: if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
2825: }
2826:
2827: $curRes = $iterator->next();
2828: }
2829: }
2830:
2831: # Check: Was this only one resource, a map?
2832: if ($resourceCount == 1 && $resource->is_sequence() && !$self->{FORCE_TOP}) {
2833: my $firstResource = $resource->map_start();
2834: my $finishResource = $resource->map_finish();
2835: return
2836: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
2837: $finishResource, $self->{FILTER},
2838: $self->{ALREADY_SEEN},
2839: $self->{CONDITION},
2840: $self->{FORCE_TOP});
2841:
2842: }
2843:
2844: # Set up some bookkeeping information.
2845: $self->{CURRENT_DEPTH} = 0;
2846: $self->{MAX_DEPTH} = $maxDepth;
2847: $self->{STACK} = [];
2848: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2849: $self->{FINISHED} = 0; # When true, the iterator has finished
2850:
2851: for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
2852: push @{$self->{STACK}}, [];
2853: }
2854:
2855: # Prime the recursion w/ the first resource **5**
2856: push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
2857: $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
2858:
2859: bless ($self);
2860:
2861: return $self;
2862: }
2863:
2864: sub next {
2865: my $self = shift;
2866: my $closeAllPages=shift;
2867: if ($self->{FINISHED}) {
2868: return END_ITERATOR();
2869: }
2870:
2871: # If we want to return the top-level map object, and haven't yet,
2872: # do so.
2873: if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
2874: $self->{HAVE_RETURNED_0} = 1;
2875: return $self->{NAV_MAP}->getById('0.0');
2876: }
2877: if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0_BEGIN_MAP}) {
2878: $self->{HAVE_RETURNED_0_BEGIN_MAP} = 1;
2879: return $self->BEGIN_MAP();
2880: }
2881:
2882: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2883: # grab the next from the recursive iterator
2884: my $next = $self->{RECURSIVE_ITERATOR}->next($closeAllPages);
2885:
2886: # is it a begin or end map? If so, update the depth
2887: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
2888: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
2889:
2890: # Are we back at depth 0? If so, stop recursing
2891: if ($self->{RECURSIVE_DEPTH} == 0) {
2892: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2893: }
2894:
2895: return $next;
2896: }
2897:
2898: if (defined($self->{FORCE_NEXT})) {
2899: my $tmp = $self->{FORCE_NEXT};
2900: $self->{FORCE_NEXT} = undef;
2901: return $tmp;
2902: }
2903:
2904: # Have we not yet begun? If not, return BEGIN_MAP and
2905: # remember we've started.
2906: if ( !$self->{STARTED} ) {
2907: $self->{STARTED} = 1;
2908: return $self->BEGIN_MAP();
2909: }
2910:
2911: # Here's the guts of the iterator.
2912:
2913: # Find the next resource, if any.
2914: my $found = 0;
2915: my $i = $self->{MAX_DEPTH};
2916: my $newDepth;
2917: my $here;
2918: while ( $i >= 0 && !$found ) {
2919: if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
2920: $here = pop @{$self->{STACK}->[$i]}; # **7**
2921: $found = 1;
2922: $newDepth = $i;
2923: }
2924: $i--;
2925: }
2926:
2927: # If we still didn't find anything, we're done.
2928: if ( !$found ) {
2929: # We need to get back down to the correct branch depth
2930: if ( $self->{CURRENT_DEPTH} > 0 ) {
2931: $self->{CURRENT_DEPTH}--;
2932: return END_BRANCH();
2933: } else {
2934: $self->{FINISHED} = 1;
2935: return END_MAP();
2936: }
2937: }
2938:
2939: # If this is not a resource, it must be an END_BRANCH marker we want
2940: # to return directly.
2941: if (!ref($here)) { # **8**
2942: if ($here == END_BRANCH()) { # paranoia, in case of later extension
2943: $self->{CURRENT_DEPTH}--;
2944: return $here;
2945: }
2946: }
2947:
2948: # Otherwise, it is a resource and it's safe to store in $self->{HERE}
2949: $self->{HERE} = $here;
2950:
2951: # Get to the right level
2952: if ( $self->{CURRENT_DEPTH} > $newDepth ) {
2953: push @{$self->{STACK}->[$newDepth]}, $here;
2954: $self->{CURRENT_DEPTH}--;
2955: return END_BRANCH();
2956: }
2957: if ( $self->{CURRENT_DEPTH} < $newDepth) {
2958: push @{$self->{STACK}->[$newDepth]}, $here;
2959: $self->{CURRENT_DEPTH}++;
2960: return BEGIN_BRANCH();
2961: }
2962:
2963: # If we made it here, we have the next resource, and we're at the
2964: # right branch level. So let's examine the resource for where
2965: # we can get to from here.
2966:
2967: # So we need to look at all the resources we can get to from here,
2968: # categorize them if we haven't seen them, remember if we have a new
2969: my $nextUnfiltered = $here->getNext();
2970: my $maxDepthAdded = -1;
2971:
2972: for (@$nextUnfiltered) {
2973: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
2974: my $depth = $_->{DATA}->{DISPLAY_DEPTH};
2975: push @{$self->{STACK}->[$depth]}, $_;
2976: $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
2977: if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
2978: }
2979: }
2980:
2981: # Is this the end of a branch? If so, all of the resources examined above
2982: # led to lower levels than the one we are currently at, so we push a END_BRANCH
2983: # marker onto the stack so we don't forget.
2984: # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
2985: # BC branch and gets to C, it will see F as the only next resource, but it's
2986: # one level lower. Thus, this is the end of the branch, since there are no
2987: # more resources added to this level or above.
2988: # We don't do this if the examined resource is the finish resource,
2989: # because the condition given above is true, but the "END_MAP" will
2990: # take care of things and we should already be at depth 0.
2991: my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
2992: if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
2993: push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
2994: }
2995:
2996: # That ends the main iterator logic. Now, do we want to recurse
2997: # down this map (if this resource is a map)?
2998: if ( ($self->{HERE}->is_sequence() || (!$closeAllPages && $self->{HERE}->is_page())) &&
2999: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
3000: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
3001: my $firstResource = $self->{HERE}->map_start();
3002: my $finishResource = $self->{HERE}->map_finish();
3003:
3004: $self->{RECURSIVE_ITERATOR} =
3005: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
3006: $finishResource, $self->{FILTER},
3007: $self->{ALREADY_SEEN},
3008: $self->{CONDITION},
3009: $self->{FORCE_TOP});
3010: }
3011:
3012: # If this is a blank resource, don't actually return it.
3013: # Should you ever find you need it, make sure to add an option to the code
3014: # that you can use; other things depend on this behavior.
3015: my $browsePriv = $self->{HERE}->browsePriv();
3016: if (!$self->{HERE}->src() ||
3017: (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
3018: return $self->next($closeAllPages);
3019: }
3020:
3021: return $self->{HERE};
3022:
3023: }
3024:
3025: =pod
3026:
3027: The other method available on the iterator is B<getStack>, which
3028: returns an array populated with the current 'stack' of maps, as
3029: references to the resource objects. Example: This is useful when
3030: making the navigation map, as we need to check whether we are under a
3031: page map to see if we need to link directly to the resource, or to the
3032: page. The first elements in the array will correspond to the top of
3033: the stack (most inclusive map).
3034:
3035: =cut
3036:
3037: sub getStack {
3038: my $self=shift;
3039:
3040: my @stack;
3041:
3042: $self->populateStack(\@stack);
3043:
3044: return \@stack;
3045: }
3046:
3047: # Private method: Calls the iterators recursively to populate the stack.
3048: sub populateStack {
3049: my $self=shift;
3050: my $stack = shift;
3051:
3052: push @$stack, $self->{HERE} if ($self->{HERE});
3053:
3054: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
3055: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
3056: }
3057: }
3058:
3059: 1;
3060:
3061: package Apache::lonnavmaps::DFSiterator;
3062: use Scalar::Util qw(weaken);
3063: use Apache::lonnet;
3064:
3065: # Not documented in the perldoc: This is a simple iterator that just walks
3066: # through the nav map and presents the resources in a depth-first search
3067: # fashion, ignorant of conditionals, randomized resources, etc. It presents
3068: # BEGIN_MAP and END_MAP, but does not understand branches at all. It is
3069: # useful for pre-processing of some kind, and is in fact used by the main
3070: # iterator that way, but that's about it.
3071: # One could imagine merging this into the init routine of the main iterator,
3072: # but this might as well be left separate, since it is possible some other
3073: # use might be found for it. - Jeremy
3074:
3075: # Unlike the main iterator, this DOES return all resources, even blank ones.
3076: # The main iterator needs them to correctly preprocess the map.
3077:
3078: sub BEGIN_MAP { return 1; } # begining of a new map
3079: sub END_MAP { return 2; } # end of the map
3080: sub FORWARD { return 1; } # go forward
3081: sub BACKWARD { return 2; }
3082:
3083: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
3084: # filter hash ref (or undef), already seen hash or undef, condition
3085: # (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
3086: sub new {
3087: # magic invocation to create a class instance
3088: my $proto = shift;
3089: my $class = ref($proto) || $proto;
3090: my $self = {};
3091:
3092: weaken($self->{NAV_MAP} = shift);
3093: return undef unless ($self->{NAV_MAP});
3094:
3095: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
3096: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
3097:
3098: # If the given resources are just the ID of the resource, get the
3099: # objects
3100: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
3101: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
3102: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
3103: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
3104:
3105: $self->{FILTER} = shift;
3106:
3107: # A hash, used as a set, of resource already seen
3108: $self->{ALREADY_SEEN} = shift;
3109: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
3110: $self->{CONDITION} = shift;
3111: $self->{DIRECTION} = shift || FORWARD();
3112:
3113: # Flag: Have we started yet?
3114: $self->{STARTED} = 0;
3115:
3116: # Should we continue calling the recursive iterator, if any?
3117: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
3118: # The recursive iterator, if any
3119: $self->{RECURSIVE_ITERATOR} = undef;
3120: # Are we recursing on a map, or a branch?
3121: $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
3122: # And the count of how deep it is, so that this iterator can keep track of
3123: # when to pick back up again.
3124: $self->{RECURSIVE_DEPTH} = 0;
3125:
3126: # For keeping track of our branches, we maintain our own stack
3127: $self->{STACK} = [];
3128:
3129: # Start with the first resource
3130: if ($self->{DIRECTION} == FORWARD) {
3131: push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
3132: } else {
3133: push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
3134: }
3135:
3136: bless($self);
3137: return $self;
3138: }
3139:
3140: sub next {
3141: my $self = shift;
3142:
3143: # Are we using a recursive iterator? If so, pull from that and
3144: # watch the depth; we want to resume our level at the correct time.
3145: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
3146: # grab the next from the recursive iterator
3147: my $next = $self->{RECURSIVE_ITERATOR}->next();
3148:
3149: # is it a begin or end map? Update depth if so
3150: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
3151: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
3152:
3153: # Are we back at depth 0? If so, stop recursing.
3154: if ($self->{RECURSIVE_DEPTH} == 0) {
3155: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
3156: }
3157:
3158: return $next;
3159: }
3160:
3161: # Is there a current resource to grab? If not, then return
3162: # END_MAP, which will end the iterator.
3163: if (scalar(@{$self->{STACK}}) == 0) {
3164: return $self->END_MAP();
3165: }
3166:
3167: # Have we not yet begun? If not, return BEGIN_MAP and
3168: # remember that we've started.
3169: if ( !$self->{STARTED} ) {
3170: $self->{STARTED} = 1;
3171: return $self->BEGIN_MAP;
3172: }
3173:
3174: # Get the next resource in the branch
3175: $self->{HERE} = pop @{$self->{STACK}};
3176:
3177: # remember that we've seen this, so we don't return it again later
3178: $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
3179:
3180: # Get the next possible resources
3181: my $nextUnfiltered;
3182: if ($self->{DIRECTION} == FORWARD()) {
3183: $nextUnfiltered = $self->{HERE}->getNext();
3184: } else {
3185: $nextUnfiltered = $self->{HERE}->getPrevious();
3186: }
3187: my $next = [];
3188:
3189: # filter the next possibilities to remove things we've
3190: # already seen.
3191: foreach my $item (@$nextUnfiltered) {
3192: if (!defined($self->{ALREADY_SEEN}->{$item->{ID}})) {
3193: push @$next, $item;
3194: }
3195: }
3196:
3197: while (@$next) {
3198: # copy the next possibilities over to the stack
3199: push @{$self->{STACK}}, shift @$next;
3200: }
3201:
3202: # If this is a map and we want to recurse down it... (not filtered out)
3203: if ($self->{HERE}->is_map() &&
3204: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
3205: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
3206: my $firstResource = $self->{HERE}->map_start();
3207: my $finishResource = $self->{HERE}->map_finish();
3208:
3209: $self->{RECURSIVE_ITERATOR} =
3210: Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource,
3211: $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
3212: $self->{CONDITION}, $self->{DIRECTION});
3213: }
3214:
3215: return $self->{HERE};
3216: }
3217:
3218: # Identical to the full iterator methods of the same name. Hate to copy/paste
3219: # but I also hate to "inherit" either iterator from the other.
3220:
3221: sub getStack {
3222: my $self=shift;
3223:
3224: my @stack;
3225:
3226: $self->populateStack(\@stack);
3227:
3228: return \@stack;
3229: }
3230:
3231: # Private method: Calls the iterators recursively to populate the stack.
3232: sub populateStack {
3233: my $self=shift;
3234: my $stack = shift;
3235:
3236: push @$stack, $self->{HERE} if ($self->{HERE});
3237:
3238: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
3239: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
3240: }
3241: }
3242:
3243: 1;
3244:
3245: package Apache::lonnavmaps::resource;
3246: use Scalar::Util qw(weaken);
3247: use Apache::lonnet;
3248:
3249: =pod
3250:
3251: =head1 Object: resource
3252:
3253: X<resource, navmap object>
3254: A resource object encapsulates a resource in a resource map, allowing
3255: easy manipulation of the resource, querying the properties of the
3256: resource (including user properties), and represents a reference that
3257: can be used as the canonical representation of the resource by
3258: lonnavmap clients like renderers.
3259:
3260: A resource only makes sense in the context of a navmap, as some of the
3261: data is stored in the navmap object.
3262:
3263: You will probably never need to instantiate this object directly. Use
3264: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
3265: starting resource.
3266:
3267: Resource objects respect the parameter_hiddenparts, which suppresses
3268: various parts according to the wishes of the map author. As of this
3269: writing, there is no way to override this parameter, and suppressed
3270: parts will never be returned, nor will their response types or ids be
3271: stored.
3272:
3273: =head2 Overview
3274:
3275: A B<Resource> is the most granular type of object in LON-CAPA that can
3276: be included in a course. It can either be a particular resource, like
3277: an HTML page, external resource, problem, etc., or it can be a
3278: container sequence, such as a "page" or a "map".
3279:
3280: To see a sequence from the user's point of view, please see the
3281: B<Creating a Course: Maps and Sequences> chapter of the Author's
3282: Manual.
3283:
3284: A Resource Object, once obtained from a navmap object via a B<getBy*>
3285: method of the navmap, or from an iterator, allows you to query
3286: information about that resource.
3287:
3288: Generally, you do not ever want to create a resource object yourself,
3289: so creation has been left undocumented. Always retrieve resources
3290: from navmap objects.
3291:
3292: =head3 Identifying Resources
3293:
3294: X<big hash>Every resource is identified by a Resource ID in the big hash that is
3295: unique to that resource for a given course. X<resource ID, in big hash>
3296: The Resource ID has the form #.#, where the first number is the same
3297: for every resource in a map, and the second is unique. For instance,
3298: for a course laid out like this:
3299:
3300: * Problem 1
3301: * Map
3302: * Resource 2
3303: * Resource 3
3304:
3305: C<Problem 1> and C<Map> will share a first number, and C<Resource 2>
3306: C<Resource 3> will share a first number. The second number may end up
3307: re-used between the two groups.
3308:
3309: The resource ID is only used in the big hash, but can be used in the
3310: context of a course to identify a resource easily. (For instance, the
3311: printing system uses it to record which resources from a sequence you
3312: wish to print.)
3313:
3314: X<symb> X<resource, symb>
3315: All resources also have B<symb>s, which uniquely identify a resource
3316: in a course. Many internal LON-CAPA functions expect a symb. A symb
3317: carries along with it the URL of the resource, and the map it appears
3318: in. Symbs are much larger than resource IDs.
3319:
3320: =cut
3321:
3322: sub new {
3323: # magic invocation to create a class instance
3324: my $proto = shift;
3325: my $class = ref($proto) || $proto;
3326: my $self = {};
3327:
3328: weaken($self->{NAV_MAP} = shift);
3329: $self->{ID} = shift;
3330:
3331: # Store this new resource in the parent nav map's cache.
3332: $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
3333: $self->{RESOURCE_ERROR} = 0;
3334:
3335: # A hash that can be used by two-pass algorithms to store data
3336: # about this resource in. Not used by the resource object
3337: # directly.
3338: $self->{DATA} = {};
3339:
3340: bless($self);
3341:
3342: return $self;
3343: }
3344:
3345: # private function: simplify the NAV_HASH lookups we keep doing
3346: # pass the name, and to automatically append my ID, pass a true val on the
3347: # second param
3348: sub navHash {
3349: my $self = shift;
3350: my $param = shift;
3351: my $id = shift;
3352: return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
3353: }
3354:
3355: =pod
3356:
3357: =head2 Methods
3358:
3359: Once you have a resource object, here's what you can do with it:
3360:
3361: =head3 Attribute Retrieval
3362:
3363: Every resource has certain attributes that can be retrieved and used:
3364:
3365: =over 4
3366:
3367: =item * B<ID>: Every resource has an ID that is unique for that
3368: resource in the course it is in. The ID is actually in the hash
3369: representing the resource, so for a resource object $res, obtain
3370: it via C<$res->{ID}).
3371:
3372: =item * B<compTitle>:
3373:
3374: Returns a "composite title", that is equal to $res->title() if the
3375: resource has a title, and is otherwise the last part of the URL (e.g.,
3376: "problem.problem").
3377:
3378: =item * B<ext>:
3379:
3380: Returns true if the resource is external.
3381:
3382: =item * B<kind>:
3383:
3384: Returns the kind of the resource from the compiled nav map.
3385:
3386: =item * B<randomout>:
3387:
3388: Returns true if this resource was chosen to NOT be shown to the user
3389: by the random map selection feature. In other words, this is usually
3390: false.
3391:
3392: =item * B<randompick>:
3393:
3394: Returns the number of randomly picked items for a map if the randompick
3395: feature is being used on the map.
3396:
3397: =item * B<randomorder>:
3398:
3399: Returns true for a map if the randomorder feature is being used on the
3400: map.
3401:
3402: =item * B<src>:
3403:
3404: Returns the source for the resource.
3405:
3406: =item * B<symb>:
3407:
3408: Returns the symb for the resource.
3409:
3410: =item * B<title>:
3411:
3412: Returns the title of the resource.
3413:
3414: =back
3415:
3416: =cut
3417:
3418: # These info functions can be used directly, as they don't return
3419: # resource information.
3420: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
3421: sub encrypted { my $self=shift; return $self->navHash("encrypted_", 1); }
3422: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
3423: sub from { my $self=shift; return $self->navHash("from_", 1); }
3424: # considered private and undocumented
3425: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
3426: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
3427: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
3428: sub randompick {
3429: my $self = shift;
3430: return $self->parmval('randompick');
3431: }
3432: sub randomorder {
3433: my $self = shift;
3434: return ($self->parmval('randomorder') =~ /^yes$/i);
3435: }
3436: sub link {
3437: my $self=shift;
3438: if ($self->encrypted()) { return &Apache::lonenc::encrypted($self->src); }
3439: return $self->src;
3440: }
3441: sub src {
3442: my $self=shift;
3443: return $self->navHash("src_", 1);
3444: }
3445: sub shown_symb {
3446: my $self=shift;
3447: if ($self->encrypted()) {return &Apache::lonenc::encrypted($self->symb());}
3448: return $self->symb();
3449: }
3450: sub id {
3451: my $self=shift;
3452: return $self->{ID};
3453: }
3454: sub enclosing_map_src {
3455: my $self=shift;
3456: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
3457: return $self->navHash('map_id_'.$first);
3458: }
3459: sub symb {
3460: my $self=shift;
3461: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
3462: my $symbSrc = &Apache::lonnet::declutter($self->src());
3463: my $symb = &Apache::lonnet::declutter($self->navHash('map_id_'.$first))
3464: . '___' . $second . '___' . $symbSrc;
3465: return &Apache::lonnet::symbclean($symb);
3466: }
3467: sub wrap_symb {
3468: my $self = shift;
3469: return $self->{NAV_MAP}->wrap_symb($self->symb());
3470: }
3471: sub title {
3472: my $self=shift;
3473: if ($self->{ID} eq '0.0') {
3474: # If this is the top-level map, return the title of the course
3475: # since this map can not be titled otherwise.
3476: return $env{'course.'.$env{'request.course.id'}.'.description'};
3477: }
3478: return $self->navHash("title_", 1); }
3479: # considered private and undocumented
3480: sub to { my $self=shift; return $self->navHash("to_", 1); }
3481: sub condition {
3482: my $self=shift;
3483: my $undercond=$self->navHash("undercond_", 1);
3484: if (!defined($undercond)) { return 1; };
3485: my $condid=$self->navHash("condid_$undercond");
3486: if (!defined($condid)) { return 1; };
3487: my $condition=&Apache::lonnet::directcondval($condid);
3488: return $condition;
3489: }
3490: sub condval {
3491: my $self=shift;
3492: my ($pathname,$filename) =
3493: &Apache::lonnet::split_uri_for_cond($self->src());
3494:
3495: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
3496: /\&\Q$filename\E\:([\d\|]+)\&/);
3497: if ($match) {
3498: return &Apache::lonnet::condval($1);
3499: }
3500: return 0;
3501: }
3502: sub compTitle {
3503: my $self = shift;
3504: my $title = $self->title();
3505: $title=~s/\&colon\;/\:/gs;
3506: if (!$title) {
3507: $title = $self->src();
3508: $title = substr($title, rindex($title, '/') + 1);
3509: }
3510: return $title;
3511: }
3512:
3513: =pod
3514:
3515: B<Predicate Testing the Resource>
3516:
3517: These methods are shortcuts to deciding if a given resource has a given property.
3518:
3519: =over 4
3520:
3521: =item * B<is_map>:
3522:
3523: Returns true if the resource is a map type.
3524:
3525: =item * B<is_problem>:
3526:
3527: Returns true if the resource is a problem type, false
3528: otherwise. (Looks at the extension on the src field; might need more
3529: to work correctly.)
3530:
3531: =item * B<is_page>:
3532:
3533: Returns true if the resource is a page.
3534:
3535: =item * B<is_sequence>:
3536:
3537: Returns true if the resource is a sequence.
3538:
3539: =back
3540:
3541: =cut
3542:
3543: sub hasResource {
3544: my $self = shift;
3545: return $self->{NAV_MAP}->hasResource(@_);
3546: }
3547:
3548: sub retrieveResources {
3549: my $self = shift;
3550: return $self->{NAV_MAP}->retrieveResources(@_);
3551: }
3552:
3553: sub is_exam {
3554: my ($self,$part) = @_;
3555: if ($self->parmval('type',$part) eq 'exam') {
3556: return 1;
3557: }
3558: if ($self->src() =~ /\.(exam)$/) {
3559: return 1;
3560: }
3561: return 0;
3562: }
3563: sub is_html {
3564: my $self=shift;
3565: my $src = $self->src();
3566: return ($src =~ /html$/);
3567: }
3568: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
3569: sub is_page {
3570: my $self=shift;
3571: my $src = $self->src();
3572: return $self->navHash("is_map_", 1) &&
3573: $self->navHash("map_type_" . $self->map_pc()) eq 'page';
3574: }
3575: sub is_practice {
3576: my $self=shift;
3577: my ($part) = @_;
3578: if ($self->parmval('type',$part) eq 'practice') {
3579: return 1;
3580: }
3581: return 0;
3582: }
3583: sub is_problem {
3584: my $self=shift;
3585: my $src = $self->src();
3586: if ($src =~ /\.(problem|exam|quiz|assess|survey|form|library|task)$/) {
3587: return !($self->is_practice());
3588: }
3589: return 0;
3590: }
3591: sub contains_problem {
3592: my $self=shift;
3593: if ($self->is_page()) {
3594: my $hasProblem=$self->hasResource($self,sub { $_[0]->is_problem() },1);
3595: return $hasProblem;
3596: }
3597: return 0;
3598: }
3599: sub map_contains_problem {
3600: my $self=shift;
3601: if ($self->is_map()) {
3602: my $has_problem=
3603: $self->hasResource($self,sub { $_[0]->is_problem() },1);
3604: return $has_problem;
3605: }
3606: return 0;
3607: }
3608: sub is_sequence {
3609: my $self=shift;
3610: return $self->navHash("is_map_", 1) &&
3611: $self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
3612: }
3613: sub is_survey {
3614: my $self = shift();
3615: my $part = shift();
3616: if ($self->parmval('type',$part) eq 'survey') {
3617: return 1;
3618: }
3619: if ($self->src() =~ /\.(survey)$/) {
3620: return 1;
3621: }
3622: return 0;
3623: }
3624: sub is_task {
3625: my $self=shift;
3626: my $src = $self->src();
3627: return ($src =~ /\.(task)$/)
3628: }
3629:
3630: sub is_empty_sequence {
3631: my $self=shift;
3632: my $src = $self->src();
3633: return !$self->is_page() && $self->navHash("is_map_", 1) && !$self->navHash("map_type_" . $self->map_pc());
3634: }
3635:
3636: # Private method: Shells out to the parmval in the nav map, handler parts.
3637: sub parmval {
3638: my $self = shift;
3639: my $what = shift;
3640: my $part = shift;
3641: if (!defined($part)) {
3642: $part = '0';
3643: }
3644: return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
3645: }
3646:
3647: =pod
3648:
3649: B<Map Methods>
3650:
3651: These methods are useful for getting information about the map
3652: properties of the resource, if the resource is a map (B<is_map>).
3653:
3654: =over 4
3655:
3656: =item * B<map_finish>:
3657:
3658: Returns a reference to a resource object corresponding to the finish
3659: resource of the map.
3660:
3661: =item * B<map_pc>:
3662:
3663: Returns the pc value of the map, which is the first number that
3664: appears in the resource ID of the resources in the map, and is the
3665: number that appears around the middle of the symbs of the resources in
3666: that map.
3667:
3668: =item * B<map_start>:
3669:
3670: Returns a reference to a resource object corresponding to the start
3671: resource of the map.
3672:
3673: =item * B<map_type>:
3674:
3675: Returns a string with the type of the map in it.
3676:
3677: =back
3678:
3679: =cut
3680:
3681: sub map_finish {
3682: my $self = shift;
3683: my $src = $self->src();
3684: $src = &Apache::lonnet::clutter($src);
3685: my $res = $self->navHash("map_finish_$src", 0);
3686: $res = $self->{NAV_MAP}->getById($res);
3687: return $res;
3688: }
3689: sub map_pc {
3690: my $self = shift;
3691: my $src = $self->src();
3692: return $self->navHash("map_pc_$src", 0);
3693: }
3694: sub map_start {
3695: my $self = shift;
3696: my $src = $self->src();
3697: $src = &Apache::lonnet::clutter($src);
3698: my $res = $self->navHash("map_start_$src", 0);
3699: $res = $self->{NAV_MAP}->getById($res);
3700: return $res;
3701: }
3702: sub map_type {
3703: my $self = shift;
3704: my $pc = $self->map_pc();
3705: return $self->navHash("map_type_$pc", 0);
3706: }
3707:
3708: #####
3709: # Property queries
3710: #####
3711:
3712: # These functions will be responsible for returning the CORRECT
3713: # VALUE for the parameter, no matter what. So while they may look
3714: # like direct calls to parmval, they can be more than that.
3715: # So, for instance, the duedate function should use the "duedatetype"
3716: # information, rather than the resource object user.
3717:
3718: =pod
3719:
3720: =head2 Resource Parameters
3721:
3722: In order to use the resource parameters correctly, the nav map must
3723: have been instantiated with genCourseAndUserOptions set to true, so
3724: the courseopt and useropt is read correctly. Then, you can call these
3725: functions to get the relevant parameters for the resource. Each
3726: function defaults to part "0", but can be directed to another part by
3727: passing the part as the parameter.
3728:
3729: These methods are responsible for getting the parameter correct, not
3730: merely reflecting the contents of the GDBM hashes. As we move towards
3731: dates relative to other dates, these methods should be updated to
3732: reflect that. (Then, anybody using these methods will not have to update
3733: their code.)
3734:
3735: =over 4
3736:
3737: =item * B<acc>:
3738:
3739: Get the Client IP/Name Access Control information.
3740:
3741: =item * B<answerdate>:
3742:
3743: Get the answer-reveal date for the problem.
3744:
3745: =item * B<awarded>:
3746:
3747: Gets the awarded value for the problem part. Requires genUserData set to
3748: true when the navmap object was created.
3749:
3750: =item * B<duedate>:
3751:
3752: Get the due date for the problem.
3753:
3754: =item * B<tries>:
3755:
3756: Get the number of tries the student has used on the problem.
3757:
3758: =item * B<maxtries>:
3759:
3760: Get the number of max tries allowed.
3761:
3762: =item * B<opendate>:
3763:
3764: Get the open date for the problem.
3765:
3766: =item * B<sig>:
3767:
3768: Get the significant figures setting.
3769:
3770: =item * B<tol>:
3771:
3772: Get the tolerance for the problem.
3773:
3774: =item * B<tries>:
3775:
3776: Get the number of tries the user has already used on the problem.
3777:
3778: =item * B<type>:
3779:
3780: Get the question type for the problem.
3781:
3782: =item * B<weight>:
3783:
3784: Get the weight for the problem.
3785:
3786: =back
3787:
3788: =cut
3789:
3790: sub acc {
3791: (my $self, my $part) = @_;
3792: return $self->parmval("acc", $part);
3793: }
3794: sub answerdate {
3795: (my $self, my $part) = @_;
3796: # Handle intervals
3797: if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
3798: return $self->duedate($part) +
3799: $self->parmval("answerdate", $part);
3800: }
3801: return $self->parmval("answerdate", $part);
3802: }
3803: sub awarded {
3804: my $self = shift; my $part = shift;
3805: $self->{NAV_MAP}->get_user_data();
3806: if (!defined($part)) { $part = '0'; }
3807: return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->symb()}->{'resource.'.$part.'.awarded'};
3808: }
3809: # this should work exactly like the copy in lonhomework.pm
3810: sub duedate {
3811: (my $self, my $part) = @_;
3812: my $date;
3813: my $interval=$self->parmval("interval", $part);
3814: my $due_date=$self->parmval("duedate", $part);
3815: if ($interval =~ /\d+/) {
3816: my $first_access=&Apache::lonnet::get_first_access('map',$self->symb);
3817: if (defined($first_access)) {
3818: $interval = $first_access+$interval;
3819: $date = ($interval < $due_date)? $interval : $due_date;
3820: } else {
3821: $date = $due_date;
3822: }
3823: } else {
3824: $date = $due_date;
3825: }
3826: return $date;
3827: }
3828: sub handgrade {
3829: (my $self, my $part) = @_;
3830: my @response_ids = $self->responseIds($part);
3831: if (@response_ids) {
3832: foreach my $response_id (@response_ids) {
3833: if (lc($self->parmval("handgrade",$part.'_'.$response_id))
3834: eq 'yes') {
3835: return 'yes';
3836: }
3837: }
3838: }
3839: return $self->parmval("handgrade", $part);
3840: }
3841: sub maxtries {
3842: (my $self, my $part) = @_;
3843: return $self->parmval("maxtries", $part);
3844: }
3845: sub opendate {
3846: (my $self, my $part) = @_;
3847: if ($self->parmval("opendate.type", $part) eq 'date_interval') {
3848: return $self->duedate($part) -
3849: $self->parmval("opendate", $part);
3850: }
3851: return $self->parmval("opendate");
3852: }
3853: sub problemstatus {
3854: (my $self, my $part) = @_;
3855: return lc $self->parmval("problemstatus", $part);
3856: }
3857: sub sig {
3858: (my $self, my $part) = @_;
3859: return $self->parmval("sig", $part);
3860: }
3861: sub tol {
3862: (my $self, my $part) = @_;
3863: return $self->parmval("tol", $part);
3864: }
3865: sub tries {
3866: my $self = shift;
3867: my $tries = $self->queryRestoreHash('tries', shift);
3868: if (!defined($tries)) { return '0';}
3869: return $tries;
3870: }
3871: sub type {
3872: (my $self, my $part) = @_;
3873: return $self->parmval("type", $part);
3874: }
3875: sub weight {
3876: my $self = shift; my $part = shift;
3877: if (!defined($part)) { $part = '0'; }
3878: return &Apache::lonnet::EXT('resource.'.$part.'.weight',
3879: $self->symb(), $env{'user.domain'},
3880: $env{'user.name'},
3881: $env{'request.course.sec'});
3882: }
3883: sub part_display {
3884: my $self= shift(); my $partID = shift();
3885: if (! defined($partID)) { $partID = '0'; }
3886: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',
3887: $self->symb);
3888: if (! defined($display) || $display eq '') {
3889: $display = $partID;
3890: }
3891: return $display;
3892: }
3893:
3894: # Multiple things need this
3895: sub getReturnHash {
3896: my $self = shift;
3897:
3898: if (!defined($self->{RETURN_HASH})) {
3899: my %tmpHash = &Apache::lonnet::restore($self->symb());
3900: $self->{RETURN_HASH} = \%tmpHash;
3901: }
3902: }
3903:
3904: ######
3905: # Status queries
3906: ######
3907:
3908: # These methods query the status of problems.
3909:
3910: # If we need to count parts, this function determines the number of
3911: # parts from the metadata. When called, it returns a reference to a list
3912: # of strings corresponding to the parts. (Thus, using it in a scalar context
3913: # tells you how many parts you have in the problem:
3914: # $partcount = scalar($resource->countParts());
3915: # Don't use $self->{PARTS} directly because you don't know if it's been
3916: # computed yet.
3917:
3918: =pod
3919:
3920: =head2 Resource misc
3921:
3922: Misc. functions for the resource.
3923:
3924: =over 4
3925:
3926: =item * B<hasDiscussion>:
3927:
3928: Returns a false value if there has been discussion since the user last
3929: logged in, true if there has. Always returns false if the discussion
3930: data was not extracted when the nav map was constructed.
3931:
3932: =item * B<last_post_time>:
3933:
3934: Returns a false value if there hasn't been discussion otherwise returns
3935: unix timestamp of last time a discussion posting (or edit) was made.
3936:
3937: =item * B<discussion_info>:
3938:
3939: optional argument is a filter (currently can be 'unread');
3940: returns in scalar context the count of the number of discussion postings.
3941:
3942: returns in list context both the count of postings and a hash ref
3943: containing information about the postings (subject, id, timestamp) in a hash.
3944:
3945: Default is to return counts for all postings. However if called with a second argument set to 'unread', will return information about only unread postings.
3946:
3947: =item * B<getFeedback>:
3948:
3949: Gets the feedback for the resource and returns the raw feedback string
3950: for the resource, or the null string if there is no feedback or the
3951: email data was not extracted when the nav map was constructed. Usually
3952: used like this:
3953:
3954: for my $url (split(/\,/, $res->getFeedback())) {
3955: my $link = &escape($url);
3956: ...
3957:
3958: and use the link as appropriate.
3959:
3960: =cut
3961:
3962: sub hasDiscussion {
3963: my $self = shift;
3964: return $self->{NAV_MAP}->hasDiscussion($self->symb());
3965: }
3966:
3967: sub last_post_time {
3968: my $self = shift;
3969: return $self->{NAV_MAP}->last_post_time($self->symb());
3970: }
3971:
3972: sub discussion_info {
3973: my ($self,$filter) = @_;
3974: return $self->{NAV_MAP}->discussion_info($self->symb(),$filter);
3975: }
3976:
3977: sub getFeedback {
3978: my $self = shift;
3979: my $source = $self->src();
3980: my $symb = $self->symb();
3981: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
3982: return $self->{NAV_MAP}->getFeedback($symb,$source);
3983: }
3984:
3985: sub getErrors {
3986: my $self = shift;
3987: my $source = $self->src();
3988: my $symb = $self->symb();
3989: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
3990: return $self->{NAV_MAP}->getErrors($symb,$source);
3991: }
3992:
3993: =pod
3994:
3995: =item * B<parts>():
3996:
3997: Returns a list reference containing sorted strings corresponding to
3998: each part of the problem. Single part problems have only a part '0'.
3999: Multipart problems do not return their part '0', since they typically
4000: do not really matter.
4001:
4002: =item * B<countParts>():
4003:
4004: Returns the number of parts of the problem a student can answer. Thus,
4005: for single part problems, returns 1. For multipart, it returns the
4006: number of parts in the problem, not including psuedo-part 0.
4007:
4008: =item * B<countResponses>():
4009:
4010: Returns the total number of responses in the problem a student can answer.
4011:
4012: =item * B<responseTypes>():
4013:
4014: Returns a hash whose keys are the response types. The values are the number
4015: of times each response type is used. This is for the I<entire> problem, not
4016: just a single part.
4017:
4018: =item * B<multipart>():
4019:
4020: Returns true if the problem is multipart, false otherwise. Use this instead
4021: of countParts if all you want is multipart/not multipart.
4022:
4023: =item * B<responseType>($part):
4024:
4025: Returns the response type of the part, without the word "response" on the
4026: end. Example return values: 'string', 'essay', 'numeric', etc.
4027:
4028: =item * B<responseIds>($part):
4029:
4030: Retreives the response IDs for the given part as an array reference containing
4031: strings naming the response IDs. This may be empty.
4032:
4033: =back
4034:
4035: =cut
4036:
4037: sub parts {
4038: my $self = shift;
4039:
4040: if ($self->ext) { return []; }
4041:
4042: $self->extractParts();
4043: return $self->{PARTS};
4044: }
4045:
4046: sub countParts {
4047: my $self = shift;
4048:
4049: my $parts = $self->parts();
4050:
4051: # If I left this here, then it's not necessary.
4052: #my $delta = 0;
4053: #for my $part (@$parts) {
4054: # if ($part eq '0') { $delta--; }
4055: #}
4056:
4057: if ($self->{RESOURCE_ERROR}) {
4058: return 0;
4059: }
4060:
4061: return scalar(@{$parts}); # + $delta;
4062: }
4063:
4064: sub countResponses {
4065: my $self = shift;
4066: my $count;
4067: foreach my $part (@{$self->parts()}) {
4068: $count+= scalar($self->responseIds($part));
4069: }
4070: return $count;
4071: }
4072:
4073: sub responseTypes {
4074: my $self = shift;
4075: my %responses;
4076: foreach my $part (@{$self->parts()}) {
4077: foreach my $responsetype ($self->responseType($part)) {
4078: $responses{$responsetype}++ if (defined($responsetype));
4079: }
4080: }
4081: return %responses;
4082: }
4083:
4084: sub multipart {
4085: my $self = shift;
4086: return $self->countParts() > 1;
4087: }
4088:
4089: sub singlepart {
4090: my $self = shift;
4091: return $self->countParts() == 1;
4092: }
4093:
4094: sub responseType {
4095: my $self = shift;
4096: my $part = shift;
4097:
4098: $self->extractParts();
4099: if (defined($self->{RESPONSE_TYPES}->{$part})) {
4100: return @{$self->{RESPONSE_TYPES}->{$part}};
4101: } else {
4102: return undef;
4103: }
4104: }
4105:
4106: sub responseIds {
4107: my $self = shift;
4108: my $part = shift;
4109:
4110: $self->extractParts();
4111: if (defined($self->{RESPONSE_IDS}->{$part})) {
4112: return @{$self->{RESPONSE_IDS}->{$part}};
4113: } else {
4114: return undef;
4115: }
4116: }
4117:
4118: # Private function: Extracts the parts information, both part names and
4119: # part types, and saves it.
4120: sub extractParts {
4121: my $self = shift;
4122:
4123: return if (defined($self->{PARTS}));
4124: return if ($self->ext);
4125:
4126: $self->{PARTS} = [];
4127:
4128: my %parts;
4129:
4130: # Retrieve part count, if this is a problem
4131: if ($self->is_problem()) {
4132: my $partorder = &Apache::lonnet::metadata($self->src(), 'partorder');
4133: my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
4134:
4135: if ($partorder) {
4136: my @parts;
4137: for my $part (split (/,/,$partorder)) {
4138: if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
4139: push @parts, $part;
4140: $parts{$part} = 1;
4141: }
4142: }
4143: $self->{PARTS} = \@parts;
4144: } else {
4145: if (!$metadata) {
4146: $self->{RESOURCE_ERROR} = 1;
4147: $self->{PARTS} = [];
4148: $self->{PART_TYPE} = {};
4149: return;
4150: }
4151: foreach my $entry (split(/\,/,$metadata)) {
4152: if ($entry =~ /^(?:part|Task)_(.*)$/) {
4153: my $part = $1;
4154: # This floods the logs if it blows up
4155: if (defined($parts{$part})) {
4156: &Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
4157: }
4158:
4159: # check to see if part is turned off.
4160:
4161: if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
4162: $parts{$part} = 1;
4163: }
4164: }
4165: }
4166: my @sortedParts = sort keys %parts;
4167: $self->{PARTS} = \@sortedParts;
4168: }
4169:
4170:
4171: # These hashes probably do not need names that end with "Hash"....
4172: my %responseIdHash;
4173: my %responseTypeHash;
4174:
4175:
4176: # Init the responseIdHash
4177: foreach my $part (@{$self->{PARTS}}) {
4178: $responseIdHash{$part} = [];
4179: }
4180:
4181: # Now, the unfortunate thing about this is that parts, part name, and
4182: # response id are delimited by underscores, but both the part
4183: # name and response id can themselves have underscores in them.
4184: # So we have to use our knowlege of part names to figure out
4185: # where the part names begin and end, and even then, it is possible
4186: # to construct ambiguous situations.
4187: foreach my $data (split /,/, $metadata) {
4188: if ($data =~ /^([a-zA-Z]+)response_(.*)/
4189: || $data =~ /^(Task)_(.*)/) {
4190: my $responseType = $1;
4191: my $partStuff = $2;
4192: my $partIdSoFar = '';
4193: my @partChunks = split /_/, $partStuff;
4194: my $i = 0;
4195: for ($i = 0; $i < scalar(@partChunks); $i++) {
4196: if ($partIdSoFar) { $partIdSoFar .= '_'; }
4197: $partIdSoFar .= $partChunks[$i];
4198: if ($parts{$partIdSoFar}) {
4199: my @otherChunks = @partChunks[$i+1..$#partChunks];
4200: my $responseId = join('_', @otherChunks);
4201: if ($self->is_task()) {
4202: push(@{$responseIdHash{$partIdSoFar}},
4203: $partIdSoFar);
4204: } else {
4205: push(@{$responseIdHash{$partIdSoFar}},
4206: $responseId);
4207: }
4208: push(@{$responseTypeHash{$partIdSoFar}},
4209: $responseType);
4210: }
4211: }
4212: }
4213: }
4214: my $resorder = &Apache::lonnet::metadata($self->src(),'responseorder');
4215: #
4216: # Reorder the arrays in the %responseIdHash and %responseTypeHash
4217: if ($resorder) {
4218: my @resorder=split(/,/,$resorder);
4219: foreach my $part (keys(%responseIdHash)) {
4220: my $i=0;
4221: my %resids = map { ($_,$i++) } @{ $responseIdHash{$part} };
4222: my @neworder;
4223: foreach my $possibleid (@resorder) {
4224: if (exists($resids{$possibleid})) {
4225: push(@neworder,$resids{$possibleid});
4226: }
4227: }
4228: my @ids;
4229: my @type;
4230: foreach my $element (@neworder) {
4231: push (@ids,$responseIdHash{$part}->[$element]);
4232: push (@type,$responseTypeHash{$part}->[$element]);
4233: }
4234: $responseIdHash{$part}=\@ids;
4235: $responseTypeHash{$part}=\@type;
4236: }
4237: }
4238: $self->{RESPONSE_IDS} = \%responseIdHash;
4239: $self->{RESPONSE_TYPES} = \%responseTypeHash;
4240: }
4241:
4242: return;
4243: }
4244:
4245: =pod
4246:
4247: =head2 Resource Status
4248:
4249: Problem resources have status information, reflecting their various
4250: dates and completion statuses.
4251:
4252: There are two aspects to the status: the date-related information and
4253: the completion information.
4254:
4255: Idiomatic usage of these two methods would probably look something
4256: like
4257:
4258: foreach my $part ($resource->parts()) {
4259: my $dateStatus = $resource->getDateStatus($part);
4260: my $completionStatus = $resource->getCompletionStatus($part);
4261:
4262: or
4263:
4264: my $status = $resource->status($part);
4265:
4266: ... use it here ...
4267: }
4268:
4269: Which you use depends on exactly what you are looking for. The
4270: status() function has been optimized for the nav maps display and may
4271: not precisely match what you need elsewhere.
4272:
4273: The symbolic constants shown below can be accessed through the
4274: resource object: C<$res->OPEN>.
4275:
4276: =over 4
4277:
4278: =item * B<getDateStatus>($part):
4279:
4280: ($part defaults to 0). A convenience function that returns a symbolic
4281: constant telling you about the date status of the part. The possible
4282: return values are:
4283:
4284: =back
4285:
4286: B<Date Codes>
4287:
4288: =over 4
4289:
4290: =item * B<OPEN_LATER>:
4291:
4292: The problem will be opened later.
4293:
4294: =item * B<OPEN>:
4295:
4296: Open and not yet due.
4297:
4298:
4299: =item * B<PAST_DUE_ANSWER_LATER>:
4300:
4301: The due date has passed, but the answer date has not yet arrived.
4302:
4303: =item * B<PAST_DUE_NO_ANSWER>:
4304:
4305: The due date has passed and there is no answer opening date set.
4306:
4307: =item * B<ANSWER_OPEN>:
4308:
4309: The answer date is here.
4310:
4311: =item * B<NETWORK_FAILURE>:
4312:
4313: The information is unknown due to network failure.
4314:
4315: =back
4316:
4317: =cut
4318:
4319: # Apparently the compiler optimizes these into constants automatically
4320: sub OPEN_LATER { return 0; }
4321: sub OPEN { return 1; }
4322: sub PAST_DUE_NO_ANSWER { return 2; }
4323: sub PAST_DUE_ANSWER_LATER { return 3; }
4324: sub ANSWER_OPEN { return 4; }
4325: sub NOTHING_SET { return 5; }
4326: sub NETWORK_FAILURE { return 100; }
4327:
4328: # getDateStatus gets the date status for a given problem part.
4329: # Because answer date, due date, and open date are fully independent
4330: # (i.e., it is perfectly possible to *only* have an answer date),
4331: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
4332: # (past, future, none given). This function handles this with a decision
4333: # tree. Read the comments to follow the decision tree.
4334:
4335: sub getDateStatus {
4336: my $self = shift;
4337: my $part = shift;
4338: $part = "0" if (!defined($part));
4339:
4340: # Always return network failure if there was one.
4341: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
4342:
4343: my $now = time();
4344:
4345: my $open = $self->opendate($part);
4346: my $due = $self->duedate($part);
4347: my $answer = $self->answerdate($part);
4348:
4349: if (!$open && !$due && !$answer) {
4350: # no data on the problem at all
4351: # should this be the same as "open later"? think multipart.
4352: return $self->NOTHING_SET;
4353: }
4354: if (!$open || $now < $open) {return $self->OPEN_LATER}
4355: if (!$due || $now < $due) {return $self->OPEN}
4356: if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
4357: if ($answer) { return $self->ANSWER_OPEN; }
4358: return PAST_DUE_NO_ANSWER;
4359: }
4360:
4361: =pod
4362:
4363: B<>
4364:
4365: =over 4
4366:
4367: =item * B<getCompletionStatus>($part):
4368:
4369: ($part defaults to 0.) A convenience function that returns a symbolic
4370: constant telling you about the completion status of the part, with the
4371: following possible results:
4372:
4373: =back
4374:
4375: B<Completion Codes>
4376:
4377: =over 4
4378:
4379: =item * B<NOT_ATTEMPTED>:
4380:
4381: Has not been attempted at all.
4382:
4383: =item * B<INCORRECT>:
4384:
4385: Attempted, but wrong by student.
4386:
4387: =item * B<INCORRECT_BY_OVERRIDE>:
4388:
4389: Attempted, but wrong by instructor override.
4390:
4391: =item * B<CORRECT>:
4392:
4393: Correct or correct by instructor.
4394:
4395: =item * B<CORRECT_BY_OVERRIDE>:
4396:
4397: Correct by instructor override.
4398:
4399: =item * B<EXCUSED>:
4400:
4401: Excused. Not yet implemented.
4402:
4403: =item * B<NETWORK_FAILURE>:
4404:
4405: Information not available due to network failure.
4406:
4407: =item * B<ATTEMPTED>:
4408:
4409: Attempted, and not yet graded.
4410:
4411: =back
4412:
4413: =cut
4414:
4415: sub NOT_ATTEMPTED { return 10; }
4416: sub INCORRECT { return 11; }
4417: sub INCORRECT_BY_OVERRIDE { return 12; }
4418: sub CORRECT { return 13; }
4419: sub CORRECT_BY_OVERRIDE { return 14; }
4420: sub EXCUSED { return 15; }
4421: sub ATTEMPTED { return 16; }
4422:
4423: sub getCompletionStatus {
4424: my $self = shift;
4425: my $part = shift;
4426: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
4427:
4428: my $status = $self->queryRestoreHash('solved', $part);
4429:
4430: # Left as separate if statements in case we ever do more with this
4431: if ($status eq 'correct_by_student') {return $self->CORRECT;}
4432: if ($status eq 'correct_by_scantron') {return $self->CORRECT;}
4433: if ($status eq 'correct_by_override') {
4434: return $self->CORRECT_BY_OVERRIDE;
4435: }
4436: if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
4437: if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
4438: if ($status eq 'excused') {return $self->EXCUSED; }
4439: if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
4440: return $self->NOT_ATTEMPTED;
4441: }
4442:
4443: sub queryRestoreHash {
4444: my $self = shift;
4445: my $hashentry = shift;
4446: my $part = shift;
4447: $part = "0" if (!defined($part) || $part eq '');
4448: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
4449:
4450: $self->getReturnHash();
4451:
4452: return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
4453: }
4454:
4455: =pod
4456:
4457: B<Composite Status>
4458:
4459: Along with directly returning the date or completion status, the
4460: resource object includes a convenience function B<status>() that will
4461: combine the two status tidbits into one composite status that can
4462: represent the status of the resource as a whole. This method represents
4463: the concept of the thing we want to display to the user on the nav maps
4464: screen, which is a combination of completion and open status. The precise logic is
4465: documented in the comments of the status method. The following results
4466: may be returned, all available as methods on the resource object
4467: ($res->NETWORK_FAILURE): In addition to the return values that match
4468: the date or completion status, this function can return "ANSWER_SUBMITTED"
4469: if that problemstatus parameter value is set to No, suppressing the
4470: incorrect/correct feedback.
4471:
4472: =over 4
4473:
4474: =item * B<NETWORK_FAILURE>:
4475:
4476: The network has failed and the information is not available.
4477:
4478: =item * B<NOTHING_SET>:
4479:
4480: No dates have been set for this problem (part) at all. (Because only
4481: certain parts of a multi-part problem may be assigned, this can not be
4482: collapsed into "open later", as we do not know a given part will EVER
4483: be opened. For single part, this is the same as "OPEN_LATER".)
4484:
4485: =item * B<CORRECT>:
4486:
4487: For any reason at all, the part is considered correct.
4488:
4489: =item * B<EXCUSED>:
4490:
4491: For any reason at all, the problem is excused.
4492:
4493: =item * B<PAST_DUE_NO_ANSWER>:
4494:
4495: The problem is past due, not considered correct, and no answer date is
4496: set.
4497:
4498: =item * B<PAST_DUE_ANSWER_LATER>:
4499:
4500: The problem is past due, not considered correct, and an answer date in
4501: the future is set.
4502:
4503: =item * B<ANSWER_OPEN>:
4504:
4505: The problem is past due, not correct, and the answer is now available.
4506:
4507: =item * B<OPEN_LATER>:
4508:
4509: The problem is not yet open.
4510:
4511: =item * B<TRIES_LEFT>:
4512:
4513: The problem is open, has been tried, is not correct, but there are
4514: tries left.
4515:
4516: =item * B<INCORRECT>:
4517:
4518: The problem is open, and all tries have been used without getting the
4519: correct answer.
4520:
4521: =item * B<OPEN>:
4522:
4523: The item is open and not yet tried.
4524:
4525: =item * B<ATTEMPTED>:
4526:
4527: The problem has been attempted.
4528:
4529: =item * B<ANSWER_SUBMITTED>:
4530:
4531: An answer has been submitted, but the student should not see it.
4532:
4533: =back
4534:
4535: =cut
4536:
4537: sub TRIES_LEFT { return 20; }
4538: sub ANSWER_SUBMITTED { return 21; }
4539: sub PARTIALLY_CORRECT{ return 22; }
4540:
4541: sub status {
4542: my $self = shift;
4543: my $part = shift;
4544: if (!defined($part)) { $part = "0"; }
4545: my $completionStatus = $self->getCompletionStatus($part);
4546: my $dateStatus = $self->getDateStatus($part);
4547:
4548: # What we have is a two-dimensional matrix with 4 entries on one
4549: # dimension and 5 entries on the other, which we want to colorize,
4550: # plus network failure and "no date data at all".
4551:
4552: #if ($self->{RESOURCE_ERROR}) { return NETWORK_FAILURE; }
4553: if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
4554:
4555: my $suppressFeedback = $self->problemstatus($part) eq 'no';
4556: # If there's an answer date and we're past it, don't
4557: # suppress the feedback; student should know
4558: if ($self->duedate($part) && $self->duedate($part) < time() &&
4559: $self->answerdate($part) && $self->answerdate($part) < time()) {
4560: $suppressFeedback = 0;
4561: }
4562:
4563: # There are a few whole rows we can dispose of:
4564: if ($completionStatus == CORRECT ||
4565: $completionStatus == CORRECT_BY_OVERRIDE ) {
4566: if ( $suppressFeedback ) { return ANSWER_SUBMITTED }
4567: my $awarded=$self->awarded($part);
4568: if ($awarded < 1 && $awarded > 0) {
4569: return PARTIALLY_CORRECT;
4570: } elsif ($awarded<1) {
4571: return INCORRECT;
4572: }
4573: return CORRECT;
4574: }
4575:
4576: # If it's WRONG... and not open
4577: if ( ($completionStatus == INCORRECT ||
4578: $completionStatus == INCORRECT_BY_OVERRIDE)
4579: && (!$self->opendate($part) || $self->opendate($part) > time()) ) {
4580: return INCORRECT;
4581: }
4582:
4583: if ($completionStatus == ATTEMPTED) {
4584: return ATTEMPTED;
4585: }
4586:
4587: # If it's EXCUSED, then return that no matter what
4588: if ($completionStatus == EXCUSED) {
4589: return EXCUSED;
4590: }
4591:
4592: if ($dateStatus == NOTHING_SET) {
4593: return NOTHING_SET;
4594: }
4595:
4596: # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
4597: # by 4 matrix (date statuses).
4598:
4599: if ($dateStatus == PAST_DUE_ANSWER_LATER ||
4600: $dateStatus == PAST_DUE_NO_ANSWER ) {
4601: return $suppressFeedback ? ANSWER_SUBMITTED : $dateStatus;
4602: }
4603:
4604: if ($dateStatus == ANSWER_OPEN) {
4605: return ANSWER_OPEN;
4606: }
4607:
4608: # Now: (incorrect, incorrect_override, not_attempted) x
4609: # (open_later), (open)
4610:
4611: if ($dateStatus == OPEN_LATER) {
4612: return OPEN_LATER;
4613: }
4614:
4615: # If it's WRONG...
4616: if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
4617: # and there are TRIES LEFT:
4618: if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
4619: return $suppressFeedback ? ANSWER_SUBMITTED : TRIES_LEFT;
4620: }
4621: return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
4622: }
4623:
4624: # Otherwise, it's untried and open
4625: return OPEN;
4626: }
4627:
4628: sub CLOSED { return 23; }
4629: sub ERROR { return 24; }
4630:
4631: =pod
4632:
4633: B<Simple Status>
4634:
4635: Convenience method B<simpleStatus> provides a "simple status" for the resource.
4636: "Simple status" corresponds to "which icon is shown on the
4637: Navmaps". There are six "simple" statuses:
4638:
4639: =over 4
4640:
4641: =item * B<CLOSED>: The problem is currently closed. (No icon shown.)
4642:
4643: =item * B<OPEN>: The problem is open and unattempted.
4644:
4645: =item * B<CORRECT>: The problem is correct for any reason.
4646:
4647: =item * B<INCORRECT>: The problem is incorrect and can still be
4648: completed successfully.
4649:
4650: =item * B<ATTEMPTED>: The problem has been attempted, but the student
4651: does not know if they are correct. (The ellipsis icon.)
4652:
4653: =item * B<ERROR>: There is an error retrieving information about this
4654: problem.
4655:
4656: =back
4657:
4658: =cut
4659:
4660: # This hash maps the composite status to this simple status, and
4661: # can be used directly, if you like
4662: my %compositeToSimple =
4663: (
4664: NETWORK_FAILURE() => ERROR,
4665: NOTHING_SET() => CLOSED,
4666: CORRECT() => CORRECT,
4667: PARTIALLY_CORRECT() => PARTIALLY_CORRECT,
4668: EXCUSED() => CORRECT,
4669: PAST_DUE_NO_ANSWER() => INCORRECT,
4670: PAST_DUE_ANSWER_LATER() => INCORRECT,
4671: ANSWER_OPEN() => INCORRECT,
4672: OPEN_LATER() => CLOSED,
4673: TRIES_LEFT() => OPEN,
4674: INCORRECT() => INCORRECT,
4675: OPEN() => OPEN,
4676: ATTEMPTED() => ATTEMPTED,
4677: ANSWER_SUBMITTED() => ATTEMPTED
4678: );
4679:
4680: sub simpleStatus {
4681: my $self = shift;
4682: my $part = shift;
4683: my $status = $self->status($part);
4684: return $compositeToSimple{$status};
4685: }
4686:
4687: =pod
4688:
4689: B<simpleStatusCount> will return an array reference containing, in
4690: this order, the number of OPEN, CLOSED, CORRECT, INCORRECT, ATTEMPTED,
4691: and ERROR parts the given problem has.
4692:
4693: =cut
4694:
4695: # This maps the status to the slot we want to increment
4696: my %statusToSlotMap =
4697: (
4698: OPEN() => 0,
4699: CLOSED() => 1,
4700: CORRECT() => 2,
4701: INCORRECT() => 3,
4702: ATTEMPTED() => 4,
4703: ERROR() => 5
4704: );
4705:
4706: sub statusToSlot { return $statusToSlotMap{shift()}; }
4707:
4708: sub simpleStatusCount {
4709: my $self = shift;
4710:
4711: my @counts = (0, 0, 0, 0, 0, 0, 0);
4712: foreach my $part (@{$self->parts()}) {
4713: $counts[$statusToSlotMap{$self->simpleStatus($part)}]++;
4714: }
4715:
4716: return \@counts;
4717: }
4718:
4719: =pod
4720:
4721: B<Completable>
4722:
4723: The completable method represents the concept of I<whether the student can
4724: currently do the problem>. If the student can do the problem, which means
4725: that it is open, there are tries left, and if the problem is manually graded
4726: or the grade is suppressed via problemstatus, the student has not tried it
4727: yet, then the method returns 1. Otherwise, it returns 0, to indicate that
4728: either the student has tried it and there is no feedback, or that for
4729: some reason it is no longer completable (not open yet, successfully completed,
4730: out of tries, etc.). As an example, this is used as the filter for the
4731: "Uncompleted Homework" option for the nav maps.
4732:
4733: If this does not quite meet your needs, do not fiddle with it (unless you are
4734: fixing it to better match the student's conception of "completable" because
4735: it's broken somehow)... make a new method.
4736:
4737: =cut
4738:
4739: sub completable {
4740: my $self = shift;
4741: if (!$self->is_problem()) { return 0; }
4742: my $partCount = $self->countParts();
4743:
4744: foreach my $part (@{$self->parts()}) {
4745: if ($part eq '0' && $partCount != 1) { next; }
4746: my $status = $self->status($part);
4747: # "If any of the parts are open, or have tries left (implies open),
4748: # and it is not "attempted" (manually graded problem), it is
4749: # not "complete"
4750: if ($self->getCompletionStatus($part) == ATTEMPTED() ||
4751: $status == ANSWER_SUBMITTED() ) {
4752: # did this part already, as well as we can
4753: next;
4754: }
4755: if ($status == OPEN() || $status == TRIES_LEFT()) {
4756: return 1;
4757: }
4758: }
4759:
4760: # If all the parts were complete, so was this problem.
4761: return 0;
4762: }
4763:
4764: =pod
4765:
4766: =head2 Resource/Nav Map Navigation
4767:
4768: =over 4
4769:
4770: =item * B<getNext>():
4771:
4772: Retreive an array of the possible next resources after this
4773: one. Always returns an array, even in the one- or zero-element case.
4774:
4775: =item * B<getPrevious>():
4776:
4777: Retreive an array of the possible previous resources from this
4778: one. Always returns an array, even in the one- or zero-element case.
4779:
4780: =cut
4781:
4782: sub getNext {
4783: my $self = shift;
4784: my @branches;
4785: my $to = $self->to();
4786: foreach my $branch ( split(/,/, $to) ) {
4787: my $choice = $self->{NAV_MAP}->getById($branch);
4788: #if (!$choice->condition()) { next; }
4789: my $next = $choice->goesto();
4790: $next = $self->{NAV_MAP}->getById($next);
4791:
4792: push @branches, $next;
4793: }
4794: return \@branches;
4795: }
4796:
4797: sub getPrevious {
4798: my $self = shift;
4799: my @branches;
4800: my $from = $self->from();
4801: foreach my $branch ( split /,/, $from) {
4802: my $choice = $self->{NAV_MAP}->getById($branch);
4803: my $prev = $choice->comesfrom();
4804: $prev = $self->{NAV_MAP}->getById($prev);
4805:
4806: push @branches, $prev;
4807: }
4808: return \@branches;
4809: }
4810:
4811: sub browsePriv {
4812: my $self = shift;
4813: if (defined($self->{BROWSE_PRIV})) {
4814: return $self->{BROWSE_PRIV};
4815: }
4816:
4817: $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre',$self->src(),
4818: $self->symb());
4819: }
4820:
4821: =pod
4822:
4823: =back
4824:
4825: =cut
4826:
4827: 1;
4828:
4829: __END__
4830:
4831:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>