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