Annotation of loncom/interface/lonnavmaps.pm, revision 1.155
1.72 bowersj2 1:
1.2 www 2: # The LearningOnline Network with CAPA
3: # Navigate Maps Handler
1.1 www 4: #
1.153 bowersj2 5: # $Id: lonnavmaps.pm,v 1.152 2003/03/04 22:30:10 matthew Exp $
1.20 albertel 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
1.2 www 29: # (Page Handler
1.1 www 30: #
1.2 www 31: # (TeX Content Handler
1.1 www 32: #
1.2 www 33: # 05/29/00,05/30 Gerd Kortemeyer)
34: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
35: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
1.1 www 36: #
1.17 www 37: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
1.21 www 38: # YEAR=2002
39: # 1/1 Gerd Kortemeyer
1.105 bowersj2 40: # Oct-Nov Jeremy Bowers
1.153 bowersj2 41: # YEAR=2003
42: # Jeremy Bowers ... lots of days
1.2 www 43:
1.1 www 44: package Apache::lonnavmaps;
45:
46: use strict;
1.2 www 47: use Apache::Constants qw(:common :http);
1.18 albertel 48: use Apache::loncommon();
1.150 www 49: use Apache::lonmenu();
1.73 bowersj2 50: use POSIX qw (floor strftime);
1.2 www 51:
1.130 www 52: my %navmaphash;
53: my %parmhash;
54:
1.133 bowersj2 55: # symbolic constants
56: sub SYMB { return 1; }
57: sub URL { return 2; }
58: sub NOTHING { return 3; }
59:
60: # Some data
61:
1.140 bowersj2 62: my $resObj = "Apache::lonnavmaps::resource";
63:
1.135 bowersj2 64: # Keep these mappings in sync with lonquickgrades, which uses the colors
65: # instead of the icons.
66: my %statusIconMap =
1.140 bowersj2 67: ( $resObj->NETWORK_FAILURE => '',
68: $resObj->NOTHING_SET => '',
69: $resObj->CORRECT => 'navmap.correct.gif',
70: $resObj->EXCUSED => 'navmap.correct.gif',
71: $resObj->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
72: $resObj->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
73: $resObj->ANSWER_OPEN => 'navmap.wrong.gif',
74: $resObj->OPEN_LATER => '',
75: $resObj->TRIES_LEFT => 'navmap.open.gif',
76: $resObj->INCORRECT => 'navmap.wrong.gif',
77: $resObj->OPEN => 'navmap.open.gif',
78: $resObj->ATTEMPTED => 'navmap.open.gif' );
1.135 bowersj2 79:
80: my %iconAltTags =
81: ( 'navmap.correct.gif' => 'Correct',
82: 'navmap.wrong.gif' => 'Incorrect',
83: 'navmap.open.gif' => 'Open' );
1.133 bowersj2 84:
1.136 bowersj2 85: # Defines a status->color mapping, null string means don't color
86: my %colormap =
1.140 bowersj2 87: ( $resObj->NETWORK_FAILURE => '',
88: $resObj->CORRECT => '',
89: $resObj->EXCUSED => '#3333FF',
90: $resObj->PAST_DUE_ANSWER_LATER => '',
91: $resObj->PAST_DUE_NO_ANSWER => '',
92: $resObj->ANSWER_OPEN => '#006600',
93: $resObj->OPEN_LATER => '',
94: $resObj->TRIES_LEFT => '',
95: $resObj->INCORRECT => '',
96: $resObj->OPEN => '',
97: $resObj->NOTHING_SET => '' );
1.136 bowersj2 98: # And a special case in the nav map; what to do when the assignment
99: # is not yet done and due in less then 24 hours
100: my $hurryUpColor = "#FF0000";
101:
1.130 www 102: sub cleanup {
103: if (tied(%navmaphash)){
104: &Apache::lonnet::logthis('Cleanup navmaps: navmaphash');
105: unless (untie(%navmaphash)) {
106: &Apache::lonnet::logthis('Failed cleanup navmaps: navmaphash');
107: }
108: }
109: if (tied(%parmhash)){
110: &Apache::lonnet::logthis('Cleanup navmaps: parmhash');
111: unless (untie(%parmhash)) {
112: &Apache::lonnet::logthis('Failed cleanup navmaps: parmhash');
113: }
114: }
115: }
116:
1.1 www 117: sub handler {
1.99 bowersj2 118: my $r = shift;
1.118 bowersj2 119: real_handler($r);
120: }
121:
122: sub real_handler {
123: my $r = shift;
1.2 www 124:
1.51 bowersj2 125: # Handle header-only request
126: if ($r->header_only) {
127: if ($ENV{'browser.mathml'}) {
128: $r->content_type('text/xml');
129: } else {
130: $r->content_type('text/html');
131: }
132: $r->send_http_header;
133: return OK;
134: }
135:
136: # Send header, don't cache this page
137: if ($ENV{'browser.mathml'}) {
138: $r->content_type('text/xml');
139: } else {
140: $r->content_type('text/html');
141: }
142: &Apache::loncommon::no_cache($r);
143: $r->send_http_header;
144:
1.106 bowersj2 145: # Create the nav map
1.51 bowersj2 146: my $navmap = Apache::lonnavmaps::navmap->new(
147: $ENV{"request.course.fn"}.".db",
1.80 bowersj2 148: $ENV{"request.course.fn"}."_parms.db", 1, 1);
1.51 bowersj2 149:
1.55 bowersj2 150:
151: if (!defined($navmap)) {
152: my $requrl = $r->uri;
153: $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
154: return HTTP_NOT_ACCEPTABLE;
155: }
1.64 bowersj2 156:
1.111 bowersj2 157: $r->print("<html><head>\n");
1.150 www 158: $r->print("<title>Navigate Course Contents</title>");
159: # ------------------------------------------------------------ Get query string
160: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register']);
161: # ----------------------------------------------------- Force menu registration
162: my $addentries='';
163: if ($ENV{'form.register'}) {
164: $addentries=' onLoad="'.&Apache::lonmenu::loadevents().
165: '" onUnload="'.&Apache::lonmenu::unloadevents().'"';
166: $r->print(&Apache::lonmenu::registerurl(1));
167: }
1.111 bowersj2 168:
1.64 bowersj2 169: # Header
1.150 www 170: $r->print('</head>'.
171: &Apache::loncommon::bodytag('Navigate Course Contents','',
1.151 www 172: $addentries,'','',$ENV{'form.register'}));
1.64 bowersj2 173: $r->print('<script>window.focus();</script>');
1.101 bowersj2 174:
1.124 bowersj2 175: $r->rflush();
176:
177: # Now that we've displayed some stuff to the user, init the navmap
178: $navmap->init();
179:
1.55 bowersj2 180:
1.95 bowersj2 181: $r->print('<br> ');
182: $r->rflush();
183:
1.55 bowersj2 184: # Check that it's defined
185: if (!($navmap->courseMapDefined())) {
186: $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
187: '</body></html>');
188: return OK;
189: }
190:
1.155 ! bowersj2 191: # See if there's only one map in the top-level... if so,
! 192: # automatically display it
! 193: my $iterator = $navmap->getIterator(undef, undef, undef, 0);
! 194: my $depth = 1;
! 195: $iterator->next();
! 196: my $curRes = $iterator->next();
! 197: my $sequenceCount = 0;
! 198: my $sequenceId;
! 199: while ($depth > 0) {
! 200: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
! 201: if ($curRes == $iterator->END_MAP()) { $depth--; }
! 202:
! 203: if (ref($curRes) && $curRes->is_sequence()) {
! 204: $sequenceCount++;
! 205: $sequenceId = $curRes->map_pc();
! 206: }
! 207:
! 208: $curRes = $iterator->next();
! 209: }
! 210:
! 211: if ($sequenceCount == 1) {
! 212: # The automatic iterator creation in the render call
! 213: # will pick this up.
! 214: $ENV{'form.filter'} = "$sequenceId";
! 215: }
! 216:
1.133 bowersj2 217: # renderer call
1.140 bowersj2 218: my $render = render({ 'cols' => [0,1,2,3],
219: 'url' => '/adm/navmaps',
1.153 bowersj2 220: 'suppressNavmap' => 1,
1.140 bowersj2 221: 'r' => $r});
1.133 bowersj2 222:
1.126 bowersj2 223: $navmap->untieHashes();
1.51 bowersj2 224:
1.128 bowersj2 225: $r->print("</body></html>");
1.134 bowersj2 226: $r->rflush();
1.59 bowersj2 227:
1.51 bowersj2 228: return OK;
229: }
230:
231: # Convenience functions: Returns a string that adds or subtracts
232: # the second argument from the first hash, appropriate for the
233: # query string that determines which folders to recurse on
234: sub addToFilter {
235: my $hashIn = shift;
236: my $addition = shift;
237: my %hash = %$hashIn;
238: $hash{$addition} = 1;
239:
240: return join (",", keys(%hash));
241: }
242:
243: sub removeFromFilter {
244: my $hashIn = shift;
245: my $subtraction = shift;
246: my %hash = %$hashIn;
247:
248: delete $hash{$subtraction};
249: return join(",", keys(%hash));
250: }
251:
252: # Convenience function: Given a stack returned from getStack on the iterator,
253: # return the correct src() value.
254: # Later, this should add an anchor when we start putting anchors in pages.
255: sub getLinkForResource {
256: my $stack = shift;
257: my $res;
258:
259: # Check to see if there are any pages in the stack
260: foreach $res (@$stack) {
261: if (defined($res) && $res->is_page()) {
262: return $res->src();
263: }
264: }
265:
266: # Failing that, return the src of the last resource that is defined
267: # (when we first recurse on a map, it puts an undefined resource
268: # on the bottom because $self->{HERE} isn't defined yet, and we
269: # want the src for the map anyhow)
270: foreach (@$stack) {
271: if (defined($_)) { $res = $_; }
272: }
273:
274: return $res->src();
275: }
276:
1.53 bowersj2 277: # Convenience function: This seperates the logic of how to create
278: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
279: # etc.) into a seperate function. It takes a resource object as the
280: # first parameter, and the part number of the resource as the second.
281: # It's basically a big switch statement on the status of the resource.
282:
283: sub getDescription {
284: my $res = shift;
285: my $part = shift;
1.69 bowersj2 286: my $status = $res->status($part);
1.53 bowersj2 287:
288: if ($status == $res->NETWORK_FAILURE) { return ""; }
289: if ($status == $res->NOTHING_SET) {
290: return "Not currently assigned.";
291: }
292: if ($status == $res->OPEN_LATER) {
1.73 bowersj2 293: return "Open " . timeToHumanString($res->opendate($part));
1.53 bowersj2 294: }
295: if ($status == $res->OPEN) {
1.79 bowersj2 296: if ($res->duedate($part)) {
1.73 bowersj2 297: return "Due " . timeToHumanString($res->duedate($part));
1.66 bowersj2 298: } else {
299: return "Open, no due date";
300: }
1.53 bowersj2 301: }
1.54 bowersj2 302: if ($status == $res->PAST_DUE_ANSWER_LATER) {
1.73 bowersj2 303: return "Answer open " . timeToHumanString($res->answerdate($part));
1.54 bowersj2 304: }
305: if ($status == $res->PAST_DUE_NO_ANSWER) {
1.73 bowersj2 306: return "Was due " . timeToHumanString($res->duedate($part));
1.53 bowersj2 307: }
308: if ($status == $res->ANSWER_OPEN) {
309: return "Answer available";
310: }
1.59 bowersj2 311: if ($status == $res->EXCUSED) {
1.66 bowersj2 312: return "Excused by instructor";
1.59 bowersj2 313: }
1.69 bowersj2 314: if ($status == $res->ATTEMPTED) {
315: return "Not yet graded.";
316: }
1.59 bowersj2 317: if ($status == $res->TRIES_LEFT) {
1.79 bowersj2 318: my $tries = $res->tries($part);
319: my $maxtries = $res->maxtries($part);
320: my $triesString = "";
321: if ($tries && $maxtries) {
322: $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
323: if ($maxtries > 1 && $maxtries - $tries == 1) {
324: $triesString = "<b>$triesString</b>";
325: }
326: }
1.66 bowersj2 327: if ($res->duedate()) {
1.73 bowersj2 328: return "Due " . timeToHumanString($res->duedate($part)) .
1.66 bowersj2 329: " $triesString";
330: } else {
331: return "No due date $triesString";
332: }
1.59 bowersj2 333: }
1.53 bowersj2 334: }
335:
1.115 bowersj2 336: # Convenience function, so others can use it: Is the problem due in less then
337: # 24 hours, and still can be done?
338:
339: sub dueInLessThen24Hours {
340: my $res = shift;
341: my $part = shift;
342: my $status = $res->status($part);
343:
344: return ($status == $res->OPEN() || $status == $res->ATTEMPTED() ||
345: $status == $res->TRIES_LEFT()) &&
346: $res->duedate() && $res->duedate() < time()+(24*60*60) &&
347: $res->duedate() > time();
348: }
349:
350: # Convenience function, so others can use it: Is there only one try remaining for the
351: # part, with more then one try to begin with, not due yet and still can be done?
352: sub lastTry {
353: my $res = shift;
354: my $part = shift;
355:
356: my $tries = $res->tries($part);
357: my $maxtries = $res->maxtries($part);
358: return $tries && $maxtries && $maxtries > 1 &&
359: $maxtries - $tries == 1 && $res->duedate() &&
360: $res->duedate() > time();
361: }
362:
1.101 bowersj2 363: # This puts a human-readable name on the ENV variable.
1.68 bowersj2 364: sub advancedUser {
365: return $ENV{'user.adv'};
366: }
367:
1.73 bowersj2 368:
369: # timeToHumanString takes a time number and converts it to a
370: # human-readable representation, meant to be used in the following
371: # manner:
372: # print "Due $timestring"
373: # print "Open $timestring"
374: # print "Answer available $timestring"
375: # Very, very, very, VERY English-only... goodness help a localizer on
376: # this func...
1.53 bowersj2 377: sub timeToHumanString {
1.58 albertel 378: my ($time) = @_;
379: # zero, '0' and blank are bad times
1.73 bowersj2 380: if (!$time) {
381: return 'never';
382: }
383:
384: my $now = time();
385:
386: my @time = localtime($time);
387: my @now = localtime($now);
388:
389: # Positive = future
390: my $delta = $time - $now;
391:
392: my $minute = 60;
393: my $hour = 60 * $minute;
394: my $day = 24 * $hour;
395: my $week = 7 * $day;
396: my $inPast = 0;
397:
398: # Logic in comments:
399: # Is it now? (extremely unlikely)
400: if ( $delta == 0 ) {
401: return "this instant";
402: }
403:
404: if ($delta < 0) {
405: $inPast = 1;
406: $delta = -$delta;
407: }
408:
409: if ( $delta > 0 ) {
1.101 bowersj2 410:
1.73 bowersj2 411: my $tense = $inPast ? " ago" : "";
412: my $prefix = $inPast ? "" : "in ";
1.101 bowersj2 413:
414: # Less then a minute
1.73 bowersj2 415: if ( $delta < $minute ) {
416: if ($delta == 1) { return "${prefix}1 second$tense"; }
417: return "$prefix$delta seconds$tense";
418: }
419:
1.101 bowersj2 420: # Less then an hour
1.73 bowersj2 421: if ( $delta < $hour ) {
422: # If so, use minutes
423: my $minutes = floor($delta / 60);
424: if ($minutes == 1) { return "${prefix}1 minute$tense"; }
425: return "$prefix$minutes minutes$tense";
426: }
427:
428: # Is it less then 24 hours away? If so,
429: # display hours + minutes
430: if ( $delta < $hour * 24) {
431: my $hours = floor($delta / $hour);
432: my $minutes = floor(($delta % $hour) / $minute);
433: my $hourString = "$hours hours";
434: my $minuteString = ", $minutes minutes";
435: if ($hours == 1) {
436: $hourString = "1 hour";
437: }
438: if ($minutes == 1) {
439: $minuteString = ", 1 minute";
440: }
441: if ($minutes == 0) {
442: $minuteString = "";
443: }
444: return "$prefix$hourString$minuteString$tense";
445: }
446:
447: # Less then 5 days away, display day of the week and
448: # HH:MM
449: if ( $delta < $day * 5 ) {
1.85 bowersj2 450: my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
1.73 bowersj2 451: $timeStr =~ s/12:00 am/midnight/;
452: $timeStr =~ s/12:00 pm/noon/;
453: return ($inPast ? "last " : "next ") .
454: $timeStr;
455: }
456:
457: # Is it this year?
458: if ( $time[5] == $now[5]) {
459: # Return on Month Day, HH:MM meridian
460: my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
461: $timeStr =~ s/12:00 am/midnight/;
462: $timeStr =~ s/12:00 pm/noon/;
463: return $timeStr;
464: }
465:
466: # Not this year, so show the year
467: my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
468: $timeStr =~ s/12:00 am/midnight/;
469: $timeStr =~ s/12:00 pm/noon/;
470: return $timeStr;
1.58 albertel 471: }
1.53 bowersj2 472: }
473:
1.51 bowersj2 474:
1.133 bowersj2 475: =pod
476:
477: =head1 navmap renderer
478:
479: The navmaprenderer package provides a sophisticated rendering of the standard navigation maps interface into HTML. The provided nav map handler is actually just a glorified call to this.
480:
481: Because of the large number of parameters this function presents, instead of passing it arguments as is normal, pass it in an anonymous hash with the given options. This is because there is no obvious order you may wish to override these in and a hash is easier to read and understand then "undef, undef, undef, 1, undef, undef, renderButton, undef, 0" when you mostly want default behaviors.
482:
483: The package provides a function called 'render', called as Apache::lonnavmaps::renderer->render({}).
1.51 bowersj2 484:
1.133 bowersj2 485: =head2 Overview of Columns
1.51 bowersj2 486:
1.133 bowersj2 487: The renderer will build an HTML table for the navmap and return it. The table is consists of several columns, and a row for each resource (or possibly each part). You tell the renderer how many columns to create and what to place in each column, optionally using one or more of the preparent columns, and the renderer will assemble the table.
1.51 bowersj2 488:
1.133 bowersj2 489: Any additional generally useful column types should be placed in the renderer code here, so anybody can use it anywhere else. Any code specific to the current application (such as the addition of <input> elements in a column) should be placed in the code of the thing using the renderer.
1.51 bowersj2 490:
1.133 bowersj2 491: At the core of the renderer is the array reference COLS (see Example section below for how to pass this correctly). The COLS array will consist of entries of one of two types of things: Either an integer representing one of the pre-packaged column types, or a sub reference that takes a resource reference, a part number, and a reference to the argument hash passed to the renderer, and returns a string that will be inserted into the HTML representation as it.
1.51 bowersj2 492:
1.133 bowersj2 493: The pre-packaged column names are refered to by constants in the Apache::lonnavmaps::renderer namespace. The following currently exist:
1.51 bowersj2 494:
1.133 bowersj2 495: =over 4
1.51 bowersj2 496:
1.133 bowersj2 497: =item * B<resource>: The general info about the resource: Link, icon for the type, etc. The first column in the standard nav map display. This column also accepts the following parameter in the renderer hash:
1.51 bowersj2 498:
499: =over 4
500:
1.133 bowersj2 501: =item * B<resource_nolink>: If true, the resource will not be linked. Default: false, resource will have links.
502:
503: =item * B<resource_part_count>: If true (default), the resource will show a part count if the full part list is not displayed. If false, the resource will never show a part count.
504:
1.144 bowersj2 505: =item * B<resource_no_folder_link>: If true, the resource's folder will not be clickable to open or close it. Default is false.
506:
1.133 bowersj2 507: =back
1.51 bowersj2 508:
1.133 bowersj2 509: =item B<communication_status>: Whether there is discussion on the resource, email for the user, or (lumped in here) perl errors in the execution of the problem. This is the second column in the main nav map.
1.51 bowersj2 510:
1.133 bowersj2 511: =item B<quick_status>: An icon for the status of a problem, with four possible states: Correct, incorrect, open, or none (not open yet, not a problem). The third column of the standard navmap.
1.51 bowersj2 512:
1.133 bowersj2 513: =item B<long_status>: A text readout of the details of the current status of the problem, such as "Due in 22 hours". The fourth column of the standard navmap.
1.51 bowersj2 514:
1.133 bowersj2 515: =back
1.51 bowersj2 516:
1.133 bowersj2 517: If you add any others please be sure to document them here.
1.51 bowersj2 518:
1.133 bowersj2 519: An example of a column renderer that will show the ID number of a resource, along with the part name if any:
1.51 bowersj2 520:
1.133 bowersj2 521: sub {
522: my ($resource, $part, $params) = @_;
523: if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
524: return '<td>' . $resource->{ID} . '</td>';
525: }
1.51 bowersj2 526:
1.133 bowersj2 527: Note these functions are responsible for the TD tags, which allow them to override vertical and horizontal alignment, etc.
1.130 www 528:
1.133 bowersj2 529: =head2 Parameters
1.115 bowersj2 530:
1.140 bowersj2 531: Most of these parameters are only useful if you are *not* using the folder interface (i.e., the default first column), which is probably the common case. If you are using this interface, then you should be able to get away with just using 'cols' (to specify the columns shown), 'url' (necessary for the folders to link to the current screen correctly), and possibly 'queryString' if your app calls for it. In that case, maintaining the state of the folders will be done automatically.
532:
1.133 bowersj2 533: =over 4
1.51 bowersj2 534:
1.144 bowersj2 535: =item * B<iterator>: A reference to a fresh ::iterator to use from the navmaps. The rendering will reflect the options passed to the iterator, so you can use that to just render a certain part of the course, if you like. If one is not passed, the renderer will attempt to construct one from ENV{'form.filter'} and ENV{'form.condition'} information, plus the 'iterator_map' parameter if any.
536:
537: =item * B<iterator_map>: If you are letting the renderer do the iterator handling, you can instruct the renderer to render only a particular map by passing it the source of the map you want to process, like '/res/103/jerf/navmap.course.sequence'.
1.140 bowersj2 538:
539: =item * B<navmap>: A reference to a navmap, used only if an iterator is not passed in. If this is necessary to make an iterator but it is not passed in, a new one will be constructed based on ENV info. This is useful to do basic error checking before passing it off to render.
1.92 bowersj2 540:
1.133 bowersj2 541: =item * B<cols>: An array reference
1.92 bowersj2 542:
1.133 bowersj2 543: =item * B<showParts>: A flag. If yes (default), a line for the resource itself, and a line for each part will be displayed. If not, only one line for each resource will be displayed.
1.51 bowersj2 544:
1.133 bowersj2 545: =item * B<condenseParts>: A flag. If yes (default), if all parts of the problem have the same status and that status is Nothing Set, Correct, or Network Failure, then only one line will be displayed for that resource anyhow. If no, all parts will always be displayed. If showParts is 0, this is ignored.
1.55 bowersj2 546:
1.140 bowersj2 547: =item * B<jumpCount>: A string identifying the URL to place the anchor 'curloc' at. Default to no anchor at all. It is the responsibility of the renderer user to ensure that the #curloc is in the URL. By default, determined through the use of the ENV{} 'jump' and 'jumpType' information.
1.84 bowersj2 548:
1.140 bowersj2 549: =item * B<hereURL>: A URL identifying where to place the 'here' marker. By default, will pull this from the ENV{'form.here*'} info.
1.51 bowersj2 550:
1.140 bowersj2 551: =item * B<hereSymb>: A Symb identifying where to place the 'here' marker. Default same as hereURL.
1.115 bowersj2 552:
1.133 bowersj2 553: =item * B<indentString>: A string identifying the indentation string to use. By default, this is a 25 pixel whitespace image with no alt text.
1.55 bowersj2 554:
1.133 bowersj2 555: =item * B<queryString>: A string which will be prepended to the query string used when the folders are opened or closed.
1.51 bowersj2 556:
1.133 bowersj2 557: =item * B<url>: The url the folders will link to, which should be the current page. Required if the resource info column is shown.
1.51 bowersj2 558:
1.140 bowersj2 559: =item * B<currentJumpIndex>: Describes the currently-open row number to cause the browser to jump to, because the user just opened that folder. By default, pulled from the Jump information in the ENV{'form.*'}.
1.139 bowersj2 560:
561: =item * B<r>: The standard Apache response object. If you pass this to the render, it will use it to flush the table every 20 rows and handle the rendering itself.
562:
1.140 bowersj2 563: =item * B<printKey>: If true, print the key that appears on the top of the standard navmaps. Default is false.
564:
565: =item * B<printCloseAll>: If true, print the "Close all folders" or "open all folders" links. Default is true.
566:
1.153 bowersj2 567: =item * B<filterFunc>: A function that takes the resource object as its only parameter and returns a true or false value. If true, the resource is displayed. If false, it is simply skipped in the display. By default, all resources are shown.
568:
569: =item * B<suppressNavmaps>: If true, will not display Navigate Content resources. Default to false.
1.143 bowersj2 570:
1.133 bowersj2 571: =back
1.51 bowersj2 572:
1.133 bowersj2 573: =head2 Additional Info
1.51 bowersj2 574:
1.133 bowersj2 575: In addition to the parameters you can pass to the renderer, which will be passed through unchange to the column renderers, the renderer will generate the following information which your renderer may find useful:
1.59 bowersj2 576:
1.145 bowersj2 577: If you want to know how many rows were printed, the 'counter' element of the hash passed into the render function will contain the count. You may want to check whether any resources were printed at all.
578:
1.133 bowersj2 579: =over 4
1.59 bowersj2 580:
1.133 bowersj2 581: =back
1.59 bowersj2 582:
1.133 bowersj2 583: =cut
1.59 bowersj2 584:
1.133 bowersj2 585: sub resource { return 0; }
586: sub communication_status { return 1; }
587: sub quick_status { return 2; }
588: sub long_status { return 3; }
1.124 bowersj2 589:
1.133 bowersj2 590: # Data for render_resource
1.51 bowersj2 591:
1.133 bowersj2 592: sub render_resource {
593: my ($resource, $part, $params) = @_;
1.51 bowersj2 594:
1.133 bowersj2 595: my $nonLinkedText = ''; # stuff after resource title not in link
1.51 bowersj2 596:
1.134 bowersj2 597: my $link = $params->{"resourceLink"};
598: my $src = $resource->src();
599: my $it = $params->{"iterator"};
1.133 bowersj2 600: my $filter = $it->{FILTER};
601:
602: my $title = $resource->compTitle();
603: if ($src =~ /^\/uploaded\//) {
604: $nonLinkedText=$title;
605: $title = '';
606: }
607: my $partLabel = "";
608: my $newBranchText = "";
609:
610: # If this is a new branch, label it so
611: if ($params->{'isNewBranch'}) {
612: $newBranchText = "<img src='/adm/lonIcons/branch.gif' border='0' />";
1.51 bowersj2 613: }
614:
1.133 bowersj2 615: # links to open and close the folder
616: my $linkopen = "<a href='$link'>";
617: my $linkclose = "</a>";
1.51 bowersj2 618:
1.133 bowersj2 619: # Default icon: HTML page
620: my $icon = "<img src='/adm/lonIcons/html.gif' alt='' border='0' />";
621:
622: if ($resource->is_problem()) {
623: if ($part eq "0" || $params->{'condensed'}) {
624: $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border="0" />';
625: } else {
626: $icon = $params->{'indentString'};
627: }
628: }
1.51 bowersj2 629:
1.133 bowersj2 630: # Display the correct map icon to open or shut map
631: if ($resource->is_map()) {
632: my $mapId = $resource->map_pc();
633: my $nowOpen = !defined($filter->{$mapId});
634: if ($it->{CONDITION}) {
635: $nowOpen = !$nowOpen;
636: }
1.144 bowersj2 637:
638: if (!$params->{'resource_no_folder_link'}) {
639: $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') . '.gif';
640: $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
641:
642: $linkopen = "<a href='" . $params->{'url'} . '?' .
643: $params->{'queryString'} . '&filter=';
644: $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
645: addToFilter($filter, $mapId) :
646: removeFromFilter($filter, $mapId);
647: $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
648: . $params->{'hereType'} . '&here=' .
649: &Apache::lonnet::escape($params->{'here'}) .
650: '&jumpType=' . SYMB() . '&jump=' .
651: &Apache::lonnet::escape($resource->symb()) .
652: "&folderManip=1'>";
653: } else {
654: # Don't allow users to manipulate folder
655: $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') .
656: '.nomanip.gif';
657: $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
658:
659: $linkopen = "";
660: $linkclose = "";
661: }
1.133 bowersj2 662: }
1.51 bowersj2 663:
1.133 bowersj2 664: if ($resource->randomout()) {
665: $nonLinkedText .= ' <i>(hidden)</i> ';
666: }
667:
668: # We're done preparing and finally ready to start the rendering
669: my $result = "<td align='left' valign='center'>";
1.140 bowersj2 670:
671: my $indentLevel = $params->{'indentLevel'};
672: if ($newBranchText) { $indentLevel--; }
673:
1.133 bowersj2 674: # print indentation
1.140 bowersj2 675: for (my $i = 0; $i < $indentLevel; $i++) {
1.133 bowersj2 676: $result .= $params->{'indentString'};
1.84 bowersj2 677: }
678:
1.133 bowersj2 679: # Decide what to display
680: $result .= "$newBranchText$linkopen$icon$linkclose";
681:
682: my $curMarkerBegin = '';
683: my $curMarkerEnd = '';
1.51 bowersj2 684:
1.133 bowersj2 685: # Is this the current resource?
686: if (!$params->{'displayedHereMarker'} &&
687: (($params->{'hereType'} == SYMB() &&
688: $resource->symb() eq $params->{'here'}) ||
689: ($params->{'hereType'} == URL() &&
690: $resource->src() eq $params->{'here'}))) {
691: $curMarkerBegin = '<font color="red" size="+2">> </font>';
692: $curMarkerEnd = '<font color="red" size="+2"><</font>';
1.51 bowersj2 693: }
694:
1.133 bowersj2 695: if ($resource->is_problem() && $part ne "0" &&
696: !$params->{'condensed'}) {
697: $partLabel = " (Part $part)";
698: $title = "";
1.51 bowersj2 699: }
700:
1.133 bowersj2 701: if ($params->{'multipart'} && $params->{'condensed'}) {
702: $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
1.51 bowersj2 703: }
704:
1.144 bowersj2 705: if (!$params->{'resource_nolink'}) {
706: $result .= " $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
707: } else {
708: $result .= " $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
709: }
1.51 bowersj2 710:
1.133 bowersj2 711: return $result;
712: }
1.51 bowersj2 713:
1.133 bowersj2 714: sub render_communication_status {
715: my ($resource, $part, $params) = @_;
1.134 bowersj2 716: my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
717:
718: my $link = $params->{"resourceLink"};
719: my $linkopen = "<a href='$link'>";
720: my $linkclose = "</a>";
721:
722: if ($resource->hasDiscussion()) {
723: $discussionHTML = $linkopen .
724: '<img border="0" src="/adm/lonMisc/chat.gif" />' .
725: $linkclose;
726: }
727:
728: if ($resource->getFeedback()) {
729: my $feedback = $resource->getFeedback();
730: foreach (split(/\,/, $feedback)) {
731: if ($_) {
732: $feedbackHTML .= ' <a href="/adm/email?display='
733: . &Apache::lonnet::escape($_) . '">'
734: . '<img src="/adm/lonMisc/feedback.gif" '
735: . 'border="0" /></a>';
736: }
737: }
738: }
739:
740: if ($resource->getErrors()) {
741: my $errors = $resource->getErrors();
742: foreach (split(/,/, $errors)) {
743: if ($_) {
744: $errorHTML .= ' <a href="/adm/email?display='
745: . &Apache::lonnet::escape($_) . '">'
746: . '<img src="/adm/lonMisc/bomb.gif" '
747: . 'border="0" /></a>';
748: }
749: }
750: }
751:
752: return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML </td>";
753:
1.133 bowersj2 754: }
755: sub render_quick_status {
756: my ($resource, $part, $params) = @_;
1.135 bowersj2 757: my $result = "";
758: my $firstDisplayed = !$params->{'condensed'} &&
759: $params->{'multipart'} && $part eq "0";
760:
761: my $link = $params->{"resourceLink"};
762: my $linkopen = "<a href='$link'>";
763: my $linkclose = "</a>";
764:
765: if ($resource->is_problem() &&
766: !$firstDisplayed) {
767: my $icon = $statusIconMap{$resource->status($part)};
768: my $alt = $iconAltTags{$icon};
769: if ($icon) {
770: $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";
771: } else {
772: $result .= "<td width='30'> </td>\n";
773: }
774: } else { # not problem, no icon
775: $result .= "<td width='30'> </td>\n";
776: }
777:
778: return $result;
1.133 bowersj2 779: }
780: sub render_long_status {
781: my ($resource, $part, $params) = @_;
1.136 bowersj2 782: my $result = "<td align='right' valign='center'>\n";
783: my $firstDisplayed = !$params->{'condensed'} &&
784: $params->{'multipart'} && $part eq "0";
785:
786: my $color;
787: if ($resource->is_problem()) {
788: $color = $colormap{$resource->status};
789:
790: if (dueInLessThen24Hours($resource, $part) ||
791: lastTry($resource, $part)) {
792: $color = $hurryUpColor;
793: }
794: }
795:
796: if ($resource->kind() eq "res" &&
797: $resource->is_problem() &&
798: !$firstDisplayed) {
799: if ($color) {$result .= "<font color=\"$color\"><b>"; }
800: $result .= getDescription($resource, $part);
801: if ($color) {$result .= "</b></font>"; }
802: }
803: if ($resource->is_map() && advancedUser() && $resource->randompick()) {
804: $result .= '(randomly select ' . $resource->randompick() .')';
805: }
806:
807: $result .= " </td>\n";
808:
809: return $result;
1.51 bowersj2 810: }
811:
1.133 bowersj2 812: my @preparedColumns = (\&render_resource, \&render_communication_status,
813: \&render_quick_status, \&render_long_status);
1.132 bowersj2 814:
815: sub setDefault {
816: my ($val, $default) = @_;
817: if (!defined($val)) { return $default; }
818: return $val;
819: }
820:
821: sub render {
822: my $args = shift;
1.140 bowersj2 823: &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
824: my $result = '';
825:
1.132 bowersj2 826: # Configure the renderer.
827: my $cols = $args->{'cols'};
828: if (!defined($cols)) {
829: # no columns, no nav maps.
830: return '';
831: }
1.140 bowersj2 832: my $mustCloseNavMap = 0;
833: my $navmap;
834: if (defined($args->{'navmap'})) {
835: $navmap = $args->{'navmap'};
836: }
837:
838: my $queryString = $args->{'queryString'};
839: my $jumpToURL = $args->{'jumpToURL'};
840: my $jumpToSymb = $args->{'jumpToSymb'};
841: my $jumpType;
842: my $hereURL = $args->{'hereURL'};
843: my $hereSymb = $args->{'hereSymb'};
844: my $hereType;
845: my $here;
846: my $jump;
847: my $currentJumpIndex = setDefault($args->{'currentJumpIndex'}, 0);
1.153 bowersj2 848: my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1.140 bowersj2 849: my $currentJumpDelta = 2; # change this to change how many resources are displayed
850: # before the current resource when using #current
851:
852: # If we were passed 'here' information, we are not rendering
853: # after a folder manipulation, and we were not passed an
854: # iterator, make sure we open the folders to show the "here"
855: # marker
856: my $filterHash = {};
857: # Figure out what we're not displaying
858: foreach (split(/\,/, $ENV{"form.filter"})) {
859: if ($_) {
860: $filterHash->{$_} = "1";
861: }
862: }
863:
864: my $condition = 0;
865: if ($ENV{'form.condition'}) {
866: $condition = 1;
867: }
868:
869: if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
870: # Step 1: Check to see if we have a navmap
871: if (!defined($navmap)) {
872: $navmap = Apache::lonnavmaps::navmap->new(
873: $ENV{"request.course.fn"}.".db",
874: $ENV{"request.course.fn"}."_parms.db", 1, 1);
875: $mustCloseNavMap = 1;
876: }
877: $navmap->init();
878:
879: # Step two: Locate what kind of here marker is necessary
880: # Determine where the "here" marker is and where the screen jumps to.
881:
882: # We're coming from the remote. We have either a url, a symb, or nothing,
883: # and we need to figure out what.
884: # Preference: Symb
885:
886: if ($ENV{'form.symb'}) {
887: $hereType = $jumpType = SYMB();
888: $here = $jump = $ENV{'form.symb'};
889: } elsif ($ENV{'form.postdata'}) {
890: # couldn't find a symb, is there a URL?
891: my $currenturl = $ENV{'form.postdata'};
892: $currenturl=~s/^http\:\/\///;
893: $currenturl=~s/^[^\/]+//;
894:
895: $hereType = $jumpType = URL;
896: $here = $jump = $currenturl;
897: } else {
898: # Nothing
899: $hereType = $jumpType = NOTHING();
900: }
901: # Step three: Ensure the folders are open
902: my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
903: my $depth = 1;
904: $mapIterator->next(); # discard the first BEGIN_MAP
905: my $curRes = $mapIterator->next();
906: my $counter = 0;
907: my $found = 0;
908:
909: # We only need to do this if we need to open the maps to show the
910: # current position. This will change the counter so we can't count
911: # for the jump marker with this loop.
912: while ($depth > 0 && !$found) {
913: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
914: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
915:
916: if (ref($curRes) &&
917: ($hereType == SYMB() && $curRes->symb() eq $here) ||
918: (ref($curRes) && $hereType == URL() && $curRes->src() eq $here)) {
919: my $mapStack = $mapIterator->getStack();
920:
921: # Ensure the parent maps are open
922: for my $map (@{$mapStack}) {
923: if ($condition) {
924: undef $filterHash->{$map->map_pc()};
925: } else {
926: $filterHash->{$map->map_pc()} = 1;
927: }
928: }
929: $found = 1;
930: }
931:
932: $curRes = $mapIterator->next();
933: }
934:
935: # Since we changed the folders, (re-)locate the jump point, if any
936: $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
937: $depth = 1;
938: $mapIterator->next();
939: $curRes = $mapIterator->next();
940: my $foundJump = 0;
941:
942: while ($depth > 0 && !$foundJump) {
943: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
944: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
945: if (ref($curRes)) { $counter++; }
946:
947: if (ref($curRes) &&
948: (($jumpType == SYMB() && $curRes->symb() eq $jump) ||
949: ($jumpType == URL() && $curRes->src() eq $jump))) {
950:
951: # This is why we have to use the main iterator instead of the
952: # potentially faster DFS: The count has to be the same, so
953: # the order has to be the same, which DFS won't give us.
954: $currentJumpIndex = $counter;
955: $foundJump = 1;
956: }
957:
958: $curRes = $mapIterator->next();
959: }
960:
961: }
962: if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
963: # If this is a click on a folder or something, we want to preserve the "here"
964: # from the querystring, and get the new "jump" marker
965: $hereType = $ENV{'form.hereType'};
966: $here = $ENV{'form.here'};
967: $jumpType = $ENV{'form.jumpType'} || NOTHING();
968: $jump = $ENV{'form.jump'};
969: }
970:
1.132 bowersj2 971: my $it = $args->{'iterator'};
972: if (!defined($it)) {
1.140 bowersj2 973: # Construct a default iterator based on $ENV{'form.'} information
974:
975: # Step 1: Check to see if we have a navmap
976: if (!defined($navmap)) {
977: $navmap = Apache::lonnavmaps::navmap->new(
978: $ENV{"request.course.fn"}.".db",
979: $ENV{"request.course.fn"}."_parms.db", 1, 1);
980: $mustCloseNavMap = 1;
981: }
982: # Paranoia: Make sure it's ready
983: $navmap->init();
984:
1.144 bowersj2 985: # See if we're being passed a specific map
986: if ($args->{'iterator_map'}) {
987: my $map = $args->{'iterator_map'};
1.145 bowersj2 988: $map = $navmap->getResourceByUrl($map);
1.144 bowersj2 989: my $firstResource = $map->map_start();
990: my $finishResource = $map->map_finish();
991:
992: $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
993: } else {
994: $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
995: }
1.132 bowersj2 996: }
997:
998: my $showParts = setDefault($args->{'showParts'}, 1);
999: my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1.139 bowersj2 1000: # keeps track of when the current resource is found,
1001: # so we can back up a few and put the anchor above the
1002: # current resource
1003: my $r = $args->{'r'};
1.140 bowersj2 1004: my $printKey = $args->{'printKey'};
1005: my $printCloseAll = $args->{'printCloseAll'};
1006: if (!defined($printCloseAll)) { $printCloseAll = 1; }
1.143 bowersj2 1007: my $filterFunc = setDefault($args->{'filterFunc'},
1008: sub {return 1;});
1.144 bowersj2 1009:
1.140 bowersj2 1010: # Print key?
1011: if ($printKey) {
1012: $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1013: my $date=localtime;
1014: $result.='<tr><td align="right" valign="bottom">Key: </td>';
1015: if ($navmap->{LAST_CHECK}) {
1016: $result .=
1017: '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
1018: strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
1019: '</td><td align="center" valign="bottom"> '.
1020: '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
1021: '</td>';
1022: } else {
1023: $result .= '<td align="center" valign="bottom"> '.
1024: '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
1025: ' <img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
1026: '</td>';
1027: }
1028:
1029: $result .= '</tr></table>';
1030: }
1031:
1032: if ($printCloseAll) {
1033: if ($condition) {
1034: $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
1035: "&hereType=$hereType&here=" . Apache::lonnet::escape($here) .
1036: "\">Close All Folders</a>";
1037: } else {
1038: $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
1039: "&hereType=$hereType&here=" . Apache::lonnet::escape($here) .
1040: "\">Open All Folders</a>";
1041: }
1.143 bowersj2 1042: $result .= "<br /><br />\n";
1.140 bowersj2 1043: }
1044:
1045: if ($r) {
1046: $r->print($result);
1047: $r->rflush();
1048: $result = "";
1049: }
1.132 bowersj2 1050: # End parameter setting
1.133 bowersj2 1051:
1.132 bowersj2 1052: # Data
1.140 bowersj2 1053: $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1.132 bowersj2 1054: my $res = "Apache::lonnavmaps::resource";
1055: my %condenseStatuses =
1056: ( $res->NETWORK_FAILURE => 1,
1057: $res->NOTHING_SET => 1,
1058: $res->CORRECT => 1 );
1059: my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1.133 bowersj2 1060:
1061: # Shared variables
1062: $args->{'counter'} = 0; # counts the rows
1063: $args->{'indentLevel'} = 0;
1064: $args->{'isNewBranch'} = 0;
1065: $args->{'condensed'} = 0;
1066: $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
1067: $args->{'displayedHereMarker'} = 0;
1.132 bowersj2 1068:
1.133 bowersj2 1069: my $displayedJumpMarker = 0;
1.132 bowersj2 1070: # Set up iteration.
1071: my $depth = 1;
1072: $it->next(); # discard initial BEGIN_MAP
1073: my $curRes = $it->next();
1074: my $now = time();
1075: my $in24Hours = $now + 24 * 60 * 60;
1076: my $rownum = 0;
1077:
1.141 bowersj2 1078: # export "here" marker information
1079: $args->{'here'} = $here;
1080: $args->{'hereType'} = $hereType;
1081:
1.132 bowersj2 1082: while ($depth > 0) {
1083: if ($curRes == $it->BEGIN_MAP()) { $depth++; }
1084: if ($curRes == $it->END_MAP()) { $depth--; }
1085:
1086: # Maintain indentation level.
1087: if ($curRes == $it->BEGIN_MAP() ||
1088: $curRes == $it->BEGIN_BRANCH() ) {
1.133 bowersj2 1089: $args->{'indentLevel'}++;
1.132 bowersj2 1090: }
1091: if ($curRes == $it->END_MAP() ||
1092: $curRes == $it->END_BRANCH() ) {
1.133 bowersj2 1093: $args->{'indentLevel'}--;
1.132 bowersj2 1094: }
1095: # Notice new branches
1096: if ($curRes == $it->BEGIN_BRANCH()) {
1.133 bowersj2 1097: $args->{'isNewBranch'} = 1;
1098: }
1099:
1100: # If this isn't an actual resource, continue on
1101: if (!ref($curRes)) {
1102: $curRes = $it->next();
1103: next;
1.132 bowersj2 1104: }
1.133 bowersj2 1105:
1106: $args->{'counter'}++;
1.143 bowersj2 1107:
1108: # If this has been filtered out, continue on
1109: if (!(&$filterFunc($curRes))) {
1110: $curRes = $it->next();
1111: $args->{'isNewBranch'} = 0; # Don't falsely remember this
1112: next;
1113: }
1.132 bowersj2 1114:
1.153 bowersj2 1115: # If we're suppressing navmaps and this is a navmap, continue on
1116: if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
1117: $curRes = $it->next();
1118: next;
1119: }
1120:
1.132 bowersj2 1121: # Does it have multiple parts?
1.133 bowersj2 1122: $args->{'multipart'} = 0;
1123: $args->{'condensed'} = 0;
1.132 bowersj2 1124: my @parts;
1125:
1126: # Decide what parts to show.
1.133 bowersj2 1127: if ($curRes->is_problem() && $showParts) {
1.132 bowersj2 1128: @parts = @{$curRes->parts()};
1.133 bowersj2 1129: $args->{'multipart'} = scalar(@parts) > 1;
1.132 bowersj2 1130:
1131: if ($condenseParts) { # do the condensation
1132: if (!$curRes->opendate("0")) {
1133: @parts = ("0");
1.133 bowersj2 1134: $args->{'condensed'} = 1;
1.132 bowersj2 1135: }
1.133 bowersj2 1136: if (!$args->{'condensed'}) {
1.132 bowersj2 1137: # Decide whether to condense based on similarity
1138: my $status = $curRes->status($parts[1]);
1139: my $due = $curRes->duedate($parts[1]);
1140: my $open = $curRes->opendate($parts[1]);
1141: my $statusAllSame = 1;
1142: my $dueAllSame = 1;
1143: my $openAllSame = 1;
1144: for (my $i = 2; $i < scalar(@parts); $i++) {
1145: if ($curRes->status($parts[$i]) != $status){
1146: $statusAllSame = 0;
1147: }
1148: if ($curRes->duedate($parts[$i]) != $due ) {
1149: $dueAllSame = 0;
1150: }
1151: if ($curRes->opendate($parts[$i]) != $open) {
1152: $openAllSame = 0;
1153: }
1154: }
1155: # $*allSame is true if all the statuses were
1156: # the same. Now, if they are all the same and
1157: # match one of the statuses to condense, or they
1158: # are all open with the same due date, or they are
1159: # all OPEN_LATER with the same open date, display the
1160: # status of the first non-zero part (to get the 'correct'
1161: # status right, since 0 is never 'correct' or 'open').
1162: if (($statusAllSame && defined($condenseStatuses{$status})) ||
1163: ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
1164: ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1165: @parts = ($parts[1]);
1.133 bowersj2 1166: $args->{'condensed'} = 1;
1.132 bowersj2 1167: }
1168:
1169: }
1170: }
1171:
1172: } else {
1173: # Not showing parts
1174: @parts = ("0"); # show main part only
1175: }
1176:
1177: # If the multipart problem was condensed, "forget" it was multipart
1178: if (scalar(@parts) == 1) {
1.133 bowersj2 1179: $args->{'multipart'} = 0;
1.132 bowersj2 1180: }
1181:
1182: # In the event of a network error, display one part.
1183: # If this is a single part, we can at least show the correct
1184: # status, but if it's multipart, we're lost, since we can't
1185: # retreive the metadata to count the parts
1186: if ($curRes->{RESOURCE_ERROR}) {
1187: @parts = ("0");
1188: }
1189:
1190: # Now, we've decided what parts to show. Loop through them and
1191: # show them.
1192: foreach my $part (@parts) {
1193: $rownum ++;
1194: my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
1195:
1196: $result .= " <tr bgcolor='$backgroundColor'>\n";
1.134 bowersj2 1197:
1198: # Set up some data about the parts that the cols might want
1199: my $filter = $it->{FILTER};
1200: my $stack = $it->getStack();
1201: my $src = getLinkForResource($stack);
1202:
1203: my $srcHasQuestion = $src =~ /\?/;
1204: $args->{"resourceLink"} = $src.
1205: ($srcHasQuestion?'&':'?') .
1.137 bowersj2 1206: 'symb=' . &Apache::lonnet::escape($curRes->symb());
1.132 bowersj2 1207:
1208: # Now, display each column.
1209: foreach my $col (@$cols) {
1.139 bowersj2 1210: my $colHTML = '';
1211: if (ref($col)) {
1212: $colHTML .= &$col($curRes, $part, $args);
1213: } else {
1214: $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
1215: }
1.132 bowersj2 1216:
1.133 bowersj2 1217: # If this is the first column and it's time to print
1218: # the anchor, do so
1219: if ($col == $cols->[0] &&
1220: $args->{'counter'} == $args->{'currentJumpIndex'} -
1.139 bowersj2 1221: $currentJumpDelta) {
1222: # Jam the anchor after the <td> tag;
1223: # necessary for valid HTML (which Mozilla requires)
1224: $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1.133 bowersj2 1225: $displayedJumpMarker = 1;
1226: }
1.139 bowersj2 1227: $result .= $colHTML . "\n";
1.132 bowersj2 1228: }
1.139 bowersj2 1229: $result .= " </tr>\n";
1.140 bowersj2 1230: $args->{'isNewBranch'} = 0;
1.139 bowersj2 1231: }
1.153 bowersj2 1232:
1.139 bowersj2 1233: if ($r && $rownum % 20 == 0) {
1234: $r->print($result);
1235: $result = "";
1236: $r->rflush();
1.132 bowersj2 1237: }
1238:
1239: $curRes = $it->next();
1240: }
1241:
1.134 bowersj2 1242: # Print out the part that jumps to #curloc if it exists
1.139 bowersj2 1243: if ($displayedJumpMarker) {
1244: $result .= "<script>location += \"#curloc\";</script>\n";
1.134 bowersj2 1245: }
1246:
1.132 bowersj2 1247: $result .= "</table>";
1.140 bowersj2 1248:
1249: if ($r) {
1250: $r->print($result);
1251: $result = "";
1252: $r->rflush();
1253: }
1254:
1255: if ($mustCloseNavMap) { $navmap->untieHashes(); }
1.132 bowersj2 1256:
1257: return $result;
1258: }
1259:
1.133 bowersj2 1260: 1;
1261:
1262: package Apache::lonnavmaps::navmap;
1263:
1264: =pod
1265:
1266: lonnavmaps provides functions and objects for dealing with the compiled course hashes generated when a user enters the course, the Apache handler for the "Navigation Map" button, and a flexible prepared renderer for navigation maps that are easy to use anywhere.
1267:
1268: =head1 navmap object: Encapsulating the compiled nav map
1269:
1270: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
1271:
1272: Most notably it provides a way to navigate the map sensibly and a flexible iterator that makes it easy to write various renderers based on nav maps.
1273:
1274: You must obtain resource objects through the navmap object.
1275:
1276: =head2 Methods
1277:
1278: =over 4
1279:
1280: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions, genMailDiscussStatus): Binds a new navmap object to the compiled nav map hash and parm hash given as filenames. genCourseAndUserOptions is a flag saying whether the course options and user options hash should be generated. This is for when you are using the parameters of the resources that require them; see documentation in resource object documentation. genMailDiscussStatus causes the nav map to retreive information about the email and discussion status of resources. Returns the navmap object if this is successful, or B<undef> if not. You must check for undef; errors will occur when you try to use the other methods otherwise.
1281:
1282: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
1283:
1284: =cut
1285:
1286: use strict;
1287: use GDBM_File;
1288:
1289: sub new {
1290: # magic invocation to create a class instance
1291: my $proto = shift;
1292: my $class = ref($proto) || $proto;
1293: my $self = {};
1294:
1295: $self->{NAV_HASH_FILE} = shift;
1296: $self->{PARM_HASH_FILE} = shift;
1297: $self->{GENERATE_COURSE_USER_OPT} = shift;
1298: $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
1299:
1300: # Resource cache stores navmap resources as we reference them. We generate
1301: # them on-demand so we don't pay for creating resources unless we use them.
1302: $self->{RESOURCE_CACHE} = {};
1303:
1304: # Network failure flag, if we accessed the course or user opt and
1305: # failed
1306: $self->{NETWORK_FAILURE} = 0;
1307:
1308: # tie the nav hash
1309:
1310: if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
1311: &GDBM_READER(), 0640))) {
1312: return undef;
1313: }
1314:
1315: if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
1316: &GDBM_READER(), 0640)))
1317: {
1318: untie $self->{PARM_HASH};
1319: return undef;
1320: }
1321:
1322: $self->{HASH_TIED} = 1;
1323: $self->{NAV_HASH} = \%navmaphash;
1324: $self->{PARM_HASH} = \%parmhash;
1.140 bowersj2 1325: $self->{INITED} = 0;
1.133 bowersj2 1326:
1327: bless($self);
1328:
1329: return $self;
1330: }
1331:
1332: sub init {
1333: my $self = shift;
1.140 bowersj2 1334: if ($self->{INITED}) { return; }
1.133 bowersj2 1335:
1336: # If the course opt hash and the user opt hash should be generated,
1337: # generate them
1338: if ($self->{GENERATE_COURSE_USER_OPT}) {
1339: my $uname=$ENV{'user.name'};
1340: my $udom=$ENV{'user.domain'};
1341: my $uhome=$ENV{'user.home'};
1342: my $cid=$ENV{'request.course.id'};
1343: my $chome=$ENV{'course.'.$cid.'.home'};
1344: my ($cdom,$cnum)=split(/\_/,$cid);
1345:
1346: my $userprefix=$uname.'_'.$udom.'_';
1347:
1348: my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
1349: unless ($uhome eq 'no_host') {
1350: # ------------------------------------------------- Get coursedata (if present)
1351: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
1352: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
1353: ':resourcedata',$chome);
1354: if ($reply!~/^error\:/) {
1355: $courserdatas{$cid}=$reply;
1356: $courserdatas{$cid.'.last_cache'}=time;
1357: }
1358: # check to see if network failed
1359: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
1360: {
1361: $self->{NETWORK_FAILURE} = 1;
1362: }
1363: }
1364: foreach (split(/\&/,$courserdatas{$cid})) {
1365: my ($name,$value)=split(/\=/,$_);
1366: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
1367: &Apache::lonnet::unescape($value);
1368: }
1369: # --------------------------------------------------- Get userdata (if present)
1370: unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
1371: my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
1372: if ($reply!~/^error\:/) {
1373: $userrdatas{$uname.'___'.$udom}=$reply;
1374: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
1375: }
1376: # check to see if network failed
1377: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
1378: {
1379: $self->{NETWORK_FAILURE} = 1;
1380: }
1381: }
1382: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
1383: my ($name,$value)=split(/\=/,$_);
1384: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
1385: &Apache::lonnet::unescape($value);
1386: }
1387: $self->{COURSE_OPT} = \%courseopt;
1388: $self->{USER_OPT} = \%useropt;
1389: }
1390: }
1391:
1392: if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
1393: my $cid=$ENV{'request.course.id'};
1394: my ($cdom,$cnum)=split(/\_/,$cid);
1395:
1396: my %emailstatus = &Apache::lonnet::dump('email_status');
1397: my $logoutTime = $emailstatus{'logout'};
1398: my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
1399: $self->{LAST_CHECK} = ($courseLeaveTime < $logoutTime ?
1400: $courseLeaveTime : $logoutTime);
1401: my %discussiontime = &Apache::lonnet::dump('discussiontimes',
1402: $cdom, $cnum);
1403: my %feedback=();
1404: my %error=();
1405: my $keys = &Apache::lonnet::reply('keys:'.
1406: $ENV{'user.domain'}.':'.
1407: $ENV{'user.name'}.':nohist_email',
1408: $ENV{'user.home'});
1409:
1410: foreach my $msgid (split(/\&/, $keys)) {
1411: $msgid=&Apache::lonnet::unescape($msgid);
1412: my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
1413: if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
1414: my ($what,$url)=($1,$2);
1415: my %status=
1416: &Apache::lonnet::get('email_status',[$msgid]);
1417: if ($status{$msgid}=~/^error\:/) {
1418: $status{$msgid}='';
1419: }
1420:
1421: if (($status{$msgid} eq 'new') ||
1422: (!$status{$msgid})) {
1423: if ($what eq 'Error') {
1424: $error{$url}.=','.$msgid;
1425: } else {
1426: $feedback{$url}.=','.$msgid;
1427: }
1428: }
1429: }
1430: }
1431:
1432: $self->{FEEDBACK} = \%feedback;
1433: $self->{ERROR_MSG} = \%error; # what is this? JB
1434: $self->{DISCUSSION_TIME} = \%discussiontime;
1435: $self->{EMAIL_STATUS} = \%emailstatus;
1436:
1437: }
1438:
1439: $self->{PARM_CACHE} = {};
1.140 bowersj2 1440: $self->{INITED} = 1;
1.133 bowersj2 1441: }
1442:
1443: # Internal function: Takes a key to look up in the nav hash and implements internal
1444: # memory caching of that key.
1445: sub navhash {
1446: my $self = shift; my $key = shift;
1447: return $self->{NAV_HASH}->{$key};
1448: }
1449:
1450: # Checks to see if coursemap is defined, matching test in old lonnavmaps
1451: sub courseMapDefined {
1452: my $self = shift;
1453: my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
1454:
1455: my $firstres = $self->navhash("map_start_$uri");
1456: my $lastres = $self->navhash("map_finish_$uri");
1457: return $firstres && $lastres;
1458: }
1459:
1460: sub getIterator {
1461: my $self = shift;
1462: my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
1463: shift, undef, shift);
1464: return $iterator;
1465: }
1466:
1467: # unties the hash when done
1468: sub untieHashes {
1469: my $self = shift;
1470: untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
1471: untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
1472: $self->{HASH_TIED} = 0;
1473: }
1474:
1475: # when the object is destroyed, be sure to untie all the hashes we tied.
1476: sub DESTROY {
1477: my $self = shift;
1478: $self->untieHashes();
1479: }
1480:
1481: # Private method: Does the given resource (as a symb string) have
1482: # current discussion? Returns 0 if chat/mail data not extracted.
1483: sub hasDiscussion {
1484: my $self = shift;
1485: my $symb = shift;
1486: if (!defined($self->{DISCUSSION_TIME})) { return 0; }
1487:
1488: #return defined($self->{DISCUSSION_TIME}->{$symb});
1489: return $self->{DISCUSSION_TIME}->{$symb} >
1490: $self->{LAST_CHECK};
1491: }
1492:
1493: # Private method: Does the given resource (as a symb string) have
1494: # current feedback? Returns the string in the feedback hash, which
1495: # will be false if it does not exist.
1496: sub getFeedback {
1497: my $self = shift;
1498: my $symb = shift;
1499:
1500: if (!defined($self->{FEEDBACK})) { return ""; }
1501:
1502: return $self->{FEEDBACK}->{$symb};
1503: }
1504:
1505: # Private method: Get the errors for that resource (by source).
1506: sub getErrors {
1507: my $self = shift;
1508: my $src = shift;
1509:
1510: if (!defined($self->{ERROR_MSG})) { return ""; }
1511: return $self->{ERROR_MSG}->{$src};
1512: }
1513:
1514: =pod
1515:
1516: =item * B<getById>(id): Based on the ID of the resource (1.1, 3.2, etc.), get a resource object for that resource. This method, or other methods that use it (as in the resource object) is the only proper way to obtain a resource object.
1517:
1518: =cut
1519:
1520: # The strategy here is to cache the resource objects, and only construct them
1521: # as we use them. The real point is to prevent reading any more from the tied
1522: # hash then we have to, which should hopefully alleviate speed problems.
1523: # Caching is just an incidental detail I throw in because it makes sense.
1524:
1525: sub getById {
1526: my $self = shift;
1527: my $id = shift;
1528:
1529: if (defined ($self->{RESOURCE_CACHE}->{$id}))
1530: {
1531: return $self->{RESOURCE_CACHE}->{$id};
1532: }
1533:
1534: # resource handles inserting itself into cache.
1535: # Not clear why the quotes are necessary, but as of this
1536: # writing it doesn't work without them.
1537: return "Apache::lonnavmaps::resource"->new($self, $id);
1.132 bowersj2 1538: }
1.133 bowersj2 1539:
1540: =pod
1541:
1542: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
1543:
1544: =cut
1545:
1546: sub firstResource {
1547: my $self = shift;
1548: my $firstResource = $self->navhash('map_start_' .
1549: &Apache::lonnet::clutter($ENV{'request.course.uri'}));
1550: return $self->getById($firstResource);
1.132 bowersj2 1551: }
1.133 bowersj2 1552:
1553: =pod
1554:
1555: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
1556:
1557: =cut
1558:
1559: sub finishResource {
1560: my $self = shift;
1561: my $firstResource = $self->navhash('map_finish_' .
1562: &Apache::lonnet::clutter($ENV{'request.course.uri'}));
1563: return $self->getById($firstResource);
1.132 bowersj2 1564: }
1.133 bowersj2 1565:
1566: # Parmval reads the parm hash and cascades the lookups. parmval_real does
1567: # the actual lookup; parmval caches the results.
1568: sub parmval {
1569: my $self = shift;
1570: my ($what,$symb)=@_;
1571: my $hashkey = $what."|||".$symb;
1572:
1573: if (defined($self->{PARM_CACHE}->{$hashkey})) {
1574: return $self->{PARM_CACHE}->{$hashkey};
1575: }
1576:
1577: my $result = $self->parmval_real($what, $symb);
1578: $self->{PARM_CACHE}->{$hashkey} = $result;
1579: return $result;
1.132 bowersj2 1580: }
1581:
1.133 bowersj2 1582: sub parmval_real {
1583: my $self = shift;
1584: my ($what,$symb) = @_;
1585:
1586: my $cid=$ENV{'request.course.id'};
1587: my $csec=$ENV{'request.course.sec'};
1588: my $uname=$ENV{'user.name'};
1589: my $udom=$ENV{'user.domain'};
1590:
1591: unless ($symb) { return ''; }
1592: my $result='';
1593:
1594: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1595:
1596: # ----------------------------------------------------- Cascading lookup scheme
1597: my $rwhat=$what;
1598: $what=~s/^parameter\_//;
1599: $what=~s/\_/\./;
1600:
1601: my $symbparm=$symb.'.'.$what;
1602: my $mapparm=$mapname.'___(all).'.$what;
1603: my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
1604:
1605: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
1606: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
1607: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
1608:
1609: my $courselevel= $usercourseprefix.'.'.$what;
1610: my $courselevelr=$usercourseprefix.'.'.$symbparm;
1611: my $courselevelm=$usercourseprefix.'.'.$mapparm;
1612:
1613: my $useropt = $self->{USER_OPT};
1614: my $courseopt = $self->{COURSE_OPT};
1615: my $parmhash = $self->{PARM_HASH};
1616:
1617: # ---------------------------------------------------------- first, check user
1618: if ($uname and defined($useropt)) {
1619: if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
1620: if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
1621: if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
1622: }
1623:
1624: # ------------------------------------------------------- second, check course
1625: if ($csec and defined($courseopt)) {
1626: if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
1627: if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
1628: if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
1629: }
1630:
1631: if (defined($courseopt)) {
1632: if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
1633: if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
1634: if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
1635: }
1636:
1637: # ----------------------------------------------------- third, check map parms
1638:
1639: my $thisparm=$$parmhash{$symbparm};
1640: if (defined($thisparm)) { return $thisparm; }
1641:
1642: # ----------------------------------------------------- fourth , check default
1643:
1644: my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
1645: if (defined($default)) { return $default}
1646:
1647: # --------------------------------------------------- fifth , cascade up parts
1648:
1649: my ($space,@qualifier)=split(/\./,$rwhat);
1650: my $qualifier=join('.',@qualifier);
1651: unless ($space eq '0') {
1652: my ($part,$id)=split(/\_/,$space);
1653: if ($id) {
1654: my $partgeneral=$self->parmval($part.".$qualifier",$symb);
1655: if (defined($partgeneral)) { return $partgeneral; }
1656: } else {
1657: my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
1658: if (defined($resourcegeneral)) { return $resourcegeneral; }
1659: }
1660: }
1661: return '';
1.145 bowersj2 1662: }
1663:
1664: =pod
1665:
1666: =item * B<getResourceByUrl>(url): Retrieves a resource object by URL of the resource. If passed a resource object, it will simply return it, so it is safe to use this method in code like "$res = $navmap->getResourceByUrl($res)", if you're not sure if $res is already an object, or just a URL. If the resource appears multiple times in the course, only the first instance will be returned. As a result, this is probably useful only for maps.
1667:
1668: =item * B<retrieveResources>(map, filterFunc, recursive, bailout): The map is a specification of a map to retreive the resources from, either as a url or as an object. The filterFunc is a reference to a function that takes a resource object as its one argument and returns true if the resource should be included, or false if it should not be. If recursive is true, the map will be recursively examined, otherwise it will not be. If bailout is true, the function will return as soon as it finds a resource, if false it will finish. By default, the map is the top-level map of the course, filterFunc is a function that always returns 1, recursive is true, bailout is false. The resources will be returned in a list reference containing the resource objects for the corresponding resources, with B<no structure information> in the list; regardless of branching, recursion, etc., it will be a flat list.
1669:
1670: Thus, this is suitable for cases where you don't want the structure, just a list of all resources. It is also suitable for finding out how many resources match a given description; for this use, if all you want to know is if I<any> resources match the description, the bailout parameter will allow you to avoid potentially expensive enumeration of all matching resources.
1671:
1.146 bowersj2 1672: =item * B<hasResources>(map, filterFunc, recursive): Convience method for
1673:
1674: scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
1675:
1676: which will tell whether the map has resources matching the description in the filter function.
1677:
1.145 bowersj2 1678: =cut
1679:
1680: sub getResourceByUrl {
1681: my $self = shift;
1682: my $resUrl = shift;
1683:
1684: if (ref($resUrl)) { return $resUrl; }
1685:
1686: $resUrl = &Apache::lonnet::clutter($resUrl);
1687: my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
1688: if ($resId =~ /,/) {
1689: $resId = (split (/,/, $resId))[0];
1690: }
1691: if (!$resId) { return ''; }
1692: return $self->getById($resId);
1693: }
1694:
1695: sub retrieveResources {
1696: my $self = shift;
1697: my $map = shift;
1698: my $filterFunc = shift;
1699: if (!defined ($filterFunc)) {
1700: $filterFunc = sub {return 1;};
1701: }
1702: my $recursive = shift;
1703: if (!defined($recursive)) { $recursive = 1; }
1704: my $bailout = shift;
1705: if (!defined($bailout)) { $bailout = 0; }
1706:
1707: # Create the necessary iterator.
1708: if (!ref($map)) { # assume it's a url of a map.
1709: $map = $self->getMapByUrl($map);
1710: }
1711:
1712: # Check the map's validity.
1713: if (!$map || !$map->is_map()) {
1714: # Oh, to throw an exception.... how I'd love that!
1715: return ();
1716: }
1717:
1.146 bowersj2 1718: # Get an iterator.
1719: my $it = $self->getIterator($map->map_start(), $map->map_finish(),
1720: !$recursive);
1721:
1722: my @resources = ();
1723:
1724: # Run down the iterator and collect the resources.
1725: my $depth = 1;
1726: $it->next();
1727: my $curRes = $it->next();
1728:
1729: while ($depth > 0) {
1730: if ($curRes == $it->BEGIN_MAP()) {
1731: $depth++;
1732: }
1733: if ($curRes == $it->END_MAP()) {
1734: $depth--;
1735: }
1736:
1737: if (ref($curRes)) {
1738: if (!&$filterFunc($curRes)) {
1739: next;
1740: }
1741:
1742: push @resources, $curRes;
1743:
1744: if ($bailout) {
1745: return @resources;
1746: }
1747: }
1748:
1749: $curRes = $it->next();
1750: }
1751:
1752: return @resources;
1753: }
1754:
1755: sub hasResource {
1756: my $self = shift;
1757: my $map = shift;
1758: my $filterFunc = shift;
1759: my $recursive = shift;
1760:
1761: return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
1.133 bowersj2 1762: }
1.51 bowersj2 1763:
1764: 1;
1765:
1766: package Apache::lonnavmaps::iterator;
1767:
1768: =pod
1769:
1770: =back
1771:
1772: =head1 navmap Iterator
1773:
1774: An I<iterator> encapsulates the logic required to traverse a data structure. navmap uses an iterator to traverse the course map according to the criteria you wish to use.
1775:
1776: To obtain an iterator, call the B<getIterator>() function of a B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator directly.) This will return a reference to the iterator:
1777:
1778: C<my $resourceIterator = $navmap-E<gt>getIterator();>
1779:
1780: To get the next thing from the iterator, call B<next>:
1781:
1782: C<my $nextThing = $resourceIterator-E<gt>next()>
1783:
1784: getIterator behaves as follows:
1785:
1786: =over 4
1787:
1.116 bowersj2 1788: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop): All parameters are optional. firstResource is a resource reference corresponding to where the iterator should start. It defaults to navmap->firstResource() for the corresponding nav map. finishResource corresponds to where you want the iterator to end, defaulting to navmap->finishResource(). filterHash is a hash used as a set containing strings representing the resource IDs, defaulting to empty. Condition is a 1 or 0 that sets what to do with the filter hash: If a 0, then only resource that exist IN the filterHash will be recursed on. If it is a 1, only resources NOT in the filterHash will be recursed on. Defaults to 0. forceTop is a boolean value. If it is false (default), the iterator will only return the first level of map that is not just a single, 'redirecting' map. If true, the iterator will return all information, starting with the top-level map, regardless of content.
1.51 bowersj2 1789:
1.101 bowersj2 1790: Thus, by default, only top-level resources will be shown. Change the condition to a 1 without changing the hash, and all resources will be shown. Changing the condition to 1 and including some values in the hash will allow you to selectively suppress parts of the navmap, while leaving it on 0 and adding things to the hash will allow you to selectively add parts of the nav map. See the handler code for examples.
1.51 bowersj2 1791:
1792: The iterator will return either a reference to a resource object, or a token representing something in the map, such as the beginning of a new branch. The possible tokens are:
1793:
1794: =over 4
1795:
1.70 bowersj2 1796: =item * BEGIN_MAP: A new map is being recursed into. This is returned I<after> the map resource itself is returned.
1797:
1798: =item * END_MAP: The map is now done.
1799:
1800: =item * BEGIN_BRANCH: A branch is now starting. The next resource returned will be the first in that branch.
1801:
1802: =item * END_BRANCH: The branch is now done.
1.51 bowersj2 1803:
1804: =back
1805:
1.70 bowersj2 1806: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_MAP.
1807:
1.116 bowersj2 1808: Maps can contain empty resources. The iterator will automatically skip over such resources, but will still treat the structure correctly. Thus, a complicated map with several branches, but consisting entirely of empty resources except for one beginning or ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs, but only one resource will be returned.
1809:
1.70 bowersj2 1810: =back
1.51 bowersj2 1811:
1812: =cut
1813:
1814: # Here are the tokens for the iterator:
1815:
1816: sub BEGIN_MAP { return 1; } # begining of a new map
1817: sub END_MAP { return 2; } # end of the map
1818: sub BEGIN_BRANCH { return 3; } # beginning of a branch
1819: sub END_BRANCH { return 4; } # end of a branch
1.89 bowersj2 1820: sub FORWARD { return 1; } # go forward
1821: sub BACKWARD { return 2; }
1.51 bowersj2 1822:
1.96 bowersj2 1823: sub min {
1824: (my $a, my $b) = @_;
1825: if ($a < $b) { return $a; } else { return $b; }
1826: }
1827:
1.107 bowersj2 1828: # In the CVS repository, documentation of this algorithm is included
1829: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
1830: # will reference the same location in the text as the part of the
1831: # algorithm is running through.
1832:
1.94 bowersj2 1833: sub new {
1834: # magic invocation to create a class instance
1835: my $proto = shift;
1836: my $class = ref($proto) || $proto;
1837: my $self = {};
1838:
1839: $self->{NAV_MAP} = shift;
1840: return undef unless ($self->{NAV_MAP});
1841:
1842: # Handle the parameters
1843: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
1844: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
1845:
1846: # If the given resources are just the ID of the resource, get the
1847: # objects
1848: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
1849: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
1850: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
1851: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
1852:
1853: $self->{FILTER} = shift;
1854:
1855: # A hash, used as a set, of resource already seen
1856: $self->{ALREADY_SEEN} = shift;
1857: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1858: $self->{CONDITION} = shift;
1859:
1.116 bowersj2 1860: # Do we want to automatically follow "redirection" maps?
1861: $self->{FORCE_TOP} = shift;
1862:
1.94 bowersj2 1863: # Now, we need to pre-process the map, by walking forward and backward
1864: # over the parts of the map we're going to look at.
1.96 bowersj2 1865:
1.97 bowersj2 1866: # The processing steps are exactly the same, except for a few small
1867: # changes, so I bundle those up in the following list of two elements:
1868: # (direction_to_iterate, VAL_name, next_resource_method_to_call,
1869: # first_resource).
1870: # This prevents writing nearly-identical code twice.
1871: my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext',
1872: 'FIRST_RESOURCE'],
1873: [BACKWARD(), 'BOT_UP_VAL', 'getPrevious',
1874: 'FINISH_RESOURCE'] );
1875:
1.98 bowersj2 1876: my $maxDepth = 0; # tracks max depth
1877:
1.116 bowersj2 1878: # If there is only one resource in this map, and it's a map, we
1879: # want to remember that, so the user can ask for the first map
1880: # that isn't just a redirector.
1881: my $resource; my $resourceCount = 0;
1882:
1.107 bowersj2 1883: # **1**
1884:
1.97 bowersj2 1885: foreach my $pass (@iterations) {
1886: my $direction = $pass->[0];
1887: my $valName = $pass->[1];
1888: my $nextResourceMethod = $pass->[2];
1889: my $firstResourceName = $pass->[3];
1890:
1891: my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP},
1892: $self->{FIRST_RESOURCE},
1893: $self->{FINISH_RESOURCE},
1894: {}, undef, 0, $direction);
1.96 bowersj2 1895:
1.97 bowersj2 1896: # prime the recursion
1897: $self->{$firstResourceName}->{DATA}->{$valName} = 0;
1.98 bowersj2 1898: my $depth = 0;
1.97 bowersj2 1899: $iterator->next();
1900: my $curRes = $iterator->next();
1.98 bowersj2 1901: while ($depth > -1) {
1.97 bowersj2 1902: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
1903: if ($curRes == $iterator->END_MAP()) { $depth--; }
1.96 bowersj2 1904:
1.97 bowersj2 1905: if (ref($curRes)) {
1.116 bowersj2 1906: # If there's only one resource, this will save it
1.117 bowersj2 1907: # we have to filter empty resources from consideration here,
1908: # or even "empty", redirecting maps have two (start & finish)
1909: # or three (start, finish, plus redirector)
1910: if($direction == FORWARD && $curRes->src()) {
1911: $resource = $curRes; $resourceCount++;
1912: }
1.97 bowersj2 1913: my $resultingVal = $curRes->{DATA}->{$valName};
1914: my $nextResources = $curRes->$nextResourceMethod();
1.116 bowersj2 1915: my $nextCount = scalar(@{$nextResources});
1.104 bowersj2 1916:
1.116 bowersj2 1917: if ($nextCount == 1) { # **3**
1.97 bowersj2 1918: my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
1919: $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
1920: }
1921:
1.116 bowersj2 1922: if ($nextCount > 1) { # **4**
1.97 bowersj2 1923: foreach my $res (@{$nextResources}) {
1924: my $current = $res->{DATA}->{$valName} || 999999999;
1925: $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
1926: }
1927: }
1928: }
1.96 bowersj2 1929:
1.107 bowersj2 1930: # Assign the final val (**2**)
1.97 bowersj2 1931: if (ref($curRes) && $direction == BACKWARD()) {
1.98 bowersj2 1932: my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
1933: $curRes->{DATA}->{BOT_UP_VAL});
1934:
1935: $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
1936: if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
1937: }
1.97 bowersj2 1938: $curRes = $iterator->next();
1.96 bowersj2 1939: }
1940: }
1.94 bowersj2 1941:
1.116 bowersj2 1942: # Check: Was this only one resource, a map?
1943: if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) {
1944: my $firstResource = $resource->map_start();
1945: my $finishResource = $resource->map_finish();
1946: return
1947: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
1948: $finishResource, $self->{FILTER},
1949: $self->{ALREADY_SEEN},
1950: $self->{CONDITION}, 0);
1951:
1952: }
1953:
1.98 bowersj2 1954: # Set up some bookkeeping information.
1955: $self->{CURRENT_DEPTH} = 0;
1956: $self->{MAX_DEPTH} = $maxDepth;
1957: $self->{STACK} = [];
1958: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1959:
1960: for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
1961: push @{$self->{STACK}}, [];
1962: }
1963:
1.107 bowersj2 1964: # Prime the recursion w/ the first resource **5**
1.98 bowersj2 1965: push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
1966: $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
1967:
1968: bless ($self);
1969:
1970: return $self;
1971: }
1972:
1973: sub next {
1974: my $self = shift;
1975:
1976: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1977: # grab the next from the recursive iterator
1978: my $next = $self->{RECURSIVE_ITERATOR}->next();
1979:
1980: # is it a begin or end map? If so, update the depth
1981: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
1982: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
1983:
1984: # Are we back at depth 0? If so, stop recursing
1985: if ($self->{RECURSIVE_DEPTH} == 0) {
1986: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1987: }
1988:
1989: return $next;
1990: }
1991:
1992: if (defined($self->{FORCE_NEXT})) {
1993: my $tmp = $self->{FORCE_NEXT};
1994: $self->{FORCE_NEXT} = undef;
1995: return $tmp;
1996: }
1997:
1998: # Have we not yet begun? If not, return BEGIN_MAP and
1999: # remember we've started.
2000: if ( !$self->{STARTED} ) {
2001: $self->{STARTED} = 1;
2002: return $self->BEGIN_MAP();
2003: }
2004:
2005: # Here's the guts of the iterator.
2006:
2007: # Find the next resource, if any.
2008: my $found = 0;
2009: my $i = $self->{MAX_DEPTH};
2010: my $newDepth;
2011: my $here;
2012: while ( $i >= 0 && !$found ) {
1.107 bowersj2 2013: if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
2014: $here = pop @{$self->{STACK}->[$i]}; # **7**
1.98 bowersj2 2015: $found = 1;
2016: $newDepth = $i;
2017: }
2018: $i--;
2019: }
2020:
2021: # If we still didn't find anything, we're done.
2022: if ( !$found ) {
2023: # We need to get back down to the correct branch depth
2024: if ( $self->{CURRENT_DEPTH} > 0 ) {
2025: $self->{CURRENT_DEPTH}--;
2026: return END_BRANCH();
2027: } else {
2028: return END_MAP();
2029: }
2030: }
2031:
1.104 bowersj2 2032: # If this is not a resource, it must be an END_BRANCH marker we want
2033: # to return directly.
1.107 bowersj2 2034: if (!ref($here)) { # **8**
1.104 bowersj2 2035: if ($here == END_BRANCH()) { # paranoia, in case of later extension
2036: $self->{CURRENT_DEPTH}--;
2037: return $here;
2038: }
2039: }
2040:
2041: # Otherwise, it is a resource and it's safe to store in $self->{HERE}
2042: $self->{HERE} = $here;
2043:
1.98 bowersj2 2044: # Get to the right level
2045: if ( $self->{CURRENT_DEPTH} > $newDepth ) {
2046: push @{$self->{STACK}->[$newDepth]}, $here;
2047: $self->{CURRENT_DEPTH}--;
2048: return END_BRANCH();
2049: }
2050: if ( $self->{CURRENT_DEPTH} < $newDepth) {
2051: push @{$self->{STACK}->[$newDepth]}, $here;
2052: $self->{CURRENT_DEPTH}++;
2053: return BEGIN_BRANCH();
2054: }
2055:
2056: # If we made it here, we have the next resource, and we're at the
2057: # right branch level. So let's examine the resource for where
2058: # we can get to from here.
2059:
2060: # So we need to look at all the resources we can get to from here,
2061: # categorize them if we haven't seen them, remember if we have a new
2062: my $nextUnfiltered = $here->getNext();
1.104 bowersj2 2063: my $maxDepthAdded = -1;
2064:
1.98 bowersj2 2065: for (@$nextUnfiltered) {
2066: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1.104 bowersj2 2067: my $depth = $_->{DATA}->{DISPLAY_DEPTH};
2068: push @{$self->{STACK}->[$depth]}, $_;
1.98 bowersj2 2069: $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
1.104 bowersj2 2070: if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
1.98 bowersj2 2071: }
2072: }
1.104 bowersj2 2073:
2074: # Is this the end of a branch? If so, all of the resources examined above
2075: # led to lower levels then the one we are currently at, so we push a END_BRANCH
2076: # marker onto the stack so we don't forget.
2077: # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
2078: # BC branch and gets to C, it will see F as the only next resource, but it's
2079: # one level lower. Thus, this is the end of the branch, since there are no
2080: # more resources added to this level or above.
1.111 bowersj2 2081: # We don't do this if the examined resource is the finish resource,
2082: # because the condition given above is true, but the "END_MAP" will
2083: # take care of things and we should already be at depth 0.
1.104 bowersj2 2084: my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
1.111 bowersj2 2085: if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
1.104 bowersj2 2086: push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
2087: }
2088:
1.98 bowersj2 2089: # That ends the main iterator logic. Now, do we want to recurse
2090: # down this map (if this resource is a map)?
2091: if ($self->{HERE}->is_map() &&
2092: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
2093: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
2094: my $firstResource = $self->{HERE}->map_start();
2095: my $finishResource = $self->{HERE}->map_finish();
2096:
2097: $self->{RECURSIVE_ITERATOR} =
2098: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
2099: $finishResource, $self->{FILTER},
2100: $self->{ALREADY_SEEN}, $self->{CONDITION});
2101: }
2102:
1.116 bowersj2 2103: # If this is a blank resource, don't actually return it.
1.117 bowersj2 2104: # Should you ever find you need it, make sure to add an option to the code
2105: # that you can use; other things depend on this behavior.
1.138 bowersj2 2106: my $browsePriv = $self->{HERE}->browsePriv();
2107: if (!$self->{HERE}->src() ||
2108: (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
1.116 bowersj2 2109: return $self->next();
2110: }
2111:
1.98 bowersj2 2112: return $self->{HERE};
2113:
2114: }
2115:
2116: =pod
2117:
2118: The other method available on the iterator is B<getStack>, which returns an array populated with the current 'stack' of maps, as references to the resource objects. Example: This is useful when making the navigation map, as we need to check whether we are under a page map to see if we need to link directly to the resource, or to the page. The first elements in the array will correspond to the top of the stack (most inclusive map).
2119:
2120: =cut
2121:
2122: sub getStack {
2123: my $self=shift;
2124:
2125: my @stack;
2126:
2127: $self->populateStack(\@stack);
2128:
2129: return \@stack;
2130: }
2131:
2132: # Private method: Calls the iterators recursively to populate the stack.
2133: sub populateStack {
2134: my $self=shift;
2135: my $stack = shift;
2136:
2137: push @$stack, $self->{HERE} if ($self->{HERE});
2138:
2139: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2140: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
2141: }
1.94 bowersj2 2142: }
2143:
2144: 1;
2145:
2146: package Apache::lonnavmaps::DFSiterator;
2147:
1.100 bowersj2 2148: # Not documented in the perldoc: This is a simple iterator that just walks
2149: # through the nav map and presents the resources in a depth-first search
2150: # fashion, ignorant of conditionals, randomized resources, etc. It presents
2151: # BEGIN_MAP and END_MAP, but does not understand branches at all. It is
2152: # useful for pre-processing of some kind, and is in fact used by the main
2153: # iterator that way, but that's about it.
2154: # One could imagine merging this into the init routine of the main iterator,
2155: # but this might as well be left seperate, since it is possible some other
2156: # use might be found for it. - Jeremy
1.94 bowersj2 2157:
1.117 bowersj2 2158: # Unlike the main iterator, this DOES return all resources, even blank ones.
2159: # The main iterator needs them to correctly preprocess the map.
2160:
1.94 bowersj2 2161: sub BEGIN_MAP { return 1; } # begining of a new map
2162: sub END_MAP { return 2; } # end of the map
2163: sub FORWARD { return 1; } # go forward
2164: sub BACKWARD { return 2; }
2165:
1.100 bowersj2 2166: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
2167: # filter hash ref (or undef), already seen hash or undef, condition
2168: # (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
1.51 bowersj2 2169: sub new {
2170: # magic invocation to create a class instance
2171: my $proto = shift;
2172: my $class = ref($proto) || $proto;
2173: my $self = {};
2174:
2175: $self->{NAV_MAP} = shift;
2176: return undef unless ($self->{NAV_MAP});
2177:
2178: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
2179: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
2180:
2181: # If the given resources are just the ID of the resource, get the
2182: # objects
2183: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
2184: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
2185: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
2186: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
2187:
2188: $self->{FILTER} = shift;
2189:
2190: # A hash, used as a set, of resource already seen
2191: $self->{ALREADY_SEEN} = shift;
1.140 bowersj2 2192: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1.63 bowersj2 2193: $self->{CONDITION} = shift;
1.89 bowersj2 2194: $self->{DIRECTION} = shift || FORWARD();
1.51 bowersj2 2195:
1.100 bowersj2 2196: # Flag: Have we started yet?
1.51 bowersj2 2197: $self->{STARTED} = 0;
2198:
2199: # Should we continue calling the recursive iterator, if any?
2200: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2201: # The recursive iterator, if any
2202: $self->{RECURSIVE_ITERATOR} = undef;
2203: # Are we recursing on a map, or a branch?
2204: $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
2205: # And the count of how deep it is, so that this iterator can keep track of
2206: # when to pick back up again.
2207: $self->{RECURSIVE_DEPTH} = 0;
2208:
2209: # For keeping track of our branches, we maintain our own stack
1.100 bowersj2 2210: $self->{STACK} = [];
1.51 bowersj2 2211:
2212: # Start with the first resource
1.89 bowersj2 2213: if ($self->{DIRECTION} == FORWARD) {
1.100 bowersj2 2214: push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
1.89 bowersj2 2215: } else {
1.100 bowersj2 2216: push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
1.89 bowersj2 2217: }
1.51 bowersj2 2218:
2219: bless($self);
2220: return $self;
2221: }
2222:
2223: sub next {
2224: my $self = shift;
2225:
2226: # Are we using a recursive iterator? If so, pull from that and
2227: # watch the depth; we want to resume our level at the correct time.
1.98 bowersj2 2228: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1.51 bowersj2 2229: # grab the next from the recursive iterator
2230: my $next = $self->{RECURSIVE_ITERATOR}->next();
2231:
2232: # is it a begin or end map? Update depth if so
2233: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
2234: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
2235:
2236: # Are we back at depth 0? If so, stop recursing.
2237: if ($self->{RECURSIVE_DEPTH} == 0) {
2238: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2239: }
2240:
2241: return $next;
2242: }
2243:
2244: # Is there a current resource to grab? If not, then return
1.100 bowersj2 2245: # END_MAP, which will end the iterator.
2246: if (scalar(@{$self->{STACK}}) == 0) {
2247: return $self->END_MAP();
1.51 bowersj2 2248: }
2249:
2250: # Have we not yet begun? If not, return BEGIN_MAP and
2251: # remember that we've started.
2252: if ( !$self->{STARTED} ) {
2253: $self->{STARTED} = 1;
2254: return $self->BEGIN_MAP;
2255: }
2256:
2257: # Get the next resource in the branch
1.100 bowersj2 2258: $self->{HERE} = pop @{$self->{STACK}};
1.52 bowersj2 2259:
1.100 bowersj2 2260: # remember that we've seen this, so we don't return it again later
1.51 bowersj2 2261: $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
2262:
2263: # Get the next possible resources
1.90 bowersj2 2264: my $nextUnfiltered;
1.89 bowersj2 2265: if ($self->{DIRECTION} == FORWARD()) {
1.90 bowersj2 2266: $nextUnfiltered = $self->{HERE}->getNext();
1.89 bowersj2 2267: } else {
1.90 bowersj2 2268: $nextUnfiltered = $self->{HERE}->getPrevious();
1.89 bowersj2 2269: }
1.51 bowersj2 2270: my $next = [];
2271:
2272: # filter the next possibilities to remove things we've
1.100 bowersj2 2273: # already seen.
1.51 bowersj2 2274: foreach (@$nextUnfiltered) {
1.52 bowersj2 2275: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
2276: push @$next, $_;
2277: }
1.51 bowersj2 2278: }
2279:
2280: while (@$next) {
1.100 bowersj2 2281: # copy the next possibilities over to the stack
2282: push @{$self->{STACK}}, shift @$next;
1.51 bowersj2 2283: }
2284:
2285: # If this is a map and we want to recurse down it... (not filtered out)
1.70 bowersj2 2286: if ($self->{HERE}->is_map() &&
1.63 bowersj2 2287: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
1.51 bowersj2 2288: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
2289: my $firstResource = $self->{HERE}->map_start();
2290: my $finishResource = $self->{HERE}->map_finish();
2291:
2292: $self->{RECURSIVE_ITERATOR} =
1.94 bowersj2 2293: Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource,
1.63 bowersj2 2294: $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
1.91 bowersj2 2295: $self->{CONDITION}, $self->{DIRECTION});
1.51 bowersj2 2296: }
2297:
2298: return $self->{HERE};
2299: }
2300:
1.1 www 2301: 1;
1.2 www 2302:
1.51 bowersj2 2303: package Apache::lonnavmaps::resource;
2304:
2305: use Apache::lonnet;
2306:
2307: =pod
2308:
2309: =head1 Object: resource
2310:
2311: A resource object encapsulates a resource in a resource map, allowing easy manipulation of the resource, querying the properties of the resource (including user properties), and represents a reference that can be used as the canonical representation of the resource by lonnavmap clients like renderers.
2312:
2313: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
2314:
1.140 bowersj2 2315: You will probably never need to instantiate this object directly. Use Apache::lonnavmaps::navmap, and use the "start" method to obtain the starting resource.
1.51 bowersj2 2316:
2317: =head2 Public Members
2318:
2319: resource objects have a hash called DATA ($resourceRef->{DATA}) that you can store whatever you want in. This allows you to easily do two-pass algorithms without worrying about managing your own resource->data hash.
2320:
2321: =head2 Methods
2322:
2323: =over 4
2324:
1.70 bowersj2 2325: =item * B<new>($navmapRef, $idString): The first arg is a reference to the parent navmap object. The second is the idString of the resource itself. Very rarely, if ever, called directly. Use the nav map->getByID() method.
2326:
2327: =back
1.51 bowersj2 2328:
2329: =cut
2330:
2331: sub new {
2332: # magic invocation to create a class instance
2333: my $proto = shift;
2334: my $class = ref($proto) || $proto;
2335: my $self = {};
2336:
2337: $self->{NAV_MAP} = shift;
2338: $self->{ID} = shift;
2339:
2340: # Store this new resource in the parent nav map's cache.
2341: $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1.66 bowersj2 2342: $self->{RESOURCE_ERROR} = 0;
1.51 bowersj2 2343:
2344: # A hash that can be used by two-pass algorithms to store data
2345: # about this resource in. Not used by the resource object
2346: # directly.
2347: $self->{DATA} = {};
2348:
2349: bless($self);
2350:
2351: return $self;
2352: }
2353:
1.70 bowersj2 2354: # private function: simplify the NAV_HASH lookups we keep doing
2355: # pass the name, and to automatically append my ID, pass a true val on the
2356: # second param
2357: sub navHash {
2358: my $self = shift;
2359: my $param = shift;
2360: my $id = shift;
1.115 bowersj2 2361: return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
1.70 bowersj2 2362: }
2363:
1.51 bowersj2 2364: =pod
2365:
1.70 bowersj2 2366: B<Metadata Retreival>
2367:
1.101 bowersj2 2368: These are methods that help you retrieve metadata about the resource: Method names are based on the fields in the compiled course representation.
1.70 bowersj2 2369:
2370: =over 4
2371:
1.106 bowersj2 2372: =item * B<compTitle>: Returns a "composite title", that is equal to $res->title() if the resource has a title, and is otherwise the last part of the URL (e.g., "problem.problem").
2373:
1.70 bowersj2 2374: =item * B<ext>: Returns true if the resource is external.
2375:
2376: =item * B<goesto>: Returns the "goesto" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
2377:
2378: =item * B<kind>: Returns the kind of the resource from the compiled nav map.
2379:
1.101 bowersj2 2380: =item * B<randomout>: Returns true if this resource was chosen to NOT be shown to the user by the random map selection feature. In other words, this is usually false.
1.51 bowersj2 2381:
1.70 bowersj2 2382: =item * B<randompick>: Returns true for a map if the randompick feature is being used on the map. (?)
2383:
2384: =item * B<src>: Returns the source for the resource.
2385:
2386: =item * B<symb>: Returns the symb for the resource.
2387:
2388: =item * B<title>: Returns the title of the resource.
2389:
2390: =item * B<to>: Returns the "to" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
1.51 bowersj2 2391:
2392: =back
2393:
2394: =cut
2395:
2396: # These info functions can be used directly, as they don't return
2397: # resource information.
1.85 bowersj2 2398: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
1.70 bowersj2 2399: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
1.85 bowersj2 2400: sub from { my $self=shift; return $self->navHash("from_", 1); }
1.51 bowersj2 2401: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
2402: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1.68 bowersj2 2403: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
2404: sub randompick {
2405: my $self = shift;
2406: return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
2407: '.0.parameter_randompick'};
2408: }
1.51 bowersj2 2409: sub src {
2410: my $self=shift;
2411: return $self->navHash("src_", 1);
2412: }
2413: sub symb {
2414: my $self=shift;
2415: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
2416: my $symbSrc = &Apache::lonnet::declutter($self->src());
2417: return &Apache::lonnet::declutter(
2418: $self->navHash('map_id_'.$first))
2419: . '___' . $second . '___' . $symbSrc;
2420: }
1.70 bowersj2 2421: sub title { my $self=shift; return $self->navHash("title_", 1); }
2422: sub to { my $self=shift; return $self->navHash("to_", 1); }
1.106 bowersj2 2423: sub compTitle {
2424: my $self = shift;
2425: my $title = $self->title();
2426: if (!$title) {
2427: $title = $self->src();
2428: $title = substr($title, rindex($title, '/') + 1);
2429: }
2430: return $title;
2431: }
1.70 bowersj2 2432: =pod
2433:
2434: B<Predicate Testing the Resource>
2435:
2436: These methods are shortcuts to deciding if a given resource has a given property.
2437:
2438: =over 4
2439:
2440: =item * B<is_map>: Returns true if the resource is a map type.
2441:
2442: =item * B<is_problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field; might need more to work correctly.)
2443:
2444: =item * B<is_page>: Returns true if the resource is a page.
2445:
1.101 bowersj2 2446: =item * B<is_sequence>: Returns true if the resource is a sequence.
1.70 bowersj2 2447:
2448: =back
2449:
2450: =cut
2451:
2452:
2453: sub is_html {
1.51 bowersj2 2454: my $self=shift;
2455: my $src = $self->src();
1.70 bowersj2 2456: return ($src =~ /html$/);
1.51 bowersj2 2457: }
1.70 bowersj2 2458: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
2459: sub is_page {
1.51 bowersj2 2460: my $self=shift;
2461: my $src = $self->src();
1.70 bowersj2 2462: return ($src =~ /page$/);
1.51 bowersj2 2463: }
1.70 bowersj2 2464: sub is_problem {
1.51 bowersj2 2465: my $self=shift;
2466: my $src = $self->src();
1.70 bowersj2 2467: return ($src =~ /problem$/);
1.51 bowersj2 2468: }
1.70 bowersj2 2469: sub is_sequence {
1.51 bowersj2 2470: my $self=shift;
2471: my $src = $self->src();
1.70 bowersj2 2472: return ($src =~ /sequence$/);
1.51 bowersj2 2473: }
2474:
1.101 bowersj2 2475: # Private method: Shells out to the parmval in the nav map, handler parts.
1.51 bowersj2 2476: sub parmval {
2477: my $self = shift;
2478: my $what = shift;
2479: my $part = shift || "0";
2480: return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
2481: }
2482:
1.70 bowersj2 2483: =pod
2484:
2485: B<Map Methods>
2486:
2487: These methods are useful for getting information about the map properties of the resource, if the resource is a map (B<is_map>).
2488:
2489: =over 4
2490:
2491: =item * B<map_finish>: Returns a reference to a resource object corresponding to the finish resource of the map.
2492:
2493: =item * B<map_pc>: Returns the pc value of the map, which is the first number that appears in the resource ID of the resources in the map, and is the number that appears around the middle of the symbs of the resources in that map.
2494:
2495: =item * B<map_start>: Returns a reference to a resource object corresponding to the start resource of the map.
2496:
2497: =item * B<map_type>: Returns a string with the type of the map in it.
2498:
2499: =back
1.51 bowersj2 2500:
1.70 bowersj2 2501: =cut
1.51 bowersj2 2502:
2503: sub map_finish {
2504: my $self = shift;
2505: my $src = $self->src();
1.144 bowersj2 2506: $src = Apache::lonnet::clutter($src);
1.51 bowersj2 2507: my $res = $self->navHash("map_finish_$src", 0);
2508: $res = $self->{NAV_MAP}->getById($res);
2509: return $res;
2510: }
1.70 bowersj2 2511: sub map_pc {
2512: my $self = shift;
2513: my $src = $self->src();
2514: return $self->navHash("map_pc_$src", 0);
2515: }
1.51 bowersj2 2516: sub map_start {
2517: my $self = shift;
2518: my $src = $self->src();
1.144 bowersj2 2519: $src = Apache::lonnet::clutter($src);
1.51 bowersj2 2520: my $res = $self->navHash("map_start_$src", 0);
2521: $res = $self->{NAV_MAP}->getById($res);
2522: return $res;
2523: }
2524: sub map_type {
2525: my $self = shift;
2526: my $pc = $self->map_pc();
2527: return $self->navHash("map_type_$pc", 0);
2528: }
2529:
2530:
2531:
2532: #####
2533: # Property queries
2534: #####
2535:
2536: # These functions will be responsible for returning the CORRECT
2537: # VALUE for the parameter, no matter what. So while they may look
2538: # like direct calls to parmval, they can be more then that.
2539: # So, for instance, the duedate function should use the "duedatetype"
2540: # information, rather then the resource object user.
2541:
2542: =pod
2543:
2544: =head2 Resource Parameters
2545:
1.70 bowersj2 2546: In order to use the resource parameters correctly, the nav map must have been instantiated with genCourseAndUserOptions set to true, so the courseopt and useropt is read correctly. Then, you can call these functions to get the relevant parameters for the resource. Each function defaults to part "0", but can be directed to another part by passing the part as the parameter.
1.51 bowersj2 2547:
2548: These methods are responsible for getting the parameter correct, not merely reflecting the contents of the GDBM hashes. As we move towards dates relative to other dates, these methods should be updated to reflect that. (Then, anybody using these methods won't have to update their code.)
2549:
2550: =over 4
2551:
2552: =item * B<acc>: Get the Client IP/Name Access Control information.
2553:
2554: =item * B<answerdate>: Get the answer-reveal date for the problem.
2555:
2556: =item * B<duedate>: Get the due date for the problem.
2557:
2558: =item * B<tries>: Get the number of tries the student has used on the problem.
2559:
2560: =item * B<maxtries>: Get the number of max tries allowed.
2561:
2562: =item * B<opendate>: Get the open date for the problem.
2563:
2564: =item * B<sig>: Get the significant figures setting.
2565:
2566: =item * B<tol>: Get the tolerance for the problem.
2567:
1.70 bowersj2 2568: =item * B<tries>: Get the number of tries the user has already used on the problem.
2569:
1.51 bowersj2 2570: =item * B<type>: Get the question type for the problem.
2571:
2572: =item * B<weight>: Get the weight for the problem.
2573:
2574: =back
2575:
2576: =cut
2577:
2578: sub acc {
2579: (my $self, my $part) = @_;
2580: return $self->parmval("acc", $part);
2581: }
2582: sub answerdate {
2583: (my $self, my $part) = @_;
2584: # Handle intervals
2585: if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
2586: return $self->duedate($part) +
2587: $self->parmval("answerdate", $part);
2588: }
2589: return $self->parmval("answerdate", $part);
1.106 bowersj2 2590: }
1.108 bowersj2 2591: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
1.51 bowersj2 2592: sub duedate {
2593: (my $self, my $part) = @_;
2594: return $self->parmval("duedate", $part);
2595: }
2596: sub maxtries {
2597: (my $self, my $part) = @_;
2598: return $self->parmval("maxtries", $part);
2599: }
2600: sub opendate {
2601: (my $self, my $part) = @_;
2602: if ($self->parmval("opendate.type", $part) eq 'date_interval') {
2603: return $self->duedate($part) -
2604: $self->parmval("opendate", $part);
2605: }
2606: return $self->parmval("opendate");
2607: }
2608: sub sig {
2609: (my $self, my $part) = @_;
2610: return $self->parmval("sig", $part);
2611: }
2612: sub tol {
2613: (my $self, my $part) = @_;
2614: return $self->parmval("tol", $part);
2615: }
1.108 bowersj2 2616: sub tries {
2617: my $self = shift;
2618: my $tries = $self->queryRestoreHash('tries', shift);
2619: if (!defined($tries)) { return '0';}
1.51 bowersj2 2620: return $tries;
2621: }
1.70 bowersj2 2622: sub type {
2623: (my $self, my $part) = @_;
2624: return $self->parmval("type", $part);
2625: }
1.109 bowersj2 2626: sub weight {
2627: my $self = shift; my $part = shift;
1.70 bowersj2 2628: return $self->parmval("weight", $part);
2629: }
1.51 bowersj2 2630:
2631: # Multiple things need this
2632: sub getReturnHash {
2633: my $self = shift;
2634:
2635: if (!defined($self->{RETURN_HASH})) {
1.84 bowersj2 2636: my %tmpHash = &Apache::lonnet::restore($self->symb());
1.51 bowersj2 2637: $self->{RETURN_HASH} = \%tmpHash;
2638: }
2639: }
2640:
2641: ######
2642: # Status queries
2643: ######
2644:
2645: # These methods query the status of problems.
2646:
2647: # If we need to count parts, this function determines the number of
2648: # parts from the metadata. When called, it returns a reference to a list
2649: # of strings corresponding to the parts. (Thus, using it in a scalar context
2650: # tells you how many parts you have in the problem:
2651: # $partcount = scalar($resource->countParts());
2652: # Don't use $self->{PARTS} directly because you don't know if it's been
2653: # computed yet.
2654:
2655: =pod
2656:
2657: =head2 Resource misc
2658:
2659: Misc. functions for the resource.
2660:
2661: =over 4
2662:
1.59 bowersj2 2663: =item * B<hasDiscussion>: Returns a false value if there has been discussion since the user last logged in, true if there has. Always returns false if the discussion data was not extracted when the nav map was constructed.
2664:
2665: =item * B<getFeedback>: Gets the feedback for the resource and returns the raw feedback string for the resource, or the null string if there is no feedback or the email data was not extracted when the nav map was constructed. Usually used like this:
2666:
2667: for (split(/\,/, $res->getFeedback())) {
2668: my $link = &Apache::lonnet::escape($_);
2669: ...
2670:
2671: and use the link as appropriate.
2672:
2673: =cut
2674:
2675: sub hasDiscussion {
2676: my $self = shift;
2677: return $self->{NAV_MAP}->hasDiscussion($self->symb());
2678: }
2679:
2680: sub getFeedback {
2681: my $self = shift;
1.124 bowersj2 2682: my $source = $self->src();
1.125 bowersj2 2683: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
1.124 bowersj2 2684: return $self->{NAV_MAP}->getFeedback($source);
2685: }
2686:
2687: sub getErrors {
2688: my $self = shift;
2689: my $source = $self->src();
2690: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
2691: return $self->{NAV_MAP}->getErrors($source);
1.59 bowersj2 2692: }
2693:
2694: =pod
2695:
1.142 bowersj2 2696: =item * B<parts>(): Returns a list reference containing sorted strings corresponding to each part of the problem. To count the number of parts, use the list in a scalar context, and subtract one if greater than two. (One part problems have a part 0. Multi-parts have a part 0, plus a part for each part. Filtering part 0 if you want it is up to you.)
1.51 bowersj2 2697:
1.70 bowersj2 2698: =item * B<countParts>(): Returns the number of parts of the problem a student can answer. Thus, for single part problems, returns 1. For multipart, it returns the number of parts in the problem, not including psuedo-part 0. Thus, B<parts> may return an array with fewer parts in it then countParts might lead you to believe.
1.51 bowersj2 2699:
2700: =back
2701:
2702: =cut
2703:
2704: sub parts {
2705: my $self = shift;
2706:
1.67 bowersj2 2707: if ($self->ext) { return ['0']; }
2708:
1.51 bowersj2 2709: $self->extractParts();
2710: return $self->{PARTS};
2711: }
2712:
2713: sub countParts {
2714: my $self = shift;
2715:
2716: my $parts = $self->parts();
1.66 bowersj2 2717:
2718: if ($self->{RESOURCE_ERROR}) {
2719: return 0;
2720: }
2721:
2722: if (scalar(@{$parts}) < 2) { return 1;}
1.51 bowersj2 2723:
2724: return scalar(@{$parts}) - 1;
2725: }
2726:
2727: # Private function: Extracts the parts information and saves it
2728: sub extractParts {
2729: my $self = shift;
2730:
1.153 bowersj2 2731: return if (defined($self->{PARTS}));
1.67 bowersj2 2732: return if ($self->ext);
1.51 bowersj2 2733:
2734: $self->{PARTS} = [];
2735:
1.82 bowersj2 2736: # Retrieve part count, if this is a problem
2737: if ($self->is_problem()) {
1.152 matthew 2738: my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
1.82 bowersj2 2739: if (!$metadata) {
2740: $self->{RESOURCE_ERROR} = 1;
2741: $self->{PARTS} = [];
2742: return;
2743: }
2744: foreach (split(/\,/,$metadata)) {
1.152 matthew 2745: if ($_ =~ /^part_(.*)$/) {
1.147 bowersj2 2746: my $part = $1;
2747: # check to see if part is turned off.
1.149 matthew 2748: if (! Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
1.147 bowersj2 2749: push @{$self->{PARTS}}, $1;
2750: }
1.82 bowersj2 2751: }
1.51 bowersj2 2752: }
1.82 bowersj2 2753:
2754:
2755: my @sortedParts = sort @{$self->{PARTS}};
2756: $self->{PARTS} = \@sortedParts;
1.51 bowersj2 2757: }
2758:
1.154 bowersj2 2759: # Ensure part 0 is included at the beginning.
2760: if ($self->{PARTS}->[0] ne '0') {
2761: unshift @{$self->{PARTS}}, '0';
2762: }
2763:
1.51 bowersj2 2764: return;
2765: }
2766:
2767: =pod
2768:
2769: =head2 Resource Status
2770:
1.101 bowersj2 2771: Problem resources have status information, reflecting their various dates and completion statuses.
1.51 bowersj2 2772:
2773: There are two aspects to the status: the date-related information and the completion information.
2774:
2775: Idiomatic usage of these two methods would probably look something like
2776:
2777: foreach ($resource->parts()) {
2778: my $dateStatus = $resource->getDateStatus($_);
2779: my $completionStatus = $resource->getCompletionStatus($_);
2780:
1.70 bowersj2 2781: or
2782:
2783: my $status = $resource->status($_);
2784:
1.51 bowersj2 2785: ... use it here ...
2786: }
2787:
1.101 bowersj2 2788: Which you use depends on exactly what you are looking for. The status() function has been optimized for the nav maps display and may not precisely match what you need elsewhere.
2789:
2790: The symbolic constants shown below can be accessed through the resource object: $res->OPEN.
2791:
1.51 bowersj2 2792: =over 4
2793:
1.70 bowersj2 2794: =item * B<getDateStatus>($part): ($part defaults to 0). A convenience function that returns a symbolic constant telling you about the date status of the part. The possible return values are:
1.51 bowersj2 2795:
2796: =back
2797:
2798: B<Date Codes>
2799:
2800: =over 4
2801:
2802: =item * B<OPEN_LATER>: The problem will be opened later.
2803:
2804: =item * B<OPEN>: Open and not yet due.
2805:
1.59 bowersj2 2806:
1.54 bowersj2 2807: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
2808:
2809: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
1.51 bowersj2 2810:
2811: =item * B<ANSWER_OPEN>: The answer date is here.
2812:
2813: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
2814:
2815: =back
2816:
2817: =cut
2818:
2819: # Apparently the compiler optimizes these into constants automatically
1.54 bowersj2 2820: sub OPEN_LATER { return 0; }
2821: sub OPEN { return 1; }
2822: sub PAST_DUE_NO_ANSWER { return 2; }
2823: sub PAST_DUE_ANSWER_LATER { return 3; }
2824: sub ANSWER_OPEN { return 4; }
2825: sub NOTHING_SET { return 5; }
2826: sub NETWORK_FAILURE { return 100; }
2827:
2828: # getDateStatus gets the date status for a given problem part.
2829: # Because answer date, due date, and open date are fully independent
2830: # (i.e., it is perfectly possible to *only* have an answer date),
2831: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
2832: # (past, future, none given). This function handles this with a decision
2833: # tree. Read the comments to follow the decision tree.
1.51 bowersj2 2834:
2835: sub getDateStatus {
2836: my $self = shift;
2837: my $part = shift;
2838: $part = "0" if (!defined($part));
1.54 bowersj2 2839:
2840: # Always return network failure if there was one.
1.51 bowersj2 2841: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2842:
2843: my $now = time();
2844:
1.53 bowersj2 2845: my $open = $self->opendate($part);
2846: my $due = $self->duedate($part);
2847: my $answer = $self->answerdate($part);
2848:
2849: if (!$open && !$due && !$answer) {
2850: # no data on the problem at all
2851: # should this be the same as "open later"? think multipart.
2852: return $self->NOTHING_SET;
2853: }
1.59 bowersj2 2854: if (!$open || $now < $open) {return $self->OPEN_LATER}
2855: if (!$due || $now < $due) {return $self->OPEN}
2856: if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
2857: if ($answer) { return $self->ANSWER_OPEN; }
1.54 bowersj2 2858: return PAST_DUE_NO_ANSWER;
1.51 bowersj2 2859: }
2860:
2861: =pod
2862:
2863: B<>
2864:
2865: =over 4
2866:
2867: =item * B<getCompletionStatus>($part): ($part defaults to 0.) A convenience function that returns a symbolic constant telling you about the completion status of the part, with the following possible results:
2868:
2869: =back
2870:
2871: B<Completion Codes>
2872:
2873: =over 4
2874:
2875: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
2876:
2877: =item * B<INCORRECT>: Attempted, but wrong by student.
2878:
2879: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
2880:
2881: =item * B<CORRECT>: Correct or correct by instructor.
2882:
2883: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
2884:
2885: =item * B<EXCUSED>: Excused. Not yet implemented.
2886:
2887: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
2888:
1.69 bowersj2 2889: =item * B<ATTEMPTED>: Attempted, and not yet graded.
2890:
1.51 bowersj2 2891: =back
2892:
2893: =cut
2894:
1.53 bowersj2 2895: sub NOT_ATTEMPTED { return 10; }
2896: sub INCORRECT { return 11; }
2897: sub INCORRECT_BY_OVERRIDE { return 12; }
2898: sub CORRECT { return 13; }
2899: sub CORRECT_BY_OVERRIDE { return 14; }
2900: sub EXCUSED { return 15; }
1.69 bowersj2 2901: sub ATTEMPTED { return 16; }
1.51 bowersj2 2902:
2903: sub getCompletionStatus {
2904: my $self = shift;
2905: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2906:
1.108 bowersj2 2907: my $status = $self->queryRestoreHash('solved', shift);
1.51 bowersj2 2908:
2909: # Left as seperate if statements in case we ever do more with this
2910: if ($status eq 'correct_by_student') {return $self->CORRECT;}
2911: if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
2912: if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
2913: if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
2914: if ($status eq 'excused') {return $self->EXCUSED; }
1.69 bowersj2 2915: if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
1.51 bowersj2 2916: return $self->NOT_ATTEMPTED;
1.108 bowersj2 2917: }
2918:
2919: sub queryRestoreHash {
2920: my $self = shift;
2921: my $hashentry = shift;
2922: my $part = shift;
2923: $part = "0" if (!defined($part));
2924: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2925:
2926: $self->getReturnHash();
2927:
2928: return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
1.51 bowersj2 2929: }
2930:
2931: =pod
2932:
2933: B<Composite Status>
2934:
1.101 bowersj2 2935: Along with directly returning the date or completion status, the resource object includes a convenience function B<status>() that will combine the two status tidbits into one composite status that can represent the status of the resource as a whole. The precise logic is documented in the comments of the status method. The following results may be returned, all available as methods on the resource object ($res->NETWORK_FAILURE):
1.51 bowersj2 2936:
2937: =over 4
2938:
1.70 bowersj2 2939: =item * B<NETWORK_FAILURE>: The network has failed and the information is not available.
1.51 bowersj2 2940:
1.70 bowersj2 2941: =item * B<NOTHING_SET>: No dates have been set for this problem (part) at all. (Because only certain parts of a multi-part problem may be assigned, this can not be collapsed into "open later", as we don't know a given part will EVER be opened. For single part, this is the same as "OPEN_LATER".)
1.53 bowersj2 2942:
1.70 bowersj2 2943: =item * B<CORRECT>: For any reason at all, the part is considered correct.
1.51 bowersj2 2944:
1.70 bowersj2 2945: =item * B<EXCUSED>: For any reason at all, the problem is excused.
1.51 bowersj2 2946:
1.70 bowersj2 2947: =item * B<PAST_DUE_NO_ANSWER>: The problem is past due, not considered correct, and no answer date is set.
1.54 bowersj2 2948:
1.70 bowersj2 2949: =item * B<PAST_DUE_ANSWER_LATER>: The problem is past due, not considered correct, and an answer date in the future is set.
1.51 bowersj2 2950:
1.70 bowersj2 2951: =item * B<ANSWER_OPEN>: The problem is past due, not correct, and the answer is now available.
1.51 bowersj2 2952:
1.70 bowersj2 2953: =item * B<OPEN_LATER>: The problem is not yet open.
1.51 bowersj2 2954:
1.70 bowersj2 2955: =item * B<TRIES_LEFT>: The problem is open, has been tried, is not correct, but there are tries left.
1.51 bowersj2 2956:
1.70 bowersj2 2957: =item * B<INCORRECT>: The problem is open, and all tries have been used without getting the correct answer.
1.51 bowersj2 2958:
1.70 bowersj2 2959: =item * B<OPEN>: The item is open and not yet tried.
1.51 bowersj2 2960:
1.70 bowersj2 2961: =item * B<ATTEMPTED>: The problem has been attempted.
1.69 bowersj2 2962:
1.51 bowersj2 2963: =back
2964:
2965: =cut
2966:
2967: sub TRIES_LEFT { return 10; }
2968:
2969: sub status {
2970: my $self = shift;
2971: my $part = shift;
2972: if (!defined($part)) { $part = "0"; }
2973: my $completionStatus = $self->getCompletionStatus($part);
2974: my $dateStatus = $self->getDateStatus($part);
2975:
2976: # What we have is a two-dimensional matrix with 4 entries on one
2977: # dimension and 5 entries on the other, which we want to colorize,
1.54 bowersj2 2978: # plus network failure and "no date data at all".
1.51 bowersj2 2979:
1.53 bowersj2 2980: if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
1.51 bowersj2 2981:
2982: # There are a few whole rows we can dispose of:
1.53 bowersj2 2983: if ($completionStatus == CORRECT ||
2984: $completionStatus == CORRECT_BY_OVERRIDE ) {
1.69 bowersj2 2985: return CORRECT;
2986: }
2987:
2988: if ($completionStatus == ATTEMPTED) {
2989: return ATTEMPTED;
1.53 bowersj2 2990: }
2991:
2992: # If it's EXCUSED, then return that no matter what
2993: if ($completionStatus == EXCUSED) {
2994: return EXCUSED;
1.51 bowersj2 2995: }
2996:
1.53 bowersj2 2997: if ($dateStatus == NOTHING_SET) {
2998: return NOTHING_SET;
1.51 bowersj2 2999: }
3000:
1.69 bowersj2 3001: # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
3002: # by 4 matrix (date statuses).
1.51 bowersj2 3003:
1.54 bowersj2 3004: if ($dateStatus == PAST_DUE_ANSWER_LATER ||
1.59 bowersj2 3005: $dateStatus == PAST_DUE_NO_ANSWER ) {
1.54 bowersj2 3006: return $dateStatus;
1.51 bowersj2 3007: }
3008:
1.53 bowersj2 3009: if ($dateStatus == ANSWER_OPEN) {
3010: return ANSWER_OPEN;
1.51 bowersj2 3011: }
3012:
3013: # Now: (incorrect, incorrect_override, not_attempted) x
3014: # (open_later), (open)
3015:
1.53 bowersj2 3016: if ($dateStatus == OPEN_LATER) {
3017: return OPEN_LATER;
1.51 bowersj2 3018: }
3019:
3020: # If it's WRONG...
1.53 bowersj2 3021: if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
1.51 bowersj2 3022: # and there are TRIES LEFT:
1.79 bowersj2 3023: if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
1.53 bowersj2 3024: return TRIES_LEFT;
1.51 bowersj2 3025: }
1.53 bowersj2 3026: return INCORRECT; # otherwise, return orange; student can't fix this
1.51 bowersj2 3027: }
3028:
3029: # Otherwise, it's untried and open
1.53 bowersj2 3030: return OPEN;
1.51 bowersj2 3031: }
3032:
3033: =pod
3034:
3035: =head2 Resource/Nav Map Navigation
3036:
3037: =over 4
3038:
1.101 bowersj2 3039: =item * B<getNext>(): Retreive an array of the possible next resources after this one. Always returns an array, even in the one- or zero-element case.
1.85 bowersj2 3040:
1.101 bowersj2 3041: =item * B<getPrevious>(): Retreive an array of the possible previous resources from this one. Always returns an array, even in the one- or zero-element case.
1.51 bowersj2 3042:
3043: =cut
3044:
3045: sub getNext {
3046: my $self = shift;
3047: my @branches;
3048: my $to = $self->to();
1.85 bowersj2 3049: foreach my $branch ( split(/,/, $to) ) {
1.51 bowersj2 3050: my $choice = $self->{NAV_MAP}->getById($branch);
3051: my $next = $choice->goesto();
3052: $next = $self->{NAV_MAP}->getById($next);
3053:
1.131 bowersj2 3054: push @branches, $next;
1.85 bowersj2 3055: }
3056: return \@branches;
3057: }
3058:
3059: sub getPrevious {
3060: my $self = shift;
3061: my @branches;
3062: my $from = $self->from();
3063: foreach my $branch ( split /,/, $from) {
3064: my $choice = $self->{NAV_MAP}->getById($branch);
3065: my $prev = $choice->comesfrom();
3066: $prev = $self->{NAV_MAP}->getById($prev);
3067:
1.131 bowersj2 3068: push @branches, $prev;
1.51 bowersj2 3069: }
3070: return \@branches;
1.131 bowersj2 3071: }
3072:
3073: sub browsePriv {
3074: my $self = shift;
3075: if (defined($self->{BROWSE_PRIV})) {
3076: return $self->{BROWSE_PRIV};
3077: }
3078:
3079: $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
1.51 bowersj2 3080: }
3081:
3082: =pod
1.2 www 3083:
1.51 bowersj2 3084: =back
1.2 www 3085:
1.51 bowersj2 3086: =cut
1.2 www 3087:
1.51 bowersj2 3088: 1;
1.2 www 3089:
1.51 bowersj2 3090: __END__
1.2 www 3091:
3092:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>