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

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

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