File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.415.4.2: download - view: text, annotated - select for diffs
Tue Sep 15 01:02:13 2009 UTC (14 years, 8 months ago) by raeburn
Branches: GCI_1
Diff to branchpoint 1.415: preferred, unified
- Customization for GCI_1.

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>