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