File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.466: download - view: text, annotated - select for diffs
Mon Nov 7 20:05:56 2011 UTC (12 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Trying to get rid of some of the copy/paste regular expressions.

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

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