File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.506: download - view: text, annotated - select for diffs
Mon Apr 13 16:46:43 2015 UTC (9 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Fix typos in rev. 1.505.

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

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