File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.470: download - view: text, annotated - select for diffs
Tue Nov 29 11:58:53 2011 UTC (12 years, 5 months ago) by foxr
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
BZ 6454 - Correctly handle attempt to get navmap for a user other than
          the current one by using lonmap to read the map in that case
          rather than binding to a map file.

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

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