File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.444.2.2: download - view: text, annotated - select for diffs
Sun Aug 15 00:03:25 2010 UTC (13 years, 9 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC1
- Backport 1.448, 1.449, 1.450.

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

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