File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.444: download - view: text, annotated - select for diffs
Sun Feb 28 22:36:38 2010 UTC (14 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_X, HEAD
- Bug 6119. New method: is_anonsurvey() reports if part has type anonsurvey
  or anonsurvey_cred.
  Method is_survey() will report if part is type survey or type surveycred.
   - anonsurvey -- course personnel can not view both identity of submitter
                   and submission details.
   - anonsurveycred -- same anonymity, but submitter receives 'awarded' for
                       submission
   -surveycred - submitter receives 'awarded' for submission to survey.
   - survey    - standard survey functionality

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

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