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