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