File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.474: download - view: text, annotated - select for diffs
Wed Dec 21 16:53:03 2011 UTC (12 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Wording change for reservable slots.
- Delay determination of proctors until needed.
- Iteration direction for ordered arrays of slots with reservations was the
  wrong way round.
  - currently reservable - find reservable slot with latest closing time for
    reservation window.
  - reservable inf future - find reservable slot with earliest opeing time for
    reservation window.

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

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