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

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

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