Annotation of loncom/interface/lonnavmaps.pm, revision 1.471

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

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