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