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