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