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