File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.476: download - view: text, annotated - select for diffs
Sun Dec 25 19:39:08 2011 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Tags for table used to construct "Tools:" menu moved to
  &show_linkitems_toolbar() routine.

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

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