File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.177: download - view: text, annotated - select for diffs
Sat Apr 19 20:47:41 2003 UTC (21 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Uses new environment variable for role-dependent determination if user is
"advanced"

    1: # The LearningOnline Network with CAPA
    2: # Navigate Maps Handler
    3: #
    4: # $Id: lonnavmaps.pm,v 1.177 2003/04/19 20:47:41 www 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: # (Page Handler
   29: #
   30: # (TeX Content Handler
   31: #
   32: # 05/29/00,05/30 Gerd Kortemeyer)
   33: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
   34: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
   35: #
   36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
   37: # YEAR=2002
   38: # 1/1 Gerd Kortemeyer
   39: # Oct-Nov Jeremy Bowers
   40: # YEAR=2003
   41: # Jeremy Bowers ... lots of days
   42: 
   43: package Apache::lonnavmaps;
   44: 
   45: use strict;
   46: use Apache::Constants qw(:common :http);
   47: use Apache::loncommon();
   48: use Apache::lonmenu();
   49: use POSIX qw (floor strftime);
   50: 
   51: # symbolic constants
   52: sub SYMB { return 1; }
   53: sub URL { return 2; }
   54: sub NOTHING { return 3; }
   55: 
   56: # Some data
   57: 
   58: my $resObj = "Apache::lonnavmaps::resource";
   59: 
   60: # Keep these mappings in sync with lonquickgrades, which uses the colors
   61: # instead of the icons.
   62: my %statusIconMap = 
   63:     ( $resObj->NETWORK_FAILURE    => '',
   64:       $resObj->NOTHING_SET        => '',
   65:       $resObj->CORRECT            => 'navmap.correct.gif',
   66:       $resObj->EXCUSED            => 'navmap.correct.gif',
   67:       $resObj->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
   68:       $resObj->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
   69:       $resObj->ANSWER_OPEN        => 'navmap.wrong.gif',
   70:       $resObj->OPEN_LATER         => '',
   71:       $resObj->TRIES_LEFT         => 'navmap.open.gif',
   72:       $resObj->INCORRECT          => 'navmap.wrong.gif',
   73:       $resObj->OPEN               => 'navmap.open.gif',
   74:       $resObj->ATTEMPTED          => 'navmap.open.gif' );
   75: 
   76: my %iconAltTags = 
   77:     ( 'navmap.correct.gif' => 'Correct',
   78:       'navmap.wrong.gif'   => 'Incorrect',
   79:       'navmap.open.gif'    => 'Open' );
   80: 
   81: # Defines a status->color mapping, null string means don't color
   82: my %colormap = 
   83:     ( $resObj->NETWORK_FAILURE        => '',
   84:       $resObj->CORRECT                => '',
   85:       $resObj->EXCUSED                => '#3333FF',
   86:       $resObj->PAST_DUE_ANSWER_LATER  => '',
   87:       $resObj->PAST_DUE_NO_ANSWER     => '',
   88:       $resObj->ANSWER_OPEN            => '#006600',
   89:       $resObj->OPEN_LATER             => '',
   90:       $resObj->TRIES_LEFT             => '',
   91:       $resObj->INCORRECT              => '',
   92:       $resObj->OPEN                   => '',
   93:       $resObj->NOTHING_SET            => '' );
   94: # And a special case in the nav map; what to do when the assignment
   95: # is not yet done and due in less then 24 hours
   96: my $hurryUpColor = "#FF0000";
   97: 
   98: sub handler {
   99:     my $r = shift;
  100:     real_handler($r);
  101: }
  102: 
  103: sub real_handler {
  104:     my $r = shift;
  105: 
  106:     # Handle header-only request
  107:     if ($r->header_only) {
  108:         if ($ENV{'browser.mathml'}) {
  109:             $r->content_type('text/xml');
  110:         } else {
  111:             $r->content_type('text/html');
  112:         }
  113:         $r->send_http_header;
  114:         return OK;
  115:     }
  116: 
  117:     # Send header, don't cache this page
  118:     if ($ENV{'browser.mathml'}) {
  119:         $r->content_type('text/xml');
  120:     } else {
  121:         $r->content_type('text/html');
  122:     }
  123:     &Apache::loncommon::no_cache($r);
  124:     $r->send_http_header;
  125: 
  126:     # Create the nav map
  127:     my $navmap = Apache::lonnavmaps::navmap->new(
  128:                         $ENV{"request.course.fn"}.".db",
  129:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
  130: 
  131: 
  132:     if (!defined($navmap)) {
  133:         my $requrl = $r->uri;
  134:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
  135:         return HTTP_NOT_ACCEPTABLE;
  136:     }
  137: 
  138:     $r->print("<html><head>\n");
  139:     $r->print("<title>Navigate Course Contents</title>");
  140: # ------------------------------------------------------------ Get query string
  141:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register']);
  142:     
  143: # ----------------------------------------------------- Force menu registration
  144:     my $addentries='';
  145:     if ($ENV{'form.register'}) {
  146:        $addentries=' onLoad="'.&Apache::lonmenu::loadevents().
  147: 	   '" onUnload="'.&Apache::lonmenu::unloadevents().'"';
  148:        $r->print(&Apache::lonmenu::registerurl(1));
  149:     }
  150: 
  151:     # Header
  152:     $r->print('</head>'.
  153:               &Apache::loncommon::bodytag('Navigate Course Contents','',
  154:                                     $addentries,'','',$ENV{'form.register'}));
  155:     $r->print('<script>window.focus();</script>');
  156: 
  157:     $r->rflush();
  158: 
  159:     # Now that we've displayed some stuff to the user, init the navmap
  160:     $navmap->init();
  161: 
  162:     $r->print('<br>&nbsp;');
  163:     $r->rflush();
  164: 
  165:     # Check that it's defined
  166:     if (!($navmap->courseMapDefined())) {
  167:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  168:                   '</body></html>');
  169:         return OK;
  170:     }
  171: 
  172:     # See if there's only one map in the top-level... if so,
  173:     # automatically display it
  174:     my $iterator = $navmap->getIterator(undef, undef, undef, 0);
  175:     my $depth = 1;
  176:     $iterator->next();
  177:     my $curRes = $iterator->next();
  178:     my $sequenceCount = 0;
  179:     my $sequenceId;
  180:     while ($depth > 0) {
  181:         if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
  182:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  183: 
  184:         if (ref($curRes) && $curRes->is_sequence()) {
  185:             $sequenceCount++;
  186:             $sequenceId = $curRes->map_pc();
  187:         }
  188: 
  189:         $curRes = $iterator->next();
  190:     }
  191: 
  192:     if ($sequenceCount == 1) {
  193:         # The automatic iterator creation in the render call 
  194:         # will pick this up.
  195:         $ENV{'form.filter'} = "$sequenceId";
  196:     }
  197: 
  198:     # renderer call
  199:     my $render = render({ 'cols' => [0,1,2,3],
  200:                           'url' => '/adm/navmaps',
  201:                           'navmap' => $navmap,
  202:                           'suppressNavmap' => 1,
  203:                           'r' => $r});
  204: 
  205:     $navmap->untieHashes();
  206: 
  207:     $r->print("</body></html>");
  208:     $r->rflush();
  209: 
  210:     return OK;
  211: }
  212: 
  213: # Convenience functions: Returns a string that adds or subtracts
  214: # the second argument from the first hash, appropriate for the 
  215: # query string that determines which folders to recurse on
  216: sub addToFilter {
  217:     my $hashIn = shift;
  218:     my $addition = shift;
  219:     my %hash = %$hashIn;
  220:     $hash{$addition} = 1;
  221: 
  222:     return join (",", keys(%hash));
  223: }
  224: 
  225: sub removeFromFilter {
  226:     my $hashIn = shift;
  227:     my $subtraction = shift;
  228:     my %hash = %$hashIn;
  229: 
  230:     delete $hash{$subtraction};
  231:     return join(",", keys(%hash));
  232: }
  233: 
  234: # Convenience function: Given a stack returned from getStack on the iterator,
  235: # return the correct src() value.
  236: # Later, this should add an anchor when we start putting anchors in pages.
  237: sub getLinkForResource {
  238:     my $stack = shift;
  239:     my $res;
  240: 
  241:     # Check to see if there are any pages in the stack
  242:     foreach $res (@$stack) {
  243:         if (defined($res) && $res->is_page()) {
  244:             return $res->src();
  245:         }
  246:     }
  247: 
  248:     # Failing that, return the src of the last resource that is defined
  249:     # (when we first recurse on a map, it puts an undefined resource
  250:     # on the bottom because $self->{HERE} isn't defined yet, and we
  251:     # want the src for the map anyhow)
  252:     foreach (@$stack) {
  253:         if (defined($_)) { $res = $_; }
  254:     }
  255: 
  256:     return $res->src();
  257: }
  258: 
  259: # Convenience function: This seperates the logic of how to create
  260: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
  261: # etc.) into a seperate function. It takes a resource object as the
  262: # first parameter, and the part number of the resource as the second.
  263: # It's basically a big switch statement on the status of the resource.
  264: 
  265: sub getDescription {
  266:     my $res = shift;
  267:     my $part = shift;
  268:     my $status = $res->status($part);
  269: 
  270:     if ($status == $res->NETWORK_FAILURE) { return ""; }
  271:     if ($status == $res->NOTHING_SET) {
  272:         return "Not currently assigned.";
  273:     }
  274:     if ($status == $res->OPEN_LATER) {
  275:         return "Open " . timeToHumanString($res->opendate($part));
  276:     }
  277:     if ($status == $res->OPEN) {
  278:         if ($res->duedate($part)) {
  279:             return "Due " . timeToHumanString($res->duedate($part));
  280:         } else {
  281:             return "Open, no due date";
  282:         }
  283:     }
  284:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
  285:         return "Answer open " . timeToHumanString($res->answerdate($part));
  286:     }
  287:     if ($status == $res->PAST_DUE_NO_ANSWER) {
  288:         return "Was due " . timeToHumanString($res->duedate($part));
  289:     }
  290:     if ($status == $res->ANSWER_OPEN) {
  291:         return "Answer available";
  292:     }
  293:     if ($status == $res->EXCUSED) {
  294:         return "Excused by instructor";
  295:     }
  296:     if ($status == $res->ATTEMPTED) {
  297:         return "Not yet graded.";
  298:     }
  299:     if ($status == $res->TRIES_LEFT) {
  300:         my $tries = $res->tries($part);
  301:         my $maxtries = $res->maxtries($part);
  302:         my $triesString = "";
  303:         if ($tries && $maxtries) {
  304:             $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
  305:             if ($maxtries > 1 && $maxtries - $tries == 1) {
  306:                 $triesString = "<b>$triesString</b>";
  307:             }
  308:         }
  309:         if ($res->duedate()) {
  310:             return "Due " . timeToHumanString($res->duedate($part)) .
  311:                 " $triesString";
  312:         } else {
  313:             return "No due date $triesString";
  314:         }
  315:     }
  316: }
  317: 
  318: # Convenience function, so others can use it: Is the problem due in less then
  319: # 24 hours, and still can be done?
  320: 
  321: sub dueInLessThen24Hours {
  322:     my $res = shift;
  323:     my $part = shift;
  324:     my $status = $res->status($part);
  325: 
  326:     return ($status == $res->OPEN() || $status == $res->ATTEMPTED() ||
  327:             $status == $res->TRIES_LEFT()) &&
  328:            $res->duedate() && $res->duedate() < time()+(24*60*60) &&
  329:            $res->duedate() > time();
  330: }
  331: 
  332: # Convenience function, so others can use it: Is there only one try remaining for the
  333: # part, with more then one try to begin with, not due yet and still can be done?
  334: sub lastTry {
  335:     my $res = shift;
  336:     my $part = shift;
  337: 
  338:     my $tries = $res->tries($part);
  339:     my $maxtries = $res->maxtries($part);
  340:     return $tries && $maxtries && $maxtries > 1 &&
  341:         $maxtries - $tries == 1 && $res->duedate() &&
  342:         $res->duedate() > time();
  343: }
  344: 
  345: # This puts a human-readable name on the ENV variable.
  346: 
  347: sub advancedUser {
  348:     return $ENV{'request.role.adv'};
  349: }
  350: 
  351: 
  352: # timeToHumanString takes a time number and converts it to a
  353: # human-readable representation, meant to be used in the following
  354: # manner:
  355: # print "Due $timestring"
  356: # print "Open $timestring"
  357: # print "Answer available $timestring"
  358: # Very, very, very, VERY English-only... goodness help a localizer on
  359: # this func...
  360: sub timeToHumanString {
  361:     my ($time) = @_;
  362:     # zero, '0' and blank are bad times
  363:     if (!$time) {
  364:         return 'never';
  365:     }
  366: 
  367:     my $now = time();
  368: 
  369:     my @time = localtime($time);
  370:     my @now = localtime($now);
  371: 
  372:     # Positive = future
  373:     my $delta = $time - $now;
  374: 
  375:     my $minute = 60;
  376:     my $hour = 60 * $minute;
  377:     my $day = 24 * $hour;
  378:     my $week = 7 * $day;
  379:     my $inPast = 0;
  380: 
  381:     # Logic in comments:
  382:     # Is it now? (extremely unlikely)
  383:     if ( $delta == 0 ) {
  384:         return "this instant";
  385:     }
  386: 
  387:     if ($delta < 0) {
  388:         $inPast = 1;
  389:         $delta = -$delta;
  390:     }
  391: 
  392:     if ( $delta > 0 ) {
  393: 
  394:         my $tense = $inPast ? " ago" : "";
  395:         my $prefix = $inPast ? "" : "in ";
  396:         
  397:         # Less then a minute
  398:         if ( $delta < $minute ) {
  399:             if ($delta == 1) { return "${prefix}1 second$tense"; }
  400:             return "$prefix$delta seconds$tense";
  401:         }
  402: 
  403:         # Less then an hour
  404:         if ( $delta < $hour ) {
  405:             # If so, use minutes
  406:             my $minutes = floor($delta / 60);
  407:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
  408:             return "$prefix$minutes minutes$tense";
  409:         }
  410:         
  411:         # Is it less then 24 hours away? If so,
  412:         # display hours + minutes
  413:         if ( $delta < $hour * 24) {
  414:             my $hours = floor($delta / $hour);
  415:             my $minutes = floor(($delta % $hour) / $minute);
  416:             my $hourString = "$hours hours";
  417:             my $minuteString = ", $minutes minutes";
  418:             if ($hours == 1) {
  419:                 $hourString = "1 hour";
  420:             }
  421:             if ($minutes == 1) {
  422:                 $minuteString = ", 1 minute";
  423:             }
  424:             if ($minutes == 0) {
  425:                 $minuteString = "";
  426:             }
  427:             return "$prefix$hourString$minuteString$tense";
  428:         }
  429: 
  430:         # Less then 5 days away, display day of the week and
  431:         # HH:MM
  432:         if ( $delta < $day * 5 ) {
  433:             my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
  434:             $timeStr =~ s/12:00 am/midnight/;
  435:             $timeStr =~ s/12:00 pm/noon/;
  436:             return ($inPast ? "last " : "next ") .
  437:                 $timeStr;
  438:         }
  439:         
  440:         # Is it this year?
  441:         if ( $time[5] == $now[5]) {
  442:             # Return on Month Day, HH:MM meridian
  443:             my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
  444:             $timeStr =~ s/12:00 am/midnight/;
  445:             $timeStr =~ s/12:00 pm/noon/;
  446:             return $timeStr;
  447:         }
  448: 
  449:         # Not this year, so show the year
  450:         my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
  451:         $timeStr =~ s/12:00 am/midnight/;
  452:         $timeStr =~ s/12:00 pm/noon/;
  453:         return $timeStr;
  454:     }
  455: }
  456: 
  457: 
  458: =pod
  459: 
  460: =head1 NAME
  461: 
  462: Apache::lonnavmap - Subroutines to handle and render the navigation maps
  463: 
  464: =head1 SYNOPSIS
  465: 
  466: The main handler generates the navigational listing for the course,
  467: the other objects export this information in a usable fashion for
  468: other modules
  469: 
  470: =head1 Object: render
  471: 
  472: The navmap renderer package provides a sophisticated rendering of the
  473: standard navigation maps interface into HTML. The provided nav map
  474: handler is actually just a glorified call to this.
  475: 
  476: Because of the large number of parameters this function presents,
  477: instead of passing it arguments as is normal, pass it in an anonymous
  478: hash with the given options. This is because there is no obvious order
  479: you may wish to override these in and a hash is easier to read and
  480: understand then "undef, undef, undef, 1, undef, undef, renderButton,
  481: undef, 0" when you mostly want default behaviors.
  482: 
  483: The package provides a function called 'render', called as
  484: Apache::lonnavmaps::renderer->render({}).
  485: 
  486: =head2 Overview of Columns
  487: 
  488: The renderer will build an HTML table for the navmap and return
  489: it. The table is consists of several columns, and a row for each
  490: resource (or possibly each part). You tell the renderer how many
  491: columns to create and what to place in each column, optionally using
  492: one or more of the preparent columns, and the renderer will assemble
  493: the table.
  494: 
  495: Any additional generally useful column types should be placed in the
  496: renderer code here, so anybody can use it anywhere else. Any code
  497: specific to the current application (such as the addition of <input>
  498: elements in a column) should be placed in the code of the thing using
  499: the renderer.
  500: 
  501: At the core of the renderer is the array reference COLS (see Example
  502: section below for how to pass this correctly). The COLS array will
  503: consist of entries of one of two types of things: Either an integer
  504: representing one of the pre-packaged column types, or a sub reference
  505: that takes a resource reference, a part number, and a reference to the
  506: argument hash passed to the renderer, and returns a string that will
  507: be inserted into the HTML representation as it.
  508: 
  509: The pre-packaged column names are refered to by constants in the
  510: Apache::lonnavmaps::renderer namespace. The following currently exist:
  511: 
  512: =over 4
  513: 
  514: =item * B<resource>:
  515: 
  516: The general info about the resource: Link, icon for the type, etc. The
  517: first column in the standard nav map display. This column also accepts
  518: the following parameter in the renderer hash:
  519: 
  520: =over 4
  521: 
  522: =item * B<resource_nolink>:
  523: 
  524: If true, the resource will not be linked. Default: false, resource
  525: will have links.
  526: 
  527: =item * B<resource_part_count>:
  528: 
  529: If true (default), the resource will show a part count if the full
  530: part list is not displayed. If false, the resource will never show a
  531: part count.
  532: 
  533: =item * B<resource_no_folder_link>:
  534: 
  535: If true, the resource's folder will not be clickable to open or close
  536: it. Default is false. True implies printCloseAll is false, since you
  537: can't close or open folders when this is on anyhow.
  538: 
  539: =back
  540: 
  541: =item B<communication_status>:
  542: 
  543: Whether there is discussion on the resource, email for the user, or
  544: (lumped in here) perl errors in the execution of the problem. This is
  545: the second column in the main nav map.
  546: 
  547: =item B<quick_status>:
  548: 
  549: An icon for the status of a problem, with four possible states:
  550: Correct, incorrect, open, or none (not open yet, not a problem). The
  551: third column of the standard navmap.
  552: 
  553: =item B<long_status>:
  554: 
  555: A text readout of the details of the current status of the problem,
  556: such as "Due in 22 hours". The fourth column of the standard navmap.
  557: 
  558: =back
  559: 
  560: If you add any others please be sure to document them here.
  561: 
  562: An example of a column renderer that will show the ID number of a
  563: resource, along with the part name if any:
  564: 
  565:  sub { 
  566:   my ($resource, $part, $params) = @_;   
  567:   if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
  568:   return '<td>' . $resource->{ID} . '</td>';
  569:  }
  570: 
  571: Note these functions are responsible for the TD tags, which allow them
  572: to override vertical and horizontal alignment, etc.
  573: 
  574: =head2 Parameters
  575: 
  576: Most of these parameters are only useful if you are *not* using the
  577: folder interface (i.e., the default first column), which is probably
  578: the common case. If you are using this interface, then you should be
  579: able to get away with just using 'cols' (to specify the columns
  580: shown), 'url' (necessary for the folders to link to the current screen
  581: correctly), and possibly 'queryString' if your app calls for it. In
  582: that case, maintaining the state of the folders will be done
  583: automatically.
  584: 
  585: =over 4
  586: 
  587: =item * B<iterator>:
  588: 
  589: A reference to a fresh ::iterator to use from the navmaps. The
  590: rendering will reflect the options passed to the iterator, so you can
  591: use that to just render a certain part of the course, if you like. If
  592: one is not passed, the renderer will attempt to construct one from
  593: ENV{'form.filter'} and ENV{'form.condition'} information, plus the
  594: 'iterator_map' parameter if any.
  595: 
  596: =item * B<iterator_map>:
  597: 
  598: If you are letting the renderer do the iterator handling, you can
  599: instruct the renderer to render only a particular map by passing it
  600: the source of the map you want to process, like
  601: '/res/103/jerf/navmap.course.sequence'.
  602: 
  603: =item * B<navmap>:
  604: 
  605: A reference to a navmap, used only if an iterator is not passed in. If
  606: this is necessary to make an iterator but it is not passed in, a new
  607: one will be constructed based on ENV info. This is useful to do basic
  608: error checking before passing it off to render.
  609: 
  610: =item * B<r>:
  611: 
  612: The standard Apache response object. This must be passed to the
  613: renderer or the course hash will be locked.
  614: 
  615: =item * B<cols>:
  616: 
  617: An array reference
  618: 
  619: =item * B<showParts>:
  620: 
  621: A flag. If yes (default), a line for the resource itself, and a line
  622: for each part will be displayed. If not, only one line for each
  623: resource will be displayed.
  624: 
  625: =item * B<condenseParts>:
  626: 
  627: A flag. If yes (default), if all parts of the problem have the same
  628: status and that status is Nothing Set, Correct, or Network Failure,
  629: then only one line will be displayed for that resource anyhow. If no,
  630: all parts will always be displayed. If showParts is 0, this is
  631: ignored.
  632: 
  633: =item * B<jumpCount>:
  634: 
  635: A string identifying the URL to place the anchor 'curloc' at. Default
  636: to no anchor at all. It is the responsibility of the renderer user to
  637: ensure that the #curloc is in the URL. By default, determined through
  638: the use of the ENV{} 'jump' information, and should normally "just
  639: work" correctly.
  640: 
  641: =item * B<here>:
  642: 
  643: A Symb identifying where to place the 'here' marker. Default empty,
  644: which means no marker.
  645: 
  646: =item * B<indentString>:
  647: 
  648: A string identifying the indentation string to use. By default, this
  649: is a 25 pixel whitespace image with no alt text.
  650: 
  651: =item * B<queryString>:
  652: 
  653: A string which will be prepended to the query string used when the
  654: folders are opened or closed.
  655: 
  656: =item * B<url>:
  657: 
  658: The url the folders will link to, which should be the current
  659: page. Required if the resource info column is shown.
  660: 
  661: =item * B<currentJumpIndex>:
  662: 
  663: Describes the currently-open row number to cause the browser to jump
  664: to, because the user just opened that folder. By default, pulled from
  665: the Jump information in the ENV{'form.*'}.
  666: 
  667: =item * B<printKey>:
  668: 
  669: If true, print the key that appears on the top of the standard
  670: navmaps. Default is false.
  671: 
  672: =item * B<printCloseAll>:
  673: 
  674: If true, print the "Close all folders" or "open all folders"
  675: links. Default is true.
  676: 
  677: =item * B<filterFunc>:
  678: 
  679: A function that takes the resource object as its only parameter and
  680: returns a true or false value. If true, the resource is displayed. If
  681: false, it is simply skipped in the display. By default, all resources
  682: are shown.
  683: 
  684: =item * B<suppressNavmaps>:
  685: 
  686: If true, will not display Navigate Content resources. Default to
  687: false.
  688: 
  689: =back
  690: 
  691: =head2 Additional Info
  692: 
  693: In addition to the parameters you can pass to the renderer, which will
  694: be passed through unchange to the column renderers, the renderer will
  695: generate the following information which your renderer may find
  696: useful:
  697: 
  698: If you want to know how many rows were printed, the 'counter' element
  699: of the hash passed into the render function will contain the
  700: count. You may want to check whether any resources were printed at
  701: all.
  702: 
  703: =over 4
  704: 
  705: =back
  706: 
  707: =cut
  708: 
  709: sub resource { return 0; }
  710: sub communication_status { return 1; }
  711: sub quick_status { return 2; }
  712: sub long_status { return 3; }
  713: 
  714: # Data for render_resource
  715: 
  716: sub render_resource {
  717:     my ($resource, $part, $params) = @_;
  718: 
  719:     my $nonLinkedText = ''; # stuff after resource title not in link
  720: 
  721:     my $link = $params->{"resourceLink"};
  722:     my $src = $resource->src();
  723:     my $it = $params->{"iterator"};
  724:     my $filter = $it->{FILTER};
  725: 
  726:     my $title = $resource->compTitle();
  727:     if ($src =~ /^\/uploaded\//) {
  728:         $nonLinkedText=$title;
  729:         $title = '';
  730:     }
  731:     my $partLabel = "";
  732:     my $newBranchText = "";
  733:     
  734:     # If this is a new branch, label it so
  735:     if ($params->{'isNewBranch'}) {
  736:         $newBranchText = "<img src='/adm/lonIcons/branch.gif' border='0' />";
  737:     }
  738: 
  739:     # links to open and close the folder
  740:     my $linkopen = "<a href='$link'>";
  741:     my $linkclose = "</a>";
  742: 
  743:     # Default icon: HTML page
  744:     my $icon = "<img src='/adm/lonIcons/html.gif' alt='' border='0' />";
  745:     
  746:     if ($resource->is_problem()) {
  747:         if ($part eq "" || $params->{'condensed'}) {
  748:             $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border="0" />';
  749:         } else {
  750:             $icon = $params->{'indentString'};
  751:         }
  752:     }
  753: 
  754:     # Display the correct map icon to open or shut map
  755:     if ($resource->is_map()) {
  756:         my $mapId = $resource->map_pc();
  757:         my $nowOpen = !defined($filter->{$mapId});
  758:         if ($it->{CONDITION}) {
  759:             $nowOpen = !$nowOpen;
  760:         }
  761: 
  762:         if (!$params->{'resource_no_folder_link'}) {
  763:             $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') . '.gif';
  764:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
  765: 
  766:             $linkopen = "<a href='" . $params->{'url'} . '?' . 
  767:                 $params->{'queryString'} . '&filter=';
  768:             $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
  769:                 addToFilter($filter, $mapId) :
  770:                 removeFromFilter($filter, $mapId);
  771:             $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
  772:                 . $params->{'hereType'} . '&here=' .
  773:                 &Apache::lonnet::escape($params->{'here'}) . 
  774:                 '&jump=' .
  775:                 &Apache::lonnet::escape($resource->symb()) . 
  776:                 "&folderManip=1'>";
  777:         } else {
  778:             # Don't allow users to manipulate folder
  779:             $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') .
  780:                 '.nomanip.gif';
  781:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
  782: 
  783:             $linkopen = "";
  784:             $linkclose = "";
  785:         }
  786:     }
  787: 
  788:     if ($resource->randomout()) {
  789:         $nonLinkedText .= ' <i>(hidden)</i> ';
  790:     }
  791:     
  792:     # We're done preparing and finally ready to start the rendering
  793:     my $result = "<td align='left' valign='center'>";
  794: 
  795:     my $indentLevel = $params->{'indentLevel'};
  796:     if ($newBranchText) { $indentLevel--; }
  797: 
  798:     # print indentation
  799:     for (my $i = 0; $i < $indentLevel; $i++) {
  800:         $result .= $params->{'indentString'};
  801:     }
  802: 
  803:     # Decide what to display
  804:     $result .= "$newBranchText$linkopen$icon$linkclose";
  805:     
  806:     my $curMarkerBegin = '';
  807:     my $curMarkerEnd = '';
  808: 
  809:     # Is this the current resource?
  810:     if (!$params->{'displayedHereMarker'} && 
  811:         $resource->symb() eq $params->{'here'} ) {
  812:         $curMarkerBegin = '<font color="red" size="+2">&gt; </font>';
  813:         $curMarkerEnd = '<font color="red" size="+2">&lt;</font>';
  814:         $params->{'displayedHereMarker'} = 1;
  815:     }
  816: 
  817:     if ($resource->is_problem() && $part ne "" && 
  818:         !$params->{'condensed'}) {
  819:         $partLabel = " (Part $part)";
  820:         $title = "";
  821:     }
  822: 
  823:     if ($params->{'condensed'} && $resource->countParts() > 1) {
  824:         $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
  825:     }
  826: 
  827:     if (!$params->{'resource_nolink'}) {
  828:         $result .= "  $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
  829:     } else {
  830:         $result .= "  $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
  831:     }
  832: 
  833:     return $result;
  834: }
  835: 
  836: sub render_communication_status {
  837:     my ($resource, $part, $params) = @_;
  838:     my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
  839: 
  840:     my $link = $params->{"resourceLink"};
  841:     my $linkopen = "<a href='$link'>";
  842:     my $linkclose = "</a>";
  843: 
  844:     if ($resource->hasDiscussion()) {
  845:         $discussionHTML = $linkopen .
  846:             '<img border="0" src="/adm/lonMisc/chat.gif" />' .
  847:             $linkclose;
  848:     }
  849:     
  850:     if ($resource->getFeedback()) {
  851:         my $feedback = $resource->getFeedback();
  852:         foreach (split(/\,/, $feedback)) {
  853:             if ($_) {
  854:                 $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
  855:                     . &Apache::lonnet::escape($_) . '">'
  856:                     . '<img src="/adm/lonMisc/feedback.gif" '
  857:                     . 'border="0" /></a>';
  858:             }
  859:         }
  860:     }
  861:     
  862:     if ($resource->getErrors()) {
  863:         my $errors = $resource->getErrors();
  864:         foreach (split(/,/, $errors)) {
  865:             if ($_) {
  866:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
  867:                     . &Apache::lonnet::escape($_) . '">'
  868:                     . '<img src="/adm/lonMisc/bomb.gif" '
  869:                     . 'border="0" /></a>';
  870:             }
  871:         }
  872:     }
  873: 
  874:     return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
  875: 
  876: }
  877: sub render_quick_status {
  878:     my ($resource, $part, $params) = @_;
  879:     my $result = "";
  880:     my $firstDisplayed = !$params->{'condensed'} && 
  881:         $params->{'multipart'} && $part eq "0";
  882: 
  883:     my $link = $params->{"resourceLink"};
  884:     my $linkopen = "<a href='$link'>";
  885:     my $linkclose = "</a>";
  886: 
  887:     if ($resource->is_problem() &&
  888:         !$firstDisplayed) {
  889:         my $icon = $statusIconMap{$resource->status($part)};
  890:         my $alt = $iconAltTags{$icon};
  891:         if ($icon) {
  892:             $result .= "<td width='30' valign='center' width='50' align='right'>$linkopen<img width='25' height='25' src='/adm/lonIcons/$icon' border='0' alt='$alt' />$linkclose</td>\n";
  893:         } else {
  894:             $result .= "<td width='30'>&nbsp;</td>\n";
  895:         }
  896:     } else { # not problem, no icon
  897:         $result .= "<td width='30'>&nbsp;</td>\n";
  898:     }
  899: 
  900:     return $result;
  901: }
  902: sub render_long_status {
  903:     my ($resource, $part, $params) = @_;
  904:     my $result = "<td align='right' valign='center'>\n";
  905:     my $firstDisplayed = !$params->{'condensed'} && 
  906:         $params->{'multipart'} && $part eq "0";
  907:                 
  908:     my $color;
  909:     if ($resource->is_problem()) {
  910:         $color = $colormap{$resource->status};
  911:         
  912:         if (dueInLessThen24Hours($resource, $part) ||
  913:             lastTry($resource, $part)) {
  914:             $color = $hurryUpColor;
  915:         }
  916:     }
  917:     
  918:     if ($resource->kind() eq "res" &&
  919:         $resource->is_problem() &&
  920:         !$firstDisplayed) {
  921:         if ($color) {$result .= "<font color=\"$color\"><b>"; }
  922:         $result .= getDescription($resource, $part);
  923:         if ($color) {$result .= "</b></font>"; }
  924:     }
  925:     if ($resource->is_map() && advancedUser() && $resource->randompick()) {
  926:         $result .= '(randomly select ' . $resource->randompick() .')';
  927:     }
  928:     
  929:     $result .= "&nbsp;</td>\n";
  930:     
  931:     return $result;
  932: }
  933: 
  934: my @preparedColumns = (\&render_resource, \&render_communication_status,
  935:                        \&render_quick_status, \&render_long_status);
  936: 
  937: sub setDefault {
  938:     my ($val, $default) = @_;
  939:     if (!defined($val)) { return $default; }
  940:     return $val;
  941: }
  942: 
  943: sub render {
  944:     my $args = shift;
  945:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
  946:     my $result = '';
  947: 
  948:     # Configure the renderer.
  949:     my $cols = $args->{'cols'};
  950:     if (!defined($cols)) {
  951:         # no columns, no nav maps.
  952:         return '';
  953:     }
  954:     my $mustCloseNavMap = 0;
  955:     my $navmap;
  956:     if (defined($args->{'navmap'})) {
  957:         $navmap = $args->{'navmap'};
  958:     }
  959: 
  960:     my $r = $args->{'r'};
  961:     my $queryString = $args->{'queryString'};
  962:     my $jump = $args->{'jump'};
  963:     my $here = $args->{'here'};
  964:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
  965:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
  966:                              # before the current resource when using #current
  967: 
  968:     # If we were passed 'here' information, we are not rendering
  969:     # after a folder manipulation, and we were not passed an
  970:     # iterator, make sure we open the folders to show the "here"
  971:     # marker
  972:     my $filterHash = {};
  973:     # Figure out what we're not displaying
  974:     foreach (split(/\,/, $ENV{"form.filter"})) {
  975:         if ($_) {
  976:             $filterHash->{$_} = "1";
  977:         }
  978:     }
  979: 
  980:     my $condition = 0;
  981:     if ($ENV{'form.condition'}) {
  982:         $condition = 1;
  983:     }
  984: 
  985:     if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
  986:         # Step 1: Check to see if we have a navmap
  987:         if (!defined($navmap)) {
  988:             $navmap = Apache::lonnavmaps::navmap->new(
  989:                         $ENV{"request.course.fn"}.".db",
  990:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
  991:             $mustCloseNavMap = 1;
  992:         }
  993:         $navmap->init();
  994: 
  995:         # Step two: Locate what kind of here marker is necessary
  996:         # Determine where the "here" marker is and where the screen jumps to.
  997: 
  998:         if ($ENV{'form.postsymb'}) {
  999:             $here = $jump = $ENV{'form.postsymb'};
 1000:         } elsif ($ENV{'form.postdata'}) {
 1001:             # couldn't find a symb, is there a URL?
 1002:             my $currenturl = $ENV{'form.postdata'};
 1003:             #$currenturl=~s/^http\:\/\///;
 1004:             #$currenturl=~s/^[^\/]+//;
 1005:             
 1006:             $here = $jump = &Apache::lonnet::symbread($currenturl);
 1007:         }
 1008: 
 1009:         # Step three: Ensure the folders are open
 1010:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
 1011:         my $depth = 1;
 1012:         $mapIterator->next(); # discard the first BEGIN_MAP
 1013:         my $curRes = $mapIterator->next();
 1014:         my $found = 0;
 1015:         
 1016:         # We only need to do this if we need to open the maps to show the
 1017:         # current position. This will change the counter so we can't count
 1018:         # for the jump marker with this loop.
 1019:         while ($depth > 0 && !$found) {
 1020:             if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
 1021:             if ($curRes == $mapIterator->END_MAP()) { $depth--; }
 1022:             
 1023:             if (ref($curRes) && $curRes->symb() eq $here) {
 1024:                 my $mapStack = $mapIterator->getStack();
 1025:                 
 1026:                 # Ensure the parent maps are open
 1027:                 for my $map (@{$mapStack}) {
 1028:                     if ($condition) {
 1029:                         undef $filterHash->{$map->map_pc()};
 1030:                     } else {
 1031:                         $filterHash->{$map->map_pc()} = 1;
 1032:                     }
 1033:                 }
 1034:                 $found = 1;
 1035:             }
 1036:             
 1037:             $curRes = $mapIterator->next();
 1038:         }            
 1039:     }        
 1040: 
 1041:     if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
 1042:         # If this is a click on a folder or something, we want to preserve the "here"
 1043:         # from the querystring, and get the new "jump" marker
 1044:         $here = $ENV{'form.here'};
 1045:         $jump = $ENV{'form.jump'};
 1046:     } 
 1047:     
 1048:     my $it = $args->{'iterator'};
 1049:     if (!defined($it)) {
 1050:         # Construct a default iterator based on $ENV{'form.'} information
 1051:         
 1052:         # Step 1: Check to see if we have a navmap
 1053:         if (!defined($navmap)) {
 1054:             $navmap = Apache::lonnavmaps::navmap->new($r, 
 1055:                         $ENV{"request.course.fn"}.".db",
 1056:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
 1057:             $mustCloseNavMap = 1;
 1058:         }
 1059:         # Paranoia: Make sure it's ready
 1060:         $navmap->init();
 1061: 
 1062:         # See if we're being passed a specific map
 1063:         if ($args->{'iterator_map'}) {
 1064:             my $map = $args->{'iterator_map'};
 1065:             $map = $navmap->getResourceByUrl($map);
 1066:             my $firstResource = $map->map_start();
 1067:             my $finishResource = $map->map_finish();
 1068: 
 1069:             $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
 1070:         } else {
 1071:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
 1072:         }
 1073:     }
 1074:     
 1075:     # (re-)Locate the jump point, if any
 1076:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
 1077:     my $depth = 1;
 1078:     $mapIterator->next();
 1079:     my $curRes = $mapIterator->next();
 1080:     my $foundJump = 0;
 1081:     my $counter = 0;
 1082:     
 1083:     while ($depth > 0 && !$foundJump) {
 1084:         if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
 1085:         if ($curRes == $mapIterator->END_MAP()) { $depth--; }
 1086:         if (ref($curRes)) { $counter++; }
 1087:         
 1088:         if (ref($curRes) && $jump eq $curRes->symb()) {
 1089:             
 1090:             # This is why we have to use the main iterator instead of the
 1091:             # potentially faster DFS: The count has to be the same, so
 1092:             # the order has to be the same, which DFS won't give us.
 1093:             $args->{'currentJumpIndex'} = $counter;
 1094:             $foundJump = 1;
 1095:         }
 1096:         
 1097:         $curRes = $mapIterator->next();
 1098:     }
 1099: 
 1100:     my $showParts = setDefault($args->{'showParts'}, 1);
 1101:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
 1102:     # keeps track of when the current resource is found,
 1103:     # so we can back up a few and put the anchor above the
 1104:     # current resource
 1105:     my $printKey = $args->{'printKey'};
 1106:     my $printCloseAll = $args->{'printCloseAll'};
 1107:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
 1108:     my $filterFunc = setDefault($args->{'filterFunc'},
 1109:                                 sub {return 1;});
 1110:     
 1111:     # Print key?
 1112:     if ($printKey) {
 1113:         $result .= '<table border="0" cellpadding="2" cellspacing="0">';
 1114:         my $date=localtime;
 1115:         $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
 1116:         if ($navmap->{LAST_CHECK}) {
 1117:             $result .= 
 1118:                 '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
 1119:                 strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
 1120:                 '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
 1121:                 '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
 1122:                 '</td>'; 
 1123:         } else {
 1124:             $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
 1125:                 '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
 1126:                 '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
 1127:                 '</td>'; 
 1128:         }
 1129: 
 1130:         $result .= '</tr></table>';
 1131:     }
 1132: 
 1133:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
 1134:         if ($condition) {
 1135:             $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
 1136:                 "&here=" . Apache::lonnet::escape($here) .
 1137:                 "\">Close All Folders</a>";
 1138:         } else {
 1139:             $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
 1140:                 "&here=" . Apache::lonnet::escape($here) . 
 1141:                 "\">Open All Folders</a>";
 1142:         }
 1143:         $result .= "<br /><br />\n";
 1144:     }    
 1145: 
 1146:     if ($r) {
 1147:         $r->print($result);
 1148:         $r->rflush();
 1149:         $result = "";
 1150:     }
 1151:     # End parameter setting
 1152:             
 1153:     # Data
 1154:     $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
 1155:     my $res = "Apache::lonnavmaps::resource";
 1156:     my %condenseStatuses =
 1157:         ( $res->NETWORK_FAILURE    => 1,
 1158:           $res->NOTHING_SET        => 1,
 1159:           $res->CORRECT            => 1 );
 1160:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
 1161: 
 1162:     # Shared variables
 1163:     $args->{'counter'} = 0; # counts the rows
 1164:     $args->{'indentLevel'} = 0;
 1165:     $args->{'isNewBranch'} = 0;
 1166:     $args->{'condensed'} = 0;    
 1167:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
 1168:     $args->{'displayedHereMarker'} = 0;
 1169: 
 1170:     my $displayedJumpMarker = 0;
 1171:     # Set up iteration.
 1172:     $depth = 1;
 1173:     $it->next(); # discard initial BEGIN_MAP
 1174:     $curRes = $it->next();
 1175:     my $now = time();
 1176:     my $in24Hours = $now + 24 * 60 * 60;
 1177:     my $rownum = 0;
 1178: 
 1179:     # export "here" marker information
 1180:     $args->{'here'} = $here;
 1181: 
 1182:     while ($depth > 0) {
 1183:         if ($curRes == $it->BEGIN_MAP()) { $depth++; }
 1184:         if ($curRes == $it->END_MAP()) { $depth--; }
 1185: 
 1186:         # Maintain indentation level.
 1187:         if ($curRes == $it->BEGIN_MAP() ||
 1188:             $curRes == $it->BEGIN_BRANCH() ) {
 1189:             $args->{'indentLevel'}++;
 1190:         }
 1191:         if ($curRes == $it->END_MAP() ||
 1192:             $curRes == $it->END_BRANCH() ) {
 1193:             $args->{'indentLevel'}--;
 1194:         }
 1195:         # Notice new branches
 1196:         if ($curRes == $it->BEGIN_BRANCH()) {
 1197:             $args->{'isNewBranch'} = 1;
 1198:         }
 1199: 
 1200:         # If this isn't an actual resource, continue on
 1201:         if (!ref($curRes)) {
 1202:             next;
 1203:         }
 1204: 
 1205:         $args->{'counter'}++;
 1206: 
 1207:         # If this has been filtered out, continue on
 1208:         if (!(&$filterFunc($curRes))) {
 1209:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
 1210:             next;
 1211:         } 
 1212: 
 1213:         # If we're suppressing navmaps and this is a navmap, continue on
 1214:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
 1215:             next;
 1216:         }
 1217: 
 1218:         # Does it have multiple parts?
 1219:         $args->{'multipart'} = 0;
 1220:         $args->{'condensed'} = 0;
 1221:         my @parts;
 1222:             
 1223:         # Decide what parts to show.
 1224:         if ($curRes->is_problem() && $showParts) {
 1225:             @parts = @{$curRes->parts()};
 1226:             $args->{'multipart'} = scalar(@parts) > 1;
 1227:             
 1228:             if ($condenseParts) { # do the condensation
 1229:                 if (!$curRes->opendate("0")) {
 1230:                     @parts = ();
 1231:                     $args->{'condensed'} = 1;
 1232:                 }
 1233:                 if (!$args->{'condensed'}) {
 1234:                     # Decide whether to condense based on similarity
 1235:                     my $status = $curRes->status($parts[1]);
 1236:                     my $due = $curRes->duedate($parts[1]);
 1237:                     my $open = $curRes->opendate($parts[1]);
 1238:                     my $statusAllSame = 1;
 1239:                     my $dueAllSame = 1;
 1240:                     my $openAllSame = 1;
 1241:                     for (my $i = 2; $i < scalar(@parts); $i++) {
 1242:                         if ($curRes->status($parts[$i]) != $status){
 1243:                             $statusAllSame = 0;
 1244:                         }
 1245:                         if ($curRes->duedate($parts[$i]) != $due ) {
 1246:                             $dueAllSame = 0;
 1247:                         }
 1248:                         if ($curRes->opendate($parts[$i]) != $open) {
 1249:                             $openAllSame = 0;
 1250:                         }
 1251:                     }
 1252:                     # $*allSame is true if all the statuses were
 1253:                     # the same. Now, if they are all the same and
 1254:                     # match one of the statuses to condense, or they
 1255:                     # are all open with the same due date, or they are
 1256:                     # all OPEN_LATER with the same open date, display the
 1257:                     # status of the first non-zero part (to get the 'correct'
 1258:                     # status right, since 0 is never 'correct' or 'open').
 1259:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
 1260:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
 1261:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
 1262:                         @parts = ();
 1263:                         $args->{'condensed'} = 1;
 1264:                     }
 1265:                     
 1266:                 }
 1267:             }
 1268:         } 
 1269:             
 1270:         # If the multipart problem was condensed, "forget" it was multipart
 1271:         if (scalar(@parts) == 1) {
 1272:             $args->{'multipart'} = 0;
 1273:         }
 1274: 
 1275:         # Now, we've decided what parts to show. Loop through them and
 1276:         # show them.
 1277:         foreach my $part ('', @parts) {
 1278:             if ($part eq '0') {
 1279:                 next;
 1280:             }
 1281:             $rownum ++;
 1282:             my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
 1283:             
 1284:             $result .= "  <tr bgcolor='$backgroundColor'>\n";
 1285: 
 1286:             # Set up some data about the parts that the cols might want
 1287:             my $filter = $it->{FILTER};
 1288:             my $stack = $it->getStack();
 1289:             my $src = getLinkForResource($stack);
 1290:             
 1291:             my $srcHasQuestion = $src =~ /\?/;
 1292:             $args->{"resourceLink"} = $src.
 1293:                 ($srcHasQuestion?'&':'?') .
 1294:                 'symb=' . &Apache::lonnet::escape($curRes->symb());
 1295:             
 1296:             # Now, display each column.
 1297:             foreach my $col (@$cols) {
 1298:                 my $colHTML = '';
 1299:                 if (ref($col)) {
 1300:                     $colHTML .= &$col($curRes, $part, $args);
 1301:                 } else {
 1302:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
 1303:                 }
 1304: 
 1305:                 # If this is the first column and it's time to print
 1306:                 # the anchor, do so
 1307:                 if ($col == $cols->[0] && 
 1308:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
 1309:                     $currentJumpDelta) {
 1310:                     # Jam the anchor after the <td> tag;
 1311:                     # necessary for valid HTML (which Mozilla requires)
 1312:                     $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
 1313:                     $displayedJumpMarker = 1;
 1314:                 }
 1315:                 $result .= $colHTML . "\n";
 1316:             }
 1317:             $result .= "    </tr>\n";
 1318:             $args->{'isNewBranch'} = 0;
 1319:         }
 1320: 
 1321:         if ($r && $rownum % 20 == 0) {
 1322:             $r->print($result);
 1323:             $result = "";
 1324:             $r->rflush();
 1325:         }
 1326:     } continue {
 1327:         $curRes = $it->next();
 1328:     }
 1329:     
 1330:     # Print out the part that jumps to #curloc if it exists
 1331:     # delay needed because the browser is processing the jump before
 1332:     # it finishes rendering, so it goes to the wrong place!
 1333:     # onload might be better, but this routine has no access to that.
 1334:     # On mozilla, the 0-millisecond timeout seems to prevent this;
 1335:     # it's quite likely this might fix other browsers, too, and 
 1336:     # certainly won't hurt anything.
 1337:     if ($displayedJumpMarker) {
 1338:         $result .= "<script>setTimeout(\"location += '#curloc';\", 0)</script>\n";
 1339:     }
 1340: 
 1341:     $result .= "</table>";
 1342:     
 1343:     if ($r) {
 1344:         $r->print($result);
 1345:         $result = "";
 1346:         $r->rflush();
 1347:     }
 1348:         
 1349:     if ($mustCloseNavMap) { $navmap->untieHashes(); } 
 1350: 
 1351:     return $result;
 1352: }
 1353: 
 1354: 1;
 1355: 
 1356: package Apache::lonnavmaps::navmap;
 1357: 
 1358: =pod
 1359: 
 1360: lonnavmaps provides functions and objects for dealing with the
 1361: compiled course hashes generated when a user enters the course, the
 1362: Apache handler for the "Navigation Map" button, and a flexible
 1363: prepared renderer for navigation maps that are easy to use anywhere.
 1364: 
 1365: =head1 Object: navmap
 1366: 
 1367: Encapsulating the compiled nav map
 1368: 
 1369: navmap is an object that encapsulates a compiled course map and
 1370: provides a reasonable interface to it.
 1371: 
 1372: Most notably it provides a way to navigate the map sensibly and a
 1373: flexible iterator that makes it easy to write various renderers based
 1374: on nav maps.
 1375: 
 1376: You must obtain resource objects through the navmap object.
 1377: 
 1378: =head2 Methods
 1379: 
 1380: =over 4
 1381: 
 1382: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions,
 1383:   genMailDiscussStatus):
 1384: 
 1385: Binds a new navmap object to the compiled nav map hash and parm hash
 1386: given as filenames. genCourseAndUserOptions is a flag saying whether
 1387: the course options and user options hash should be generated. This is
 1388: for when you are using the parameters of the resources that require
 1389: them; see documentation in resource object
 1390: documentation. genMailDiscussStatus causes the nav map to retreive
 1391: information about the email and discussion status of
 1392: resources. Returns the navmap object if this is successful, or
 1393: B<undef> if not. You must check for undef; errors will occur when you
 1394: try to use the other methods otherwise.
 1395: 
 1396: =item * B<getIterator>(first, finish, filter, condition):
 1397: 
 1398: See iterator documentation below.
 1399: 
 1400: =cut
 1401: 
 1402: use strict;
 1403: use GDBM_File;
 1404: 
 1405: sub new {
 1406:     # magic invocation to create a class instance
 1407:     my $proto = shift;
 1408:     my $class = ref($proto) || $proto;
 1409:     my $self = {};
 1410: 
 1411:     $self->{NAV_HASH_FILE} = shift;
 1412:     $self->{PARM_HASH_FILE} = shift;
 1413:     $self->{GENERATE_COURSE_USER_OPT} = shift;
 1414:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
 1415: 
 1416:     # Resource cache stores navmap resources as we reference them. We generate
 1417:     # them on-demand so we don't pay for creating resources unless we use them.
 1418:     $self->{RESOURCE_CACHE} = {};
 1419: 
 1420:     # Network failure flag, if we accessed the course or user opt and
 1421:     # failed
 1422:     $self->{NETWORK_FAILURE} = 0;
 1423: 
 1424:     # tie the nav hash
 1425: 
 1426:     my %navmaphash;
 1427:     my %parmhash;
 1428:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
 1429:               &GDBM_READER(), 0640))) {
 1430:         return undef;
 1431:     }
 1432:     
 1433:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
 1434:               &GDBM_READER(), 0640)))
 1435:     {
 1436:         untie %{$self->{PARM_HASH}};
 1437:         return undef;
 1438:     }
 1439: 
 1440:     $self->{NAV_HASH} = \%navmaphash;
 1441:     $self->{PARM_HASH} = \%parmhash;
 1442:     $self->{INITED} = 0;
 1443: 
 1444:     bless($self);
 1445:         
 1446:     return $self;
 1447: }
 1448: 
 1449: sub init {
 1450:     my $self = shift;
 1451:     if ($self->{INITED}) { return; }
 1452: 
 1453:     # If the course opt hash and the user opt hash should be generated,
 1454:     # generate them
 1455:     if ($self->{GENERATE_COURSE_USER_OPT}) {
 1456:         my $uname=$ENV{'user.name'};
 1457:         my $udom=$ENV{'user.domain'};
 1458:         my $uhome=$ENV{'user.home'};
 1459:         my $cid=$ENV{'request.course.id'};
 1460:         my $chome=$ENV{'course.'.$cid.'.home'};
 1461:         my ($cdom,$cnum)=split(/\_/,$cid);
 1462:         
 1463:         my $userprefix=$uname.'_'.$udom.'_';
 1464:         
 1465:         my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
 1466:         unless ($uhome eq 'no_host') { 
 1467: # ------------------------------------------------- Get coursedata (if present)
 1468:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1469:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1470:                                                  ':resourcedata',$chome);
 1471:                 if ($reply!~/^error\:/) {
 1472:                     $courserdatas{$cid}=$reply;
 1473:                     $courserdatas{$cid.'.last_cache'}=time;
 1474:                 }
 1475:                 # check to see if network failed
 1476:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1477:                 {
 1478:                     $self->{NETWORK_FAILURE} = 1;
 1479:                 }
 1480:             }
 1481:             foreach (split(/\&/,$courserdatas{$cid})) {
 1482:                 my ($name,$value)=split(/\=/,$_);
 1483:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1484:                     &Apache::lonnet::unescape($value);
 1485:             }
 1486: # --------------------------------------------------- Get userdata (if present)
 1487:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1488:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1489:                 if ($reply!~/^error\:/) {
 1490:                     $userrdatas{$uname.'___'.$udom}=$reply;
 1491:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1492:                 }
 1493:                 # check to see if network failed
 1494:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1495:                 {
 1496:                     $self->{NETWORK_FAILURE} = 1;
 1497:                 }
 1498:             }
 1499:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 1500:                 my ($name,$value)=split(/\=/,$_);
 1501:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1502:                     &Apache::lonnet::unescape($value);
 1503:             }
 1504:             $self->{COURSE_OPT} = \%courseopt;
 1505:             $self->{USER_OPT} = \%useropt;
 1506:         }
 1507:     }   
 1508: 
 1509:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
 1510:         my $cid=$ENV{'request.course.id'};
 1511:         my ($cdom,$cnum)=split(/\_/,$cid);
 1512:         
 1513:         my %emailstatus = &Apache::lonnet::dump('email_status');
 1514:         my $logoutTime = $emailstatus{'logout'};
 1515:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
 1516:         $self->{LAST_CHECK} = ($courseLeaveTime < $logoutTime ?
 1517:                                $courseLeaveTime : $logoutTime);
 1518:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 1519:                                                    $cdom, $cnum);
 1520:         my %feedback=();
 1521:         my %error=();
 1522:         my $keys = &Apache::lonnet::reply('keys:'.
 1523:                                           $ENV{'user.domain'}.':'.
 1524:                                           $ENV{'user.name'}.':nohist_email',
 1525:                                           $ENV{'user.home'});
 1526: 
 1527:         foreach my $msgid (split(/\&/, $keys)) {
 1528:             $msgid=&Apache::lonnet::unescape($msgid);
 1529:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
 1530:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
 1531:                 my ($what,$url)=($1,$2);
 1532:                 my %status=
 1533:                     &Apache::lonnet::get('email_status',[$msgid]);
 1534:                 if ($status{$msgid}=~/^error\:/) { 
 1535:                     $status{$msgid}=''; 
 1536:                 }
 1537:                 
 1538:                 if (($status{$msgid} eq 'new') || 
 1539:                     (!$status{$msgid})) { 
 1540:                     if ($what eq 'Error') {
 1541:                         $error{$url}.=','.$msgid; 
 1542:                     } else {
 1543:                         $feedback{$url}.=','.$msgid;
 1544:                     }
 1545:                 }
 1546:             }
 1547:         }
 1548:         
 1549:         $self->{FEEDBACK} = \%feedback;
 1550:         $self->{ERROR_MSG} = \%error; # what is this? JB
 1551:         $self->{DISCUSSION_TIME} = \%discussiontime;
 1552:         $self->{EMAIL_STATUS} = \%emailstatus;
 1553:         
 1554:     }    
 1555: 
 1556:     $self->{PARM_CACHE} = {};
 1557:     $self->{INITED} = 1;
 1558: }
 1559: 
 1560: # Internal function: Takes a key to look up in the nav hash and implements internal
 1561: # memory caching of that key.
 1562: sub navhash {
 1563:     my $self = shift; my $key = shift;
 1564:     return $self->{NAV_HASH}->{$key};
 1565: }
 1566: 
 1567: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1568: sub courseMapDefined {
 1569:     my $self = shift;
 1570:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1571: 
 1572:     my $firstres = $self->navhash("map_start_$uri");
 1573:     my $lastres = $self->navhash("map_finish_$uri");
 1574:     return $firstres && $lastres;
 1575: }
 1576: 
 1577: sub getIterator {
 1578:     my $self = shift;
 1579:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 1580:                                                      shift, undef, shift);
 1581:     return $iterator;
 1582: }
 1583: 
 1584: # unties the hash when done
 1585: sub untieHashes {
 1586:     my $self = shift;
 1587:     untie %{$self->{NAV_HASH}};
 1588:     untie %{$self->{PARM_HASH}};
 1589: }
 1590: 
 1591: # Private method: Does the given resource (as a symb string) have
 1592: # current discussion? Returns 0 if chat/mail data not extracted.
 1593: sub hasDiscussion {
 1594:     my $self = shift;
 1595:     my $symb = shift;
 1596:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1597: 
 1598:     #return defined($self->{DISCUSSION_TIME}->{$symb});
 1599:     return $self->{DISCUSSION_TIME}->{$symb} >
 1600:            $self->{LAST_CHECK};
 1601: }
 1602: 
 1603: # Private method: Does the given resource (as a symb string) have
 1604: # current feedback? Returns the string in the feedback hash, which
 1605: # will be false if it does not exist.
 1606: sub getFeedback { 
 1607:     my $self = shift;
 1608:     my $symb = shift;
 1609: 
 1610:     if (!defined($self->{FEEDBACK})) { return ""; }
 1611:     
 1612:     return $self->{FEEDBACK}->{$symb};
 1613: }
 1614: 
 1615: # Private method: Get the errors for that resource (by source).
 1616: sub getErrors { 
 1617:     my $self = shift;
 1618:     my $src = shift;
 1619:     
 1620:     if (!defined($self->{ERROR_MSG})) { return ""; }
 1621:     return $self->{ERROR_MSG}->{$src};
 1622: }
 1623: 
 1624: =pod
 1625: 
 1626: =item * B<getById>(id):
 1627: 
 1628: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
 1629: object for that resource. This method, or other methods that use it
 1630: (as in the resource object) is the only proper way to obtain a
 1631: resource object.
 1632: 
 1633: =cut
 1634: 
 1635: # The strategy here is to cache the resource objects, and only construct them
 1636: # as we use them. The real point is to prevent reading any more from the tied
 1637: # hash then we have to, which should hopefully alleviate speed problems.
 1638: # Caching is just an incidental detail I throw in because it makes sense.
 1639: 
 1640: sub getById {
 1641:     my $self = shift;
 1642:     my $id = shift;
 1643: 
 1644:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1645:     {
 1646:         return $self->{RESOURCE_CACHE}->{$id};
 1647:     }
 1648: 
 1649:     # resource handles inserting itself into cache.
 1650:     # Not clear why the quotes are necessary, but as of this
 1651:     # writing it doesn't work without them.
 1652:     return "Apache::lonnavmaps::resource"->new($self, $id);
 1653: }
 1654: 
 1655: sub getBySymb {
 1656:     my $self = shift;
 1657:     my $symb = shift;
 1658:     my ($mapUrl, $id, $filename) = split (/___/, $symb);
 1659:     my $map = $self->getResourceByUrl($mapUrl);
 1660:     return $self->getById($map->map_pc() . '.' . $id);
 1661: }
 1662: 
 1663: =pod
 1664: 
 1665: =item * B<firstResource>():
 1666: 
 1667: Returns a resource object reference corresponding to the first
 1668: resource in the navmap.
 1669: 
 1670: =cut
 1671: 
 1672: sub firstResource {
 1673:     my $self = shift;
 1674:     my $firstResource = $self->navhash('map_start_' .
 1675:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
 1676:     return $self->getById($firstResource);
 1677: }
 1678: 
 1679: =pod
 1680: 
 1681: =item * B<finishResource>():
 1682: 
 1683: Returns a resource object reference corresponding to the last resource
 1684: in the navmap.
 1685: 
 1686: =cut
 1687: 
 1688: sub finishResource {
 1689:     my $self = shift;
 1690:     my $firstResource = $self->navhash('map_finish_' .
 1691:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
 1692:     return $self->getById($firstResource);
 1693: }
 1694: 
 1695: # Parmval reads the parm hash and cascades the lookups. parmval_real does
 1696: # the actual lookup; parmval caches the results.
 1697: sub parmval {
 1698:     my $self = shift;
 1699:     my ($what,$symb)=@_;
 1700:     my $hashkey = $what."|||".$symb;
 1701: 
 1702:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
 1703:         return $self->{PARM_CACHE}->{$hashkey};
 1704:     }
 1705: 
 1706:     my $result = $self->parmval_real($what, $symb);
 1707:     $self->{PARM_CACHE}->{$hashkey} = $result;
 1708:     return $result;
 1709: }
 1710: 
 1711: sub parmval_real {
 1712:     my $self = shift;
 1713:     my ($what,$symb) = @_;
 1714: 
 1715:     my $cid=$ENV{'request.course.id'};
 1716:     my $csec=$ENV{'request.course.sec'};
 1717:     my $uname=$ENV{'user.name'};
 1718:     my $udom=$ENV{'user.domain'};
 1719: 
 1720:     unless ($symb) { return ''; }
 1721:     my $result='';
 1722: 
 1723:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1724: 
 1725: # ----------------------------------------------------- Cascading lookup scheme
 1726:     my $rwhat=$what;
 1727:     $what=~s/^parameter\_//;
 1728:     $what=~s/\_/\./;
 1729: 
 1730:     my $symbparm=$symb.'.'.$what;
 1731:     my $mapparm=$mapname.'___(all).'.$what;
 1732:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1733: 
 1734:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 1735:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 1736:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 1737: 
 1738:     my $courselevel= $usercourseprefix.'.'.$what;
 1739:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 1740:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 1741: 
 1742:     my $useropt = $self->{USER_OPT};
 1743:     my $courseopt = $self->{COURSE_OPT};
 1744:     my $parmhash = $self->{PARM_HASH};
 1745: 
 1746: # ---------------------------------------------------------- first, check user
 1747:     if ($uname and defined($useropt)) {
 1748:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 1749:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 1750:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 1751:     }
 1752: 
 1753: # ------------------------------------------------------- second, check course
 1754:     if ($csec and defined($courseopt)) {
 1755:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 1756:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 1757:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 1758:     }
 1759: 
 1760:     if (defined($courseopt)) {
 1761:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 1762:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 1763:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 1764:     }
 1765: 
 1766: # ----------------------------------------------------- third, check map parms
 1767: 
 1768:     my $thisparm=$$parmhash{$symbparm};
 1769:     if (defined($thisparm)) { return $thisparm; }
 1770: 
 1771: # ----------------------------------------------------- fourth , check default
 1772: 
 1773:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 1774:     if (defined($default)) { return $default}
 1775: 
 1776: # --------------------------------------------------- fifth , cascade up parts
 1777: 
 1778:     my ($space,@qualifier)=split(/\./,$rwhat);
 1779:     my $qualifier=join('.',@qualifier);
 1780:     unless ($space eq '0') {
 1781: 	my @parts=split(/_/,$space);
 1782: 	my $id=pop(@parts);
 1783: 	my $part=join('_',@parts);
 1784: 	if ($part eq '') { $part='0'; }
 1785: 	my $partgeneral=$self->parmval($part.".$qualifier",$symb);
 1786: 	if (defined($partgeneral)) { return $partgeneral; }
 1787:     }
 1788:     return '';
 1789: }
 1790: 
 1791: =pod
 1792: 
 1793: =item * B<getResourceByUrl>(url):
 1794: 
 1795: Retrieves a resource object by URL of the resource. If passed a
 1796: resource object, it will simply return it, so it is safe to use this
 1797: method in code like "$res = $navmap->getResourceByUrl($res)", if
 1798: you're not sure if $res is already an object, or just a URL. If the
 1799: resource appears multiple times in the course, only the first instance
 1800: will be returned. As a result, this is probably useful only for maps.
 1801: 
 1802: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
 1803: 
 1804: The map is a specification of a map to retreive the resources from,
 1805: either as a url or as an object. The filterFunc is a reference to a
 1806: function that takes a resource object as its one argument and returns
 1807: true if the resource should be included, or false if it should not
 1808: be. If recursive is true, the map will be recursively examined,
 1809: otherwise it will not be. If bailout is true, the function will return
 1810: as soon as it finds a resource, if false it will finish. By default,
 1811: the map is the top-level map of the course, filterFunc is a function
 1812: that always returns 1, recursive is true, bailout is false. The
 1813: resources will be returned in a list containing the resource objects
 1814: for the corresponding resources, with B<no structure information> in
 1815: the list; regardless of branching, recursion, etc., it will be a flat
 1816: list.
 1817: 
 1818: Thus, this is suitable for cases where you don't want the structure,
 1819: just a list of all resources. It is also suitable for finding out how
 1820: many resources match a given description; for this use, if all you
 1821: want to know is if I<any> resources match the description, the bailout
 1822: parameter will allow you to avoid potentially expensive enumeration of
 1823: all matching resources.
 1824: 
 1825: =item * B<hasResources>(map, filterFunc, recursive):
 1826: 
 1827: Convience method for
 1828: 
 1829:  scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
 1830: 
 1831: which will tell whether the map has resources matching the description
 1832: in the filter function.
 1833: 
 1834: =cut
 1835: 
 1836: sub getResourceByUrl {
 1837:     my $self = shift;
 1838:     my $resUrl = shift;
 1839: 
 1840:     if (ref($resUrl)) { return $resUrl; }
 1841: 
 1842:     $resUrl = &Apache::lonnet::clutter($resUrl);
 1843:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
 1844:     if ($resId =~ /,/) {
 1845:         $resId = (split (/,/, $resId))[0];
 1846:     }
 1847:     if (!$resId) { return ''; }
 1848:     return $self->getById($resId);
 1849: }
 1850: 
 1851: sub retrieveResources {
 1852:     my $self = shift;
 1853:     my $map = shift;
 1854:     my $filterFunc = shift;
 1855:     if (!defined ($filterFunc)) {
 1856:         $filterFunc = sub {return 1;};
 1857:     }
 1858:     my $recursive = shift;
 1859:     if (!defined($recursive)) { $recursive = 1; }
 1860:     my $bailout = shift;
 1861:     if (!defined($bailout)) { $bailout = 0; }
 1862: 
 1863:     # Create the necessary iterator.
 1864:     if (!ref($map)) { # assume it's a url of a map.
 1865:         $map = $self->getResourceByUrl($map);
 1866:     }
 1867: 
 1868:     # Check the map's validity.
 1869:     if (!$map || !$map->is_map()) {
 1870:         # Oh, to throw an exception.... how I'd love that!
 1871:         return ();
 1872:     }
 1873: 
 1874:     # Get an iterator.
 1875:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
 1876:                                 !$recursive);
 1877: 
 1878:     my @resources = ();
 1879: 
 1880:     # Run down the iterator and collect the resources.
 1881:     my $depth = 1;
 1882:     $it->next();
 1883:     my $curRes = $it->next();
 1884: 
 1885:     while ($depth > 0) {
 1886:         if ($curRes == $it->BEGIN_MAP()) {
 1887:             $depth++;
 1888:         }
 1889:         if ($curRes == $it->END_MAP()) {
 1890:             $depth--;
 1891:         }
 1892:         
 1893:         if (ref($curRes)) {
 1894:             if (!&$filterFunc($curRes)) {
 1895:                 next;
 1896:             }
 1897: 
 1898:             push @resources, $curRes;
 1899: 
 1900:             if ($bailout) {
 1901:                 return @resources;
 1902:             }
 1903:         }
 1904: 
 1905:         $curRes = $it->next();
 1906:     }
 1907: 
 1908:     return @resources;
 1909: }
 1910: 
 1911: sub hasResource {
 1912:     my $self = shift;
 1913:     my $map = shift;
 1914:     my $filterFunc = shift;
 1915:     my $recursive = shift;
 1916:     
 1917:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
 1918: }
 1919: 
 1920: 1;
 1921: 
 1922: package Apache::lonnavmaps::iterator;
 1923: 
 1924: =pod
 1925: 
 1926: =back
 1927: 
 1928: =head1 Object: navmap Iterator
 1929: 
 1930: An I<iterator> encapsulates the logic required to traverse a data
 1931: structure. navmap uses an iterator to traverse the course map
 1932: according to the criteria you wish to use.
 1933: 
 1934: To obtain an iterator, call the B<getIterator>() function of a
 1935: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
 1936: directly.) This will return a reference to the iterator:
 1937: 
 1938: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 1939: 
 1940: To get the next thing from the iterator, call B<next>:
 1941: 
 1942: C<my $nextThing = $resourceIterator-E<gt>next()>
 1943: 
 1944: getIterator behaves as follows:
 1945: 
 1946: =over 4
 1947: 
 1948: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
 1949: 
 1950: All parameters are optional. firstResource is a resource reference
 1951: corresponding to where the iterator should start. It defaults to
 1952: navmap->firstResource() for the corresponding nav map. finishResource
 1953: corresponds to where you want the iterator to end, defaulting to
 1954: navmap->finishResource(). filterHash is a hash used as a set
 1955: containing strings representing the resource IDs, defaulting to
 1956: empty. Condition is a 1 or 0 that sets what to do with the filter
 1957: hash: If a 0, then only resource that exist IN the filterHash will be
 1958: recursed on. If it is a 1, only resources NOT in the filterHash will
 1959: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
 1960: false (default), the iterator will only return the first level of map
 1961: that is not just a single, 'redirecting' map. If true, the iterator
 1962: will return all information, starting with the top-level map,
 1963: regardless of content. returnTopMap, if true (default false), will
 1964: cause the iterator to return the top-level map object (resource 0.0)
 1965: before anything else.
 1966: 
 1967: Thus, by default, only top-level resources will be shown. Change the
 1968: condition to a 1 without changing the hash, and all resources will be
 1969: shown. Changing the condition to 1 and including some values in the
 1970: hash will allow you to selectively suppress parts of the navmap, while
 1971: leaving it on 0 and adding things to the hash will allow you to
 1972: selectively add parts of the nav map. See the handler code for
 1973: examples.
 1974: 
 1975: The iterator will return either a reference to a resource object, or a
 1976: token representing something in the map, such as the beginning of a
 1977: new branch. The possible tokens are:
 1978: 
 1979: =over 4
 1980: 
 1981: =item * BEGIN_MAP:
 1982: 
 1983: A new map is being recursed into. This is returned I<after> the map
 1984: resource itself is returned.
 1985: 
 1986: =item * END_MAP:
 1987: 
 1988: The map is now done.
 1989: 
 1990: =item * BEGIN_BRANCH:
 1991: 
 1992: A branch is now starting. The next resource returned will be the first
 1993: in that branch.
 1994: 
 1995: =item * END_BRANCH:
 1996: 
 1997: The branch is now done.
 1998: 
 1999: =back
 2000: 
 2001: The tokens are retreivable via methods on the iterator object, i.e.,
 2002: $iterator->END_MAP.
 2003: 
 2004: Maps can contain empty resources. The iterator will automatically skip
 2005: over such resources, but will still treat the structure
 2006: correctly. Thus, a complicated map with several branches, but
 2007: consisting entirely of empty resources except for one beginning or
 2008: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
 2009: but only one resource will be returned.
 2010: 
 2011: =back
 2012: 
 2013: =cut
 2014: 
 2015: # Here are the tokens for the iterator:
 2016: 
 2017: sub BEGIN_MAP { return 1; }    # begining of a new map
 2018: sub END_MAP { return 2; }      # end of the map
 2019: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 2020: sub END_BRANCH { return 4; }   # end of a branch
 2021: sub FORWARD { return 1; }      # go forward
 2022: sub BACKWARD { return 2; }
 2023: 
 2024: sub min {
 2025:     (my $a, my $b) = @_;
 2026:     if ($a < $b) { return $a; } else { return $b; }
 2027: }
 2028: 
 2029: # In the CVS repository, documentation of this algorithm is included 
 2030: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
 2031: # will reference the same location in the text as the part of the
 2032: # algorithm is running through.
 2033: 
 2034: sub new {
 2035:     # magic invocation to create a class instance
 2036:     my $proto = shift;
 2037:     my $class = ref($proto) || $proto;
 2038:     my $self = {};
 2039: 
 2040:     $self->{NAV_MAP} = shift;
 2041:     return undef unless ($self->{NAV_MAP});
 2042: 
 2043:     # Handle the parameters
 2044:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2045:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2046: 
 2047:     # If the given resources are just the ID of the resource, get the
 2048:     # objects
 2049:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2050:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2051:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2052:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2053: 
 2054:     $self->{FILTER} = shift;
 2055: 
 2056:     # A hash, used as a set, of resource already seen
 2057:     $self->{ALREADY_SEEN} = shift;
 2058:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2059:     $self->{CONDITION} = shift;
 2060: 
 2061:     # Do we want to automatically follow "redirection" maps?
 2062:     $self->{FORCE_TOP} = shift;
 2063: 
 2064:     # Do we want to return the top-level map object (resource 0.0)?
 2065:     $self->{RETURN_0} = shift;
 2066:     # have we done that yet?
 2067:     $self->{HAVE_RETURNED_0} = 0;
 2068: 
 2069:     # Now, we need to pre-process the map, by walking forward and backward
 2070:     # over the parts of the map we're going to look at.
 2071: 
 2072:     # The processing steps are exactly the same, except for a few small 
 2073:     # changes, so I bundle those up in the following list of two elements:
 2074:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
 2075:     # first_resource).
 2076:     # This prevents writing nearly-identical code twice.
 2077:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
 2078:                         'FIRST_RESOURCE'],
 2079:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
 2080:                         'FINISH_RESOURCE'] );
 2081: 
 2082:     my $maxDepth = 0; # tracks max depth
 2083: 
 2084:     # If there is only one resource in this map, and it's a map, we
 2085:     # want to remember that, so the user can ask for the first map
 2086:     # that isn't just a redirector.
 2087:     my $resource; my $resourceCount = 0;
 2088: 
 2089:     # **1**
 2090: 
 2091:     foreach my $pass (@iterations) {
 2092:         my $direction = $pass->[0];
 2093:         my $valName = $pass->[1];
 2094:         my $nextResourceMethod = $pass->[2];
 2095:         my $firstResourceName = $pass->[3];
 2096: 
 2097:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
 2098:                                                             $self->{FIRST_RESOURCE},
 2099:                                                             $self->{FINISH_RESOURCE},
 2100:                                                             {}, undef, 0, $direction);
 2101:     
 2102:         # prime the recursion
 2103:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
 2104:         my $depth = 0;
 2105:         $iterator->next();
 2106:         my $curRes = $iterator->next();
 2107:         while ($depth > -1) {
 2108:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
 2109:             if ($curRes == $iterator->END_MAP()) { $depth--; }
 2110:         
 2111:             if (ref($curRes)) {
 2112:                 # If there's only one resource, this will save it
 2113:                 # we have to filter empty resources from consideration here,
 2114:                 # or even "empty", redirecting maps have two (start & finish)
 2115:                 # or three (start, finish, plus redirector)
 2116:                 if($direction == FORWARD && $curRes->src()) { 
 2117:                     $resource = $curRes; $resourceCount++; 
 2118:                 }
 2119:                 my $resultingVal = $curRes->{DATA}->{$valName};
 2120:                 my $nextResources = $curRes->$nextResourceMethod();
 2121:                 my $nextCount = scalar(@{$nextResources});
 2122: 
 2123:                 if ($nextCount == 1) { # **3**
 2124:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
 2125:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
 2126:                 }
 2127:                 
 2128:                 if ($nextCount > 1) { # **4**
 2129:                     foreach my $res (@{$nextResources}) {
 2130:                         my $current = $res->{DATA}->{$valName} || 999999999;
 2131:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
 2132:                     }
 2133:                 }
 2134:             }
 2135:             
 2136:             # Assign the final val (**2**)
 2137:             if (ref($curRes) && $direction == BACKWARD()) {
 2138:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
 2139:                                      $curRes->{DATA}->{BOT_UP_VAL});
 2140:                 
 2141:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
 2142:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
 2143:                 }
 2144:             $curRes = $iterator->next();
 2145:         }
 2146:     }
 2147: 
 2148:     # Check: Was this only one resource, a map?
 2149:     if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) { 
 2150:         my $firstResource = $resource->map_start();
 2151:         my $finishResource = $resource->map_finish();
 2152:         return 
 2153:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 2154:                                               $finishResource, $self->{FILTER},
 2155:                                               $self->{ALREADY_SEEN}, 
 2156:                                               $self->{CONDITION}, 0);
 2157:         
 2158:     }
 2159: 
 2160:     # Set up some bookkeeping information.
 2161:     $self->{CURRENT_DEPTH} = 0;
 2162:     $self->{MAX_DEPTH} = $maxDepth;
 2163:     $self->{STACK} = [];
 2164:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2165: 
 2166:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
 2167:         push @{$self->{STACK}}, [];
 2168:     }
 2169: 
 2170:     # Prime the recursion w/ the first resource **5**
 2171:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
 2172:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
 2173: 
 2174:     bless ($self);
 2175: 
 2176:     return $self;
 2177: }
 2178: 
 2179: sub next {
 2180:     my $self = shift;
 2181: 
 2182:     # If we want to return the top-level map object, and haven't yet,
 2183:     # do so.
 2184:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
 2185:         $self->{HAVE_RETURNED_0} = 1;
 2186:         return $self->{NAV_MAP}->getById('0.0');
 2187:     }
 2188: 
 2189:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2190:         # grab the next from the recursive iterator 
 2191:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 2192: 
 2193:         # is it a begin or end map? If so, update the depth
 2194:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 2195:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 2196: 
 2197:         # Are we back at depth 0? If so, stop recursing
 2198:         if ($self->{RECURSIVE_DEPTH} == 0) {
 2199:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2200:         }
 2201: 
 2202:         return $next;
 2203:     }
 2204: 
 2205:     if (defined($self->{FORCE_NEXT})) {
 2206:         my $tmp = $self->{FORCE_NEXT};
 2207:         $self->{FORCE_NEXT} = undef;
 2208:         return $tmp;
 2209:     }
 2210: 
 2211:     # Have we not yet begun? If not, return BEGIN_MAP and
 2212:     # remember we've started.
 2213:     if ( !$self->{STARTED} ) { 
 2214:         $self->{STARTED} = 1;
 2215:         return $self->BEGIN_MAP();
 2216:     }
 2217: 
 2218:     # Here's the guts of the iterator.
 2219:     
 2220:     # Find the next resource, if any.
 2221:     my $found = 0;
 2222:     my $i = $self->{MAX_DEPTH};
 2223:     my $newDepth;
 2224:     my $here;
 2225:     while ( $i >= 0 && !$found ) {
 2226:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
 2227:             $here = pop @{$self->{STACK}->[$i]}; # **7**
 2228:             $found = 1;
 2229:             $newDepth = $i;
 2230:         }
 2231:         $i--;
 2232:     }
 2233: 
 2234:     # If we still didn't find anything, we're done.
 2235:     if ( !$found ) {
 2236:         # We need to get back down to the correct branch depth
 2237:         if ( $self->{CURRENT_DEPTH} > 0 ) {
 2238:             $self->{CURRENT_DEPTH}--;
 2239:             return END_BRANCH();
 2240:         } else {
 2241:             return END_MAP();
 2242:         }
 2243:     }
 2244: 
 2245:     # If this is not a resource, it must be an END_BRANCH marker we want
 2246:     # to return directly.
 2247:     if (!ref($here)) { # **8**
 2248:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
 2249:             $self->{CURRENT_DEPTH}--;
 2250:             return $here;
 2251:         }
 2252:     }
 2253: 
 2254:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
 2255:     $self->{HERE} = $here;
 2256: 
 2257:     # Get to the right level
 2258:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
 2259:         push @{$self->{STACK}->[$newDepth]}, $here;
 2260:         $self->{CURRENT_DEPTH}--;
 2261:         return END_BRANCH();
 2262:     }
 2263:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
 2264:         push @{$self->{STACK}->[$newDepth]}, $here;
 2265:         $self->{CURRENT_DEPTH}++;
 2266:         return BEGIN_BRANCH();
 2267:     }
 2268: 
 2269:     # If we made it here, we have the next resource, and we're at the
 2270:     # right branch level. So let's examine the resource for where
 2271:     # we can get to from here.
 2272: 
 2273:     # So we need to look at all the resources we can get to from here,
 2274:     # categorize them if we haven't seen them, remember if we have a new
 2275:     my $nextUnfiltered = $here->getNext();
 2276:     my $maxDepthAdded = -1;
 2277:     
 2278:     for (@$nextUnfiltered) {
 2279:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 2280:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
 2281:             push @{$self->{STACK}->[$depth]}, $_;
 2282:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
 2283:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
 2284:         }
 2285:     }
 2286: 
 2287:     # Is this the end of a branch? If so, all of the resources examined above
 2288:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
 2289:     # marker onto the stack so we don't forget.
 2290:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
 2291:     # BC branch and gets to C, it will see F as the only next resource, but it's
 2292:     # one level lower. Thus, this is the end of the branch, since there are no
 2293:     # more resources added to this level or above.
 2294:     # We don't do this if the examined resource is the finish resource,
 2295:     # because the condition given above is true, but the "END_MAP" will
 2296:     # take care of things and we should already be at depth 0.
 2297:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
 2298:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
 2299:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
 2300:     }
 2301: 
 2302:     # That ends the main iterator logic. Now, do we want to recurse
 2303:     # down this map (if this resource is a map)?
 2304:     if ($self->{HERE}->is_map() &&
 2305:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
 2306:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 2307:         my $firstResource = $self->{HERE}->map_start();
 2308:         my $finishResource = $self->{HERE}->map_finish();
 2309: 
 2310:         $self->{RECURSIVE_ITERATOR} = 
 2311:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 2312:                                               $finishResource, $self->{FILTER},
 2313:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
 2314:     }
 2315: 
 2316:     # If this is a blank resource, don't actually return it.
 2317:     # Should you ever find you need it, make sure to add an option to the code
 2318:     #  that you can use; other things depend on this behavior.
 2319:     my $browsePriv = $self->{HERE}->browsePriv();
 2320:     if (!$self->{HERE}->src() || 
 2321:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
 2322:         return $self->next();
 2323:     }
 2324: 
 2325:     return $self->{HERE};
 2326: 
 2327: }
 2328: 
 2329: =pod
 2330: 
 2331: The other method available on the iterator is B<getStack>, which
 2332: returns an array populated with the current 'stack' of maps, as
 2333: references to the resource objects. Example: This is useful when
 2334: making the navigation map, as we need to check whether we are under a
 2335: page map to see if we need to link directly to the resource, or to the
 2336: page. The first elements in the array will correspond to the top of
 2337: the stack (most inclusive map).
 2338: 
 2339: =cut
 2340: 
 2341: sub getStack {
 2342:     my $self=shift;
 2343: 
 2344:     my @stack;
 2345: 
 2346:     $self->populateStack(\@stack);
 2347: 
 2348:     return \@stack;
 2349: }
 2350: 
 2351: # Private method: Calls the iterators recursively to populate the stack.
 2352: sub populateStack {
 2353:     my $self=shift;
 2354:     my $stack = shift;
 2355: 
 2356:     push @$stack, $self->{HERE} if ($self->{HERE});
 2357: 
 2358:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2359:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 2360:     }
 2361: }
 2362: 
 2363: 1;
 2364: 
 2365: package Apache::lonnavmaps::DFSiterator;
 2366: 
 2367: # Not documented in the perldoc: This is a simple iterator that just walks
 2368: #  through the nav map and presents the resources in a depth-first search
 2369: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
 2370: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
 2371: #  useful for pre-processing of some kind, and is in fact used by the main
 2372: #  iterator that way, but that's about it.
 2373: # One could imagine merging this into the init routine of the main iterator,
 2374: #  but this might as well be left seperate, since it is possible some other
 2375: #  use might be found for it. - Jeremy
 2376: 
 2377: # Unlike the main iterator, this DOES return all resources, even blank ones.
 2378: #  The main iterator needs them to correctly preprocess the map.
 2379: 
 2380: sub BEGIN_MAP { return 1; }    # begining of a new map
 2381: sub END_MAP { return 2; }      # end of the map
 2382: sub FORWARD { return 1; }      # go forward
 2383: sub BACKWARD { return 2; }
 2384: 
 2385: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
 2386: #         filter hash ref (or undef), already seen hash or undef, condition
 2387: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
 2388: sub new {
 2389:     # magic invocation to create a class instance
 2390:     my $proto = shift;
 2391:     my $class = ref($proto) || $proto;
 2392:     my $self = {};
 2393: 
 2394:     $self->{NAV_MAP} = shift;
 2395:     return undef unless ($self->{NAV_MAP});
 2396: 
 2397:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2398:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2399: 
 2400:     # If the given resources are just the ID of the resource, get the
 2401:     # objects
 2402:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2403:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2404:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2405:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2406: 
 2407:     $self->{FILTER} = shift;
 2408: 
 2409:     # A hash, used as a set, of resource already seen
 2410:     $self->{ALREADY_SEEN} = shift;
 2411:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2412:     $self->{CONDITION} = shift;
 2413:     $self->{DIRECTION} = shift || FORWARD();
 2414: 
 2415:     # Flag: Have we started yet?
 2416:     $self->{STARTED} = 0;
 2417: 
 2418:     # Should we continue calling the recursive iterator, if any?
 2419:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2420:     # The recursive iterator, if any
 2421:     $self->{RECURSIVE_ITERATOR} = undef;
 2422:     # Are we recursing on a map, or a branch?
 2423:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 2424:     # And the count of how deep it is, so that this iterator can keep track of
 2425:     # when to pick back up again.
 2426:     $self->{RECURSIVE_DEPTH} = 0;
 2427: 
 2428:     # For keeping track of our branches, we maintain our own stack
 2429:     $self->{STACK} = [];
 2430: 
 2431:     # Start with the first resource
 2432:     if ($self->{DIRECTION} == FORWARD) {
 2433:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
 2434:     } else {
 2435:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
 2436:     }
 2437: 
 2438:     bless($self);
 2439:     return $self;
 2440: }
 2441: 
 2442: sub next {
 2443:     my $self = shift;
 2444:     
 2445:     # Are we using a recursive iterator? If so, pull from that and
 2446:     # watch the depth; we want to resume our level at the correct time.
 2447:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2448:         # grab the next from the recursive iterator
 2449:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 2450:         
 2451:         # is it a begin or end map? Update depth if so
 2452:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 2453:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 2454: 
 2455:         # Are we back at depth 0? If so, stop recursing.
 2456:         if ($self->{RECURSIVE_DEPTH} == 0) {
 2457:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2458:         }
 2459:         
 2460:         return $next;
 2461:     }
 2462: 
 2463:     # Is there a current resource to grab? If not, then return
 2464:     # END_MAP, which will end the iterator.
 2465:     if (scalar(@{$self->{STACK}}) == 0) {
 2466:         return $self->END_MAP();
 2467:     }
 2468: 
 2469:     # Have we not yet begun? If not, return BEGIN_MAP and 
 2470:     # remember that we've started.
 2471:     if ( !$self->{STARTED} ) {
 2472:         $self->{STARTED} = 1;
 2473:         return $self->BEGIN_MAP;
 2474:     }
 2475: 
 2476:     # Get the next resource in the branch
 2477:     $self->{HERE} = pop @{$self->{STACK}};
 2478: 
 2479:     # remember that we've seen this, so we don't return it again later
 2480:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 2481:     
 2482:     # Get the next possible resources
 2483:     my $nextUnfiltered;
 2484:     if ($self->{DIRECTION} == FORWARD()) {
 2485:         $nextUnfiltered = $self->{HERE}->getNext();
 2486:     } else {
 2487:         $nextUnfiltered = $self->{HERE}->getPrevious();
 2488:     }
 2489:     my $next = [];
 2490: 
 2491:     # filter the next possibilities to remove things we've 
 2492:     # already seen.
 2493:     foreach (@$nextUnfiltered) {
 2494:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 2495:             push @$next, $_;
 2496:         }
 2497:     }
 2498: 
 2499:     while (@$next) {
 2500:         # copy the next possibilities over to the stack
 2501:         push @{$self->{STACK}}, shift @$next;
 2502:     }
 2503: 
 2504:     # If this is a map and we want to recurse down it... (not filtered out)
 2505:     if ($self->{HERE}->is_map() && 
 2506:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 2507:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 2508:         my $firstResource = $self->{HERE}->map_start();
 2509:         my $finishResource = $self->{HERE}->map_finish();
 2510: 
 2511:         $self->{RECURSIVE_ITERATOR} =
 2512:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
 2513:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 2514:                                              $self->{CONDITION}, $self->{DIRECTION});
 2515:     }
 2516: 
 2517:     return $self->{HERE};
 2518: }
 2519: 
 2520: 1;
 2521: 
 2522: package Apache::lonnavmaps::resource;
 2523: 
 2524: use Apache::lonnet;
 2525: 
 2526: =pod
 2527: 
 2528: =head1 Object: resource
 2529: 
 2530: A resource object encapsulates a resource in a resource map, allowing
 2531: easy manipulation of the resource, querying the properties of the
 2532: resource (including user properties), and represents a reference that
 2533: can be used as the canonical representation of the resource by
 2534: lonnavmap clients like renderers.
 2535: 
 2536: A resource only makes sense in the context of a navmap, as some of the
 2537: data is stored in the navmap object.
 2538: 
 2539: You will probably never need to instantiate this object directly. Use
 2540: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
 2541: starting resource.
 2542: 
 2543: =head2 Public Members
 2544: 
 2545: resource objects have a hash called DATA ($resourceRef->{DATA}) that
 2546: you can store whatever you want in. This allows you to easily do
 2547: two-pass algorithms without worrying about managing your own
 2548: resource->data hash.
 2549: 
 2550: =head2 Methods
 2551: 
 2552: =over 4
 2553: 
 2554: =item * B<new>($navmapRef, $idString):
 2555: 
 2556: The first arg is a reference to the parent navmap object. The second
 2557: is the idString of the resource itself. Very rarely, if ever, called
 2558: directly. Use the nav map->getByID() method.
 2559: 
 2560: =back
 2561: 
 2562: =cut
 2563: 
 2564: sub new {
 2565:     # magic invocation to create a class instance
 2566:     my $proto = shift;
 2567:     my $class = ref($proto) || $proto;
 2568:     my $self = {};
 2569: 
 2570:     $self->{NAV_MAP} = shift;
 2571:     $self->{ID} = shift;
 2572: 
 2573:     # Store this new resource in the parent nav map's cache.
 2574:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 2575:     $self->{RESOURCE_ERROR} = 0;
 2576: 
 2577:     # A hash that can be used by two-pass algorithms to store data
 2578:     # about this resource in. Not used by the resource object
 2579:     # directly.
 2580:     $self->{DATA} = {};
 2581:    
 2582:     bless($self);
 2583:     
 2584:     return $self;
 2585: }
 2586: 
 2587: # private function: simplify the NAV_HASH lookups we keep doing
 2588: # pass the name, and to automatically append my ID, pass a true val on the
 2589: # second param
 2590: sub navHash {
 2591:     my $self = shift;
 2592:     my $param = shift;
 2593:     my $id = shift;
 2594:     return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
 2595: }
 2596: 
 2597: =pod
 2598: 
 2599: B<Metadata Retreival>
 2600: 
 2601: These are methods that help you retrieve metadata about the resource:
 2602: Method names are based on the fields in the compiled course
 2603: representation.
 2604: 
 2605: =over 4
 2606: 
 2607: =item * B<compTitle>:
 2608: 
 2609: Returns a "composite title", that is equal to $res->title() if the
 2610: resource has a title, and is otherwise the last part of the URL (e.g.,
 2611: "problem.problem").
 2612: 
 2613: =item * B<ext>:
 2614: 
 2615: Returns true if the resource is external.
 2616: 
 2617: =item * B<goesto>:
 2618: 
 2619: Returns the "goesto" value from the compiled nav map. (It is likely
 2620: you want to use B<getNext> instead.)
 2621: 
 2622: =item * B<kind>:
 2623: 
 2624: Returns the kind of the resource from the compiled nav map.
 2625: 
 2626: =item * B<randomout>:
 2627: 
 2628: Returns true if this resource was chosen to NOT be shown to the user
 2629: by the random map selection feature. In other words, this is usually
 2630: false.
 2631: 
 2632: =item * B<randompick>:
 2633: 
 2634: Returns true for a map if the randompick feature is being used on the
 2635: map. (?)
 2636: 
 2637: =item * B<src>:
 2638: 
 2639: Returns the source for the resource.
 2640: 
 2641: =item * B<symb>:
 2642: 
 2643: Returns the symb for the resource.
 2644: 
 2645: =item * B<title>:
 2646: 
 2647: Returns the title of the resource.
 2648: 
 2649: =item * B<to>:
 2650: 
 2651: Returns the "to" value from the compiled nav map. (It is likely you
 2652: want to use B<getNext> instead.)
 2653: 
 2654: =back
 2655: 
 2656: =cut
 2657: 
 2658: # These info functions can be used directly, as they don't return
 2659: # resource information.
 2660: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
 2661: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 2662: sub from { my $self=shift; return $self->navHash("from_", 1); }
 2663: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 2664: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 2665: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 2666: sub randompick { 
 2667:     my $self = shift;
 2668:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
 2669:                                                '.0.parameter_randompick'};
 2670: }
 2671: sub src { 
 2672:     my $self=shift;
 2673:     return $self->navHash("src_", 1);
 2674: }
 2675: sub symb {
 2676:     my $self=shift;
 2677:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 2678:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 2679:     return &Apache::lonnet::declutter(
 2680:          $self->navHash('map_id_'.$first)) 
 2681:         . '___' . $second . '___' . $symbSrc;
 2682: }
 2683: sub title { my $self=shift; return $self->navHash("title_", 1); }
 2684: sub to { my $self=shift; return $self->navHash("to_", 1); }
 2685: sub compTitle {
 2686:     my $self = shift;
 2687:     my $title = $self->title();
 2688:     $title=~s/\&colon\;/\:/gs;
 2689:     if (!$title) {
 2690:         $title = $self->src();
 2691:         $title = substr($title, rindex($title, '/') + 1);
 2692:     }
 2693:     return $title;
 2694: }
 2695: =pod
 2696: 
 2697: B<Predicate Testing the Resource>
 2698: 
 2699: These methods are shortcuts to deciding if a given resource has a given property.
 2700: 
 2701: =over 4
 2702: 
 2703: =item * B<is_map>:
 2704: 
 2705: Returns true if the resource is a map type.
 2706: 
 2707: =item * B<is_problem>:
 2708: 
 2709: Returns true if the resource is a problem type, false
 2710: otherwise. (Looks at the extension on the src field; might need more
 2711: to work correctly.)
 2712: 
 2713: =item * B<is_page>:
 2714: 
 2715: Returns true if the resource is a page.
 2716: 
 2717: =item * B<is_sequence>:
 2718: 
 2719: Returns true if the resource is a sequence.
 2720: 
 2721: =back
 2722: 
 2723: =cut
 2724: 
 2725: 
 2726: sub is_html {
 2727:     my $self=shift;
 2728:     my $src = $self->src();
 2729:     return ($src =~ /html$/);
 2730: }
 2731: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 2732: sub is_page {
 2733:     my $self=shift;
 2734:     my $src = $self->src();
 2735:     return ($src =~ /page$/);
 2736: }
 2737: sub is_problem {
 2738:     my $self=shift;
 2739:     my $src = $self->src();
 2740:     return ($src =~ /problem$/);
 2741: }
 2742: sub is_sequence {
 2743:     my $self=shift;
 2744:     my $src = $self->src();
 2745:     return ($src =~ /sequence$/);
 2746: }
 2747: 
 2748: # Private method: Shells out to the parmval in the nav map, handler parts.
 2749: sub parmval {
 2750:     my $self = shift;
 2751:     my $what = shift;
 2752:     my $part = shift || "0";
 2753:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 2754: }
 2755: 
 2756: =pod
 2757: 
 2758: B<Map Methods>
 2759: 
 2760: These methods are useful for getting information about the map
 2761: properties of the resource, if the resource is a map (B<is_map>).
 2762: 
 2763: =over 4
 2764: 
 2765: =item * B<map_finish>:
 2766: 
 2767: Returns a reference to a resource object corresponding to the finish
 2768: resource of the map.
 2769: 
 2770: =item * B<map_pc>:
 2771: 
 2772: Returns the pc value of the map, which is the first number that
 2773: appears in the resource ID of the resources in the map, and is the
 2774: number that appears around the middle of the symbs of the resources in
 2775: that map.
 2776: 
 2777: =item * B<map_start>:
 2778: 
 2779: Returns a reference to a resource object corresponding to the start
 2780: resource of the map.
 2781: 
 2782: =item * B<map_type>:
 2783: 
 2784: Returns a string with the type of the map in it.
 2785: 
 2786: =back
 2787: 
 2788: =cut
 2789: 
 2790: sub map_finish {
 2791:     my $self = shift;
 2792:     my $src = $self->src();
 2793:     $src = Apache::lonnet::clutter($src);
 2794:     my $res = $self->navHash("map_finish_$src", 0);
 2795:     $res = $self->{NAV_MAP}->getById($res);
 2796:     return $res;
 2797: }
 2798: sub map_pc {
 2799:     my $self = shift;
 2800:     my $src = $self->src();
 2801:     return $self->navHash("map_pc_$src", 0);
 2802: }
 2803: sub map_start {
 2804:     my $self = shift;
 2805:     my $src = $self->src();
 2806:     $src = Apache::lonnet::clutter($src);
 2807:     my $res = $self->navHash("map_start_$src", 0);
 2808:     $res = $self->{NAV_MAP}->getById($res);
 2809:     return $res;
 2810: }
 2811: sub map_type {
 2812:     my $self = shift;
 2813:     my $pc = $self->map_pc();
 2814:     return $self->navHash("map_type_$pc", 0);
 2815: }
 2816: 
 2817: 
 2818: 
 2819: #####
 2820: # Property queries
 2821: #####
 2822: 
 2823: # These functions will be responsible for returning the CORRECT
 2824: # VALUE for the parameter, no matter what. So while they may look
 2825: # like direct calls to parmval, they can be more then that.
 2826: # So, for instance, the duedate function should use the "duedatetype"
 2827: # information, rather then the resource object user.
 2828: 
 2829: =pod
 2830: 
 2831: =head2 Resource Parameters
 2832: 
 2833: In order to use the resource parameters correctly, the nav map must
 2834: have been instantiated with genCourseAndUserOptions set to true, so
 2835: the courseopt and useropt is read correctly. Then, you can call these
 2836: functions to get the relevant parameters for the resource. Each
 2837: function defaults to part "0", but can be directed to another part by
 2838: passing the part as the parameter.
 2839: 
 2840: These methods are responsible for getting the parameter correct, not
 2841: merely reflecting the contents of the GDBM hashes. As we move towards
 2842: dates relative to other dates, these methods should be updated to
 2843: reflect that. (Then, anybody using these methods will not have to update
 2844: their code.)
 2845: 
 2846: =over 4
 2847: 
 2848: =item * B<acc>:
 2849: 
 2850: Get the Client IP/Name Access Control information.
 2851: 
 2852: =item * B<answerdate>:
 2853: 
 2854: Get the answer-reveal date for the problem.
 2855: 
 2856: =item * B<duedate>:
 2857: 
 2858: Get the due date for the problem.
 2859: 
 2860: =item * B<tries>:
 2861: 
 2862: Get the number of tries the student has used on the problem.
 2863: 
 2864: =item * B<maxtries>:
 2865: 
 2866: Get the number of max tries allowed.
 2867: 
 2868: =item * B<opendate>:
 2869: 
 2870: Get the open date for the problem.
 2871: 
 2872: =item * B<sig>:
 2873: 
 2874: Get the significant figures setting.
 2875: 
 2876: =item * B<tol>:
 2877: 
 2878: Get the tolerance for the problem.
 2879: 
 2880: =item * B<tries>:
 2881: 
 2882: Get the number of tries the user has already used on the problem.
 2883: 
 2884: =item * B<type>:
 2885: 
 2886: Get the question type for the problem.
 2887: 
 2888: =item * B<weight>:
 2889: 
 2890: Get the weight for the problem.
 2891: 
 2892: =back
 2893: 
 2894: =cut
 2895: 
 2896: sub acc {
 2897:     (my $self, my $part) = @_;
 2898:     return $self->parmval("acc", $part);
 2899: }
 2900: sub answerdate {
 2901:     (my $self, my $part) = @_;
 2902:     # Handle intervals
 2903:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 2904:         return $self->duedate($part) + 
 2905:             $self->parmval("answerdate", $part);
 2906:     }
 2907:     return $self->parmval("answerdate", $part);
 2908: }
 2909: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
 2910: sub duedate {
 2911:     (my $self, my $part) = @_;
 2912:     return $self->parmval("duedate", $part);
 2913: }
 2914: sub maxtries {
 2915:     (my $self, my $part) = @_;
 2916:     return $self->parmval("maxtries", $part);
 2917: }
 2918: sub opendate {
 2919:     (my $self, my $part) = @_;
 2920:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 2921:         return $self->duedate($part) -
 2922:             $self->parmval("opendate", $part);
 2923:     }
 2924:     return $self->parmval("opendate");
 2925: }
 2926: sub sig {
 2927:     (my $self, my $part) = @_;
 2928:     return $self->parmval("sig", $part);
 2929: }
 2930: sub tol {
 2931:     (my $self, my $part) = @_;
 2932:     return $self->parmval("tol", $part);
 2933: }
 2934: sub tries { 
 2935:     my $self = shift; 
 2936:     my $tries = $self->queryRestoreHash('tries', shift);
 2937:     if (!defined($tries)) { return '0';}
 2938:     return $tries;
 2939: }
 2940: sub type {
 2941:     (my $self, my $part) = @_;
 2942:     return $self->parmval("type", $part);
 2943: }
 2944: sub weight { 
 2945:     my $self = shift; my $part = shift;
 2946:     return $self->parmval("weight", $part);
 2947: }
 2948: 
 2949: # Multiple things need this
 2950: sub getReturnHash {
 2951:     my $self = shift;
 2952:     
 2953:     if (!defined($self->{RETURN_HASH})) {
 2954:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
 2955:         $self->{RETURN_HASH} = \%tmpHash;
 2956:     }
 2957: }       
 2958: 
 2959: ######
 2960: # Status queries
 2961: ######
 2962: 
 2963: # These methods query the status of problems.
 2964: 
 2965: # If we need to count parts, this function determines the number of
 2966: # parts from the metadata. When called, it returns a reference to a list
 2967: # of strings corresponding to the parts. (Thus, using it in a scalar context
 2968: # tells you how many parts you have in the problem:
 2969: # $partcount = scalar($resource->countParts());
 2970: # Don't use $self->{PARTS} directly because you don't know if it's been
 2971: # computed yet.
 2972: 
 2973: =pod
 2974: 
 2975: =head2 Resource misc
 2976: 
 2977: Misc. functions for the resource.
 2978: 
 2979: =over 4
 2980: 
 2981: =item * B<hasDiscussion>:
 2982: 
 2983: Returns a false value if there has been discussion since the user last
 2984: logged in, true if there has. Always returns false if the discussion
 2985: data was not extracted when the nav map was constructed.
 2986: 
 2987: =item * B<getFeedback>:
 2988: 
 2989: Gets the feedback for the resource and returns the raw feedback string
 2990: for the resource, or the null string if there is no feedback or the
 2991: email data was not extracted when the nav map was constructed. Usually
 2992: used like this:
 2993: 
 2994:  for (split(/\,/, $res->getFeedback())) {
 2995:     my $link = &Apache::lonnet::escape($_);
 2996:     ...
 2997: 
 2998: and use the link as appropriate.
 2999: 
 3000: =cut
 3001: 
 3002: sub hasDiscussion {
 3003:     my $self = shift;
 3004:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 3005: }
 3006: 
 3007: sub getFeedback {
 3008:     my $self = shift;
 3009:     my $source = $self->src();
 3010:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 3011:     return $self->{NAV_MAP}->getFeedback($source);
 3012: }
 3013: 
 3014: sub getErrors {
 3015:     my $self = shift;
 3016:     my $source = $self->src();
 3017:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 3018:     return $self->{NAV_MAP}->getErrors($source);
 3019: }
 3020: 
 3021: =pod
 3022: 
 3023: =item * B<parts>():
 3024: 
 3025: Returns a list reference containing sorted strings corresponding to
 3026: each part of the problem. To count the number of parts, use the list
 3027: in a scalar context, and subtract one if greater than two. (One part
 3028: problems have a part 0. Multi-parts have a part 0, plus a part for
 3029: each part. Filtering part 0 if you want it is up to you.)
 3030: 
 3031: =item * B<countParts>():
 3032: 
 3033: Returns the number of parts of the problem a student can answer. Thus,
 3034: for single part problems, returns 1. For multipart, it returns the
 3035: number of parts in the problem, not including psuedo-part 0. Thus,
 3036: B<parts> may return an array with fewer parts in it then countParts
 3037: might lead you to believe.
 3038: 
 3039: =back
 3040: 
 3041: =cut
 3042: 
 3043: sub parts {
 3044:     my $self = shift;
 3045: 
 3046:     if ($self->ext) { return ['0']; }
 3047: 
 3048:     $self->extractParts();
 3049:     return $self->{PARTS};
 3050: }
 3051: 
 3052: sub countParts {
 3053:     my $self = shift;
 3054:     
 3055:     my $parts = $self->parts();
 3056:     my $delta = 0;
 3057:     for my $part (@$parts) {
 3058:         if ($part eq '0') { $delta--; }
 3059:     }
 3060: 
 3061:     if ($self->{RESOURCE_ERROR}) {
 3062:         return 0;
 3063:     }
 3064: 
 3065:     return scalar(@{$parts}) + $delta;
 3066: }
 3067: 
 3068: # Private function: Extracts the parts information and saves it
 3069: sub extractParts { 
 3070:     my $self = shift;
 3071:     
 3072:     return if (defined($self->{PARTS}));
 3073:     return if ($self->ext);
 3074: 
 3075:     $self->{PARTS} = [];
 3076: 
 3077:     # Retrieve part count, if this is a problem
 3078:     if ($self->is_problem()) {
 3079:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
 3080:         if (!$metadata) {
 3081:             $self->{RESOURCE_ERROR} = 1;
 3082:             $self->{PARTS} = [];
 3083:             return;
 3084:         }
 3085:         foreach (split(/\,/,$metadata)) {
 3086:             if ($_ =~ /^part_(.*)$/) {
 3087:                 my $part = $1;
 3088:                 # check to see if part is turned off.
 3089:                 if (! Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
 3090:                     push @{$self->{PARTS}}, $1;
 3091:                 }
 3092:             }
 3093:         }
 3094:         
 3095:         
 3096:         my @sortedParts = sort @{$self->{PARTS}};
 3097:         $self->{PARTS} = \@sortedParts;
 3098:     }
 3099: 
 3100:     return;
 3101: }
 3102: 
 3103: =pod
 3104: 
 3105: =head2 Resource Status
 3106: 
 3107: Problem resources have status information, reflecting their various
 3108: dates and completion statuses.
 3109: 
 3110: There are two aspects to the status: the date-related information and
 3111: the completion information.
 3112: 
 3113: Idiomatic usage of these two methods would probably look something
 3114: like
 3115: 
 3116:  foreach ($resource->parts()) {
 3117:     my $dateStatus = $resource->getDateStatus($_);
 3118:     my $completionStatus = $resource->getCompletionStatus($_);
 3119: 
 3120:     or
 3121: 
 3122:     my $status = $resource->status($_);
 3123: 
 3124:     ... use it here ...
 3125:  }
 3126: 
 3127: Which you use depends on exactly what you are looking for. The
 3128: status() function has been optimized for the nav maps display and may
 3129: not precisely match what you need elsewhere.
 3130: 
 3131: The symbolic constants shown below can be accessed through the
 3132: resource object: C<$res->OPEN>.
 3133: 
 3134: =over 4
 3135: 
 3136: =item * B<getDateStatus>($part):
 3137: 
 3138: ($part defaults to 0). A convenience function that returns a symbolic
 3139: constant telling you about the date status of the part. The possible
 3140: return values are:
 3141: 
 3142: =back
 3143: 
 3144: B<Date Codes>
 3145: 
 3146: =over 4
 3147: 
 3148: =item * B<OPEN_LATER>:
 3149: 
 3150: The problem will be opened later.
 3151: 
 3152: =item * B<OPEN>:
 3153: 
 3154: Open and not yet due.
 3155: 
 3156: 
 3157: =item * B<PAST_DUE_ANSWER_LATER>:
 3158: 
 3159: The due date has passed, but the answer date has not yet arrived.
 3160: 
 3161: =item * B<PAST_DUE_NO_ANSWER>:
 3162: 
 3163: The due date has passed and there is no answer opening date set.
 3164: 
 3165: =item * B<ANSWER_OPEN>:
 3166: 
 3167: The answer date is here.
 3168: 
 3169: =item * B<NETWORK_FAILURE>:
 3170: 
 3171: The information is unknown due to network failure.
 3172: 
 3173: =back
 3174: 
 3175: =cut
 3176: 
 3177: # Apparently the compiler optimizes these into constants automatically
 3178: sub OPEN_LATER             { return 0; }
 3179: sub OPEN                   { return 1; }
 3180: sub PAST_DUE_NO_ANSWER     { return 2; }
 3181: sub PAST_DUE_ANSWER_LATER  { return 3; }
 3182: sub ANSWER_OPEN            { return 4; }
 3183: sub NOTHING_SET            { return 5; } 
 3184: sub NETWORK_FAILURE        { return 100; }
 3185: 
 3186: # getDateStatus gets the date status for a given problem part. 
 3187: # Because answer date, due date, and open date are fully independent
 3188: # (i.e., it is perfectly possible to *only* have an answer date), 
 3189: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 3190: # (past, future, none given). This function handles this with a decision
 3191: # tree. Read the comments to follow the decision tree.
 3192: 
 3193: sub getDateStatus {
 3194:     my $self = shift;
 3195:     my $part = shift;
 3196:     $part = "0" if (!defined($part));
 3197: 
 3198:     # Always return network failure if there was one.
 3199:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3200: 
 3201:     my $now = time();
 3202: 
 3203:     my $open = $self->opendate($part);
 3204:     my $due = $self->duedate($part);
 3205:     my $answer = $self->answerdate($part);
 3206: 
 3207:     if (!$open && !$due && !$answer) {
 3208:         # no data on the problem at all
 3209:         # should this be the same as "open later"? think multipart.
 3210:         return $self->NOTHING_SET;
 3211:     }
 3212:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 3213:     if (!$due || $now < $due) {return $self->OPEN}
 3214:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 3215:     if ($answer) { return $self->ANSWER_OPEN; }
 3216:     return PAST_DUE_NO_ANSWER;
 3217: }
 3218: 
 3219: =pod
 3220: 
 3221: B<>
 3222: 
 3223: =over 4
 3224: 
 3225: =item * B<getCompletionStatus>($part):
 3226: 
 3227: ($part defaults to 0.) A convenience function that returns a symbolic
 3228: constant telling you about the completion status of the part, with the
 3229: following possible results:
 3230: 
 3231: =back
 3232: 
 3233: B<Completion Codes>
 3234: 
 3235: =over 4
 3236: 
 3237: =item * B<NOT_ATTEMPTED>:
 3238: 
 3239: Has not been attempted at all.
 3240: 
 3241: =item * B<INCORRECT>:
 3242: 
 3243: Attempted, but wrong by student.
 3244: 
 3245: =item * B<INCORRECT_BY_OVERRIDE>:
 3246: 
 3247: Attempted, but wrong by instructor override.
 3248: 
 3249: =item * B<CORRECT>:
 3250: 
 3251: Correct or correct by instructor.
 3252: 
 3253: =item * B<CORRECT_BY_OVERRIDE>:
 3254: 
 3255: Correct by instructor override.
 3256: 
 3257: =item * B<EXCUSED>:
 3258: 
 3259: Excused. Not yet implemented.
 3260: 
 3261: =item * B<NETWORK_FAILURE>:
 3262: 
 3263: Information not available due to network failure.
 3264: 
 3265: =item * B<ATTEMPTED>:
 3266: 
 3267: Attempted, and not yet graded.
 3268: 
 3269: =back
 3270: 
 3271: =cut
 3272: 
 3273: sub NOT_ATTEMPTED         { return 10; }
 3274: sub INCORRECT             { return 11; }
 3275: sub INCORRECT_BY_OVERRIDE { return 12; }
 3276: sub CORRECT               { return 13; }
 3277: sub CORRECT_BY_OVERRIDE   { return 14; }
 3278: sub EXCUSED               { return 15; }
 3279: sub ATTEMPTED             { return 16; }
 3280: 
 3281: sub getCompletionStatus {
 3282:     my $self = shift;
 3283:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3284: 
 3285:     my $status = $self->queryRestoreHash('solved', shift);
 3286: 
 3287:     # Left as seperate if statements in case we ever do more with this
 3288:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 3289:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 3290:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 3291:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 3292:     if ($status eq 'excused') {return $self->EXCUSED; }
 3293:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 3294:     return $self->NOT_ATTEMPTED;
 3295: }
 3296: 
 3297: sub queryRestoreHash {
 3298:     my $self = shift;
 3299:     my $hashentry = shift;
 3300:     my $part = shift;
 3301:     $part = "0" if (!defined($part));
 3302:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3303: 
 3304:     $self->getReturnHash();
 3305: 
 3306:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
 3307: }
 3308: 
 3309: =pod
 3310: 
 3311: B<Composite Status>
 3312: 
 3313: Along with directly returning the date or completion status, the
 3314: resource object includes a convenience function B<status>() that will
 3315: combine the two status tidbits into one composite status that can
 3316: represent the status of the resource as a whole. The precise logic is
 3317: documented in the comments of the status method. The following results
 3318: may be returned, all available as methods on the resource object
 3319: ($res->NETWORK_FAILURE):
 3320: 
 3321: =over 4
 3322: 
 3323: =item * B<NETWORK_FAILURE>:
 3324: 
 3325: The network has failed and the information is not available.
 3326: 
 3327: =item * B<NOTHING_SET>:
 3328: 
 3329: No dates have been set for this problem (part) at all. (Because only
 3330: certain parts of a multi-part problem may be assigned, this can not be
 3331: collapsed into "open later", as we do not know a given part will EVER
 3332: be opened. For single part, this is the same as "OPEN_LATER".)
 3333: 
 3334: =item * B<CORRECT>:
 3335: 
 3336: For any reason at all, the part is considered correct.
 3337: 
 3338: =item * B<EXCUSED>:
 3339: 
 3340: For any reason at all, the problem is excused.
 3341: 
 3342: =item * B<PAST_DUE_NO_ANSWER>:
 3343: 
 3344: The problem is past due, not considered correct, and no answer date is
 3345: set.
 3346: 
 3347: =item * B<PAST_DUE_ANSWER_LATER>:
 3348: 
 3349: The problem is past due, not considered correct, and an answer date in
 3350: the future is set.
 3351: 
 3352: =item * B<ANSWER_OPEN>:
 3353: 
 3354: The problem is past due, not correct, and the answer is now available.
 3355: 
 3356: =item * B<OPEN_LATER>:
 3357: 
 3358: The problem is not yet open.
 3359: 
 3360: =item * B<TRIES_LEFT>:
 3361: 
 3362: The problem is open, has been tried, is not correct, but there are
 3363: tries left.
 3364: 
 3365: =item * B<INCORRECT>:
 3366: 
 3367: The problem is open, and all tries have been used without getting the
 3368: correct answer.
 3369: 
 3370: =item * B<OPEN>:
 3371: 
 3372: The item is open and not yet tried.
 3373: 
 3374: =item * B<ATTEMPTED>:
 3375: 
 3376: The problem has been attempted.
 3377: 
 3378: =back
 3379: 
 3380: =cut
 3381: 
 3382: sub TRIES_LEFT { return 10; }
 3383: 
 3384: sub status {
 3385:     my $self = shift;
 3386:     my $part = shift;
 3387:     if (!defined($part)) { $part = "0"; }
 3388:     my $completionStatus = $self->getCompletionStatus($part);
 3389:     my $dateStatus = $self->getDateStatus($part);
 3390: 
 3391:     # What we have is a two-dimensional matrix with 4 entries on one
 3392:     # dimension and 5 entries on the other, which we want to colorize,
 3393:     # plus network failure and "no date data at all".
 3394: 
 3395:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 3396: 
 3397:     # There are a few whole rows we can dispose of:
 3398:     if ($completionStatus == CORRECT ||
 3399:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 3400:         return CORRECT; 
 3401:     }
 3402: 
 3403:     if ($completionStatus == ATTEMPTED) {
 3404:         return ATTEMPTED;
 3405:     }
 3406: 
 3407:     # If it's EXCUSED, then return that no matter what
 3408:     if ($completionStatus == EXCUSED) {
 3409:         return EXCUSED; 
 3410:     }
 3411: 
 3412:     if ($dateStatus == NOTHING_SET) {
 3413:         return NOTHING_SET;
 3414:     }
 3415: 
 3416:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 3417:     # by 4 matrix (date statuses).
 3418: 
 3419:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 3420:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 3421:         return $dateStatus; 
 3422:     }
 3423: 
 3424:     if ($dateStatus == ANSWER_OPEN) {
 3425:         return ANSWER_OPEN;
 3426:     }
 3427: 
 3428:     # Now: (incorrect, incorrect_override, not_attempted) x 
 3429:     # (open_later), (open)
 3430:     
 3431:     if ($dateStatus == OPEN_LATER) {
 3432:         return OPEN_LATER;
 3433:     }
 3434: 
 3435:     # If it's WRONG...
 3436:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 3437:         # and there are TRIES LEFT:
 3438:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 3439:             return TRIES_LEFT;
 3440:         }
 3441:         return INCORRECT; # otherwise, return orange; student can't fix this
 3442:     }
 3443: 
 3444:     # Otherwise, it's untried and open
 3445:     return OPEN; 
 3446: }
 3447: 
 3448: =pod
 3449: 
 3450: =head2 Resource/Nav Map Navigation
 3451: 
 3452: =over 4
 3453: 
 3454: =item * B<getNext>():
 3455: 
 3456: Retreive an array of the possible next resources after this
 3457: one. Always returns an array, even in the one- or zero-element case.
 3458: 
 3459: =item * B<getPrevious>():
 3460: 
 3461: Retreive an array of the possible previous resources from this
 3462: one. Always returns an array, even in the one- or zero-element case.
 3463: 
 3464: =cut
 3465: 
 3466: sub getNext {
 3467:     my $self = shift;
 3468:     my @branches;
 3469:     my $to = $self->to();
 3470:     foreach my $branch ( split(/,/, $to) ) {
 3471:         my $choice = $self->{NAV_MAP}->getById($branch);
 3472:         my $next = $choice->goesto();
 3473:         $next = $self->{NAV_MAP}->getById($next);
 3474: 
 3475:         push @branches, $next;
 3476:     }
 3477:     return \@branches;
 3478: }
 3479: 
 3480: sub getPrevious {
 3481:     my $self = shift;
 3482:     my @branches;
 3483:     my $from = $self->from();
 3484:     foreach my $branch ( split /,/, $from) {
 3485:         my $choice = $self->{NAV_MAP}->getById($branch);
 3486:         my $prev = $choice->comesfrom();
 3487:         $prev = $self->{NAV_MAP}->getById($prev);
 3488: 
 3489:         push @branches, $prev;
 3490:     }
 3491:     return \@branches;
 3492: }
 3493: 
 3494: sub browsePriv {
 3495:     my $self = shift;
 3496:     if (defined($self->{BROWSE_PRIV})) {
 3497:         return $self->{BROWSE_PRIV};
 3498:     }
 3499: 
 3500:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
 3501: }
 3502: 
 3503: =pod
 3504: 
 3505: =back
 3506: 
 3507: =cut
 3508: 
 3509: 1;
 3510: 
 3511: __END__
 3512: 
 3513: 

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