File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.577: download - view: text, annotated - select for diffs
Sat Jun 28 17:34:00 2025 UTC (2 days, 13 hours ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6623.

    1: # The LearningOnline Network with CAPA
    2: # Navigate Maps Handler
    3: #
    4: # $Id: lonnavmaps.pm,v 1.577 2025/06/28 17:34:00 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnavmaps - Subroutines to handle and render the navigation
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: Handles navigational maps.
   39: 
   40: The main handler generates the navigational listing for the course,
   41: the other objects export this information in a usable fashion for
   42: other modules.
   43: 
   44: 
   45: This is part of the LearningOnline Network with CAPA project
   46: described at http://www.lon-capa.org.
   47: 
   48: 
   49: =head1 OVERVIEW
   50: 
   51: X<lonnavmaps, overview>
   52: When a user enters a course, LON-CAPA examines the
   53: course structure and caches it in what is often referred to as the
   54: "big hash" X<big hash>. You can see it if you are logged into
   55: LON-CAPA, in a course, by going to /adm/test. The content of 
   56: the hash will be under the heading "Big Hash".
   57: 
   58: Access to /adm/test is controlled by a domain configuration, 
   59: which a Domain Coordinator will set for a server's default domain
   60: via: Main Menu > Set domain configuration > Display (Access to 
   61: server status pages checked), and entering a username:domain
   62: or IP address in the "Show user environment" row. Users with
   63: an unexpired domain coordinator role in the server's domain
   64: automatically receive access to /adm/test.
   65: 
   66: Big Hash contains, among other things, how resources are related
   67: to each other (next/previous), what resources are maps, which 
   68: resources are being chosen to not show to the student (for random
   69: selection), and a lot of other things that can take a lot of time
   70: to compute due to the amount of data that needs to be collected and
   71: processed.
   72: 
   73: Apache::lonnavmaps provides an object model for manipulating this
   74: information in a higher-level fashion than directly manipulating 
   75: the hash. It also provides access to several auxiliary functions 
   76: that aren't necessarily stored in the Big Hash, but are a per-
   77: resource sort of value, like whether there is any feedback on 
   78: a given resource.
   79: 
   80: Apache::lonnavmaps also abstracts away branching, and someday, 
   81: conditions, for the times where you don't really care about those
   82: things.
   83: 
   84: Apache::lonnavmaps also provides fairly powerful routines for
   85: rendering navmaps, and last but not least, provides the navmaps
   86: view for when the user clicks the NAV button.
   87: 
   88: B<Note>: Apache::lonnavmaps by default will show information 
   89: for the "currently logged in user".  However, if information
   90: about resources is needed for a different user, e.g., a bubblesheet
   91: exam which uses randomorder, or randompick needs to be printed or 
   92: graded for named user(s) or specific CODEs, then the username,
   93: domain, or CODE can be passed as arguments when creating a new 
   94: navmap object.
   95: 
   96: Note if you want things like "due dates for another student",
   97: you would use the EXT function instead of lonnavmaps.
   98: That said, the lonnavmaps module can still help, because many
   99: things, such as the course structure, are usually constant
  100: between users, and Apache::lonnavmaps can help by providing
  101: symbs for the EXT call.
  102: 
  103: The rest of this file will cover the provided rendering routines, 
  104: which can often be used without fiddling with the navmap object at
  105: all, then documents the Apache::lonnavmaps::navmap object, which
  106: is the key to accessing the Big Hash information, covers the use
  107: of the Iterator (which provides the logic for traversing the 
  108: somewhat-complicated Big Hash data structure), documents the
  109: Apache::lonnavmaps::Resource objects that are returned singularly
  110: by: getBySymb(), getById(), getByMapPc(), and getResourceByUrl()
  111: (can also be as an array), or in an array by retrieveResources().
  112: 
  113: =head1 Subroutine: render
  114: 
  115: The navmap renderer package provides a sophisticated rendering of the
  116: standard navigation maps interface into HTML. The provided nav map
  117: handler is actually just a glorified call to this.
  118: 
  119: Because of the large number of parameters this function accepts,
  120: instead of passing it arguments as is normal, pass it in an anonymous
  121: hash with the desired options.
  122: 
  123: The package provides a function called 'render', called as
  124: Apache::lonnavmaps::render({}).
  125: 
  126: =head2 Overview of Columns
  127: 
  128: The renderer will build an HTML table for the navmap and return
  129: it. The table consists of several columns, and a row for each
  130: resource (or possibly each part). You tell the renderer how many
  131: columns to create and what to place in each column, optionally using
  132: one or more of the prepared columns, and the renderer will assemble
  133: the table.
  134: 
  135: Any additional generally useful column types should be placed in the
  136: renderer code here, so anybody can use it anywhere else. Any code
  137: specific to the current application (such as the addition of <input>
  138: elements in a column) should be placed in the code of the thing using
  139: the renderer.
  140: 
  141: At the core of the renderer is the array reference COLS (see Example
  142: section below for how to pass this correctly). The COLS array will
  143: consist of entries of one of two types of things: Either an integer
  144: representing one of the pre-packaged column types, or a sub reference
  145: that takes a resource reference, a part number, and a reference to the
  146: argument hash passed to the renderer, and returns a string that will
  147: be inserted into the HTML representation as it.
  148: 
  149: All other parameters are ways of either changing how the columns
  150: are printing, or which rows are shown.
  151: 
  152: The pre-packaged column names are refered to by constants in the
  153: Apache::lonnavmaps namespace. The following currently exist:
  154: 
  155: =over 4
  156: 
  157: =item * B<Apache::lonnavmaps::resource>:
  158: 
  159: The general info about the resource: Link, icon for the type, etc. The
  160: first column in the standard nav map display. This column provides the
  161: indentation effect seen in the B<NAV> screen. This column also accepts
  162: the following parameters in the renderer hash:
  163: 
  164: =over 4
  165: 
  166: =item * B<resource_nolink>: default false
  167: 
  168: If true, the resource will not be linked. By default, all non-folder
  169: resources are linked.
  170: 
  171: =item * B<resource_part_count>: default true
  172: 
  173: If true, the resource will show a part count B<if> the full
  174: part list is not displayed. (See "condense_parts" later.) If false,
  175: the resource will never show a part count.
  176: 
  177: =item * B<resource_no_folder_link>:
  178: 
  179: If true, the resource's folder will not be clickable to open or close
  180: it. Default is false. True implies printCloseAll is false, since you
  181: can't close or open folders when this is on anyhow.
  182: 
  183: =item * B<map_no_edit_link>:
  184: 
  185: If true, the title of the folder or page will not be followed by an
  186: icon/link to direct editing of a folder or composite page, originally
  187: added via the Course Editor.
  188: 
  189: =back
  190: 
  191: =item * B<Apache::lonnavmaps::communication_status>:
  192: 
  193: Whether there is discussion on the resource, email for the user, or
  194: (lumped in here) perl errors in the execution of the problem. This is
  195: the second column in the main nav map.
  196: 
  197: =item * B<Apache::lonnavmaps::quick_status>:
  198: 
  199: An icon for the status of a problem, with five possible states:
  200: Correct, incorrect, open, awaiting grading (for a problem where the
  201: computer's grade is suppressed, or the computer can't grade, like
  202: essay problem), or none (not open yet, not a problem). The
  203: third column of the standard navmap.
  204: 
  205: =item * B<Apache::lonnavmaps::long_status>:
  206: 
  207: A text readout of the details of the current status of the problem,
  208: such as "Due in 22 hours". The fourth column of the standard navmap.
  209: 
  210: =item * B<Apache::lonnavmaps::part_status_summary>:
  211: 
  212: A text readout summarizing the status of the problem. If it is a
  213: single part problem, will display "Correct", "Incorrect", 
  214: "Not yet open", "Open", "Attempted", or "Error". If there are
  215: multiple parts, this will output a string that in HTML will show a
  216: status of how many parts are in each status, in color coding, trying
  217: to match the colors of the icons within reason.
  218: 
  219: Note this only makes sense if you are I<not> showing parts. If 
  220: C<showParts> is true (see below), this column will not output
  221: anything. 
  222: 
  223: =back
  224: 
  225: If you add any others please be sure to document them here.
  226: 
  227: An example of a column renderer that will show the ID number of a
  228: resource, along with the part name if any:
  229: 
  230:  sub { 
  231:   my ($resource, $part, $params) = @_;   
  232:   if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
  233:   return '<td>' . $resource->{ID} . '</td>';
  234:  }
  235: 
  236: Note these functions are responsible for the TD tags, which allow them
  237: to override vertical and horizontal alignment, etc.
  238: 
  239: =head2 Parameters
  240: 
  241: Minimally, you should be
  242: able to get away with just using 'cols' (to specify the columns
  243: shown), 'url' (necessary for the folders to link to the current screen
  244: correctly), and possibly 'queryString' if your app calls for it. In
  245: that case, maintaining the state of the folders will be done
  246: automatically.
  247: 
  248: =over 4
  249: 
  250: =item * B<iterator>: default: constructs one from %env
  251: 
  252: A reference to a fresh ::iterator to use from the navmaps. The
  253: rendering will reflect the options passed to the iterator, so you can
  254: use that to just render a certain part of the course, if you like. If
  255: one is not passed, the renderer will attempt to construct one from
  256: env{'form.filter'} and env{'form.condition'} information, plus the
  257: 'iterator_map' parameter if any.
  258: 
  259: =item * B<iterator_map>: default: not used
  260: 
  261: If you are letting the renderer do the iterator handling, you can
  262: instruct the renderer to render only a particular map by passing it
  263: the source of the map you want to process, like
  264: '/res/103/jerf/navmap.course.sequence'.
  265: 
  266: =item * B<include_top_level_map>: default: false
  267: 
  268: If you need to include the top level map (meaning the course) in the
  269: rendered output set this to true
  270: 
  271: =item * B<navmap>: default: constructs one from %env
  272: 
  273: A reference to a navmap, used only if an iterator is not passed in. If
  274: this is necessary to make an iterator but it is not passed in, a new
  275: one will be constructed based on env info. This is useful to do basic
  276: error checking before passing it off to render.
  277: 
  278: =item * B<r>: default: must be passed in
  279: 
  280: The standard Apache response object. This must be passed to the
  281: renderer or the course hash will be locked.
  282: 
  283: =item * B<cols>: default: empty (useless)
  284: 
  285: An array reference
  286: 
  287: =item * B<showParts>:default true
  288: 
  289: A flag. If true, a line for the resource itself, and a line
  290: for each part will be displayed. If not, only one line for each
  291: resource will be displayed.
  292: 
  293: =item * B<condenseParts>: default true
  294: 
  295: A flag. If true, if all parts of the problem have the same
  296: status and that status is Nothing Set, Correct, or Network Failure,
  297: then only one line will be displayed for that resource anyhow. If no,
  298: all parts will always be displayed. If showParts is 0, this is
  299: ignored.
  300: 
  301: =item * B<jumpCount>: default: determined from %env
  302: 
  303: A string identifying the URL to place the anchor 'curloc' at.
  304: It is the responsibility of the renderer user to
  305: ensure that the #curloc is in the URL. By default, determined through
  306: the use of the env{} 'jump' information, and should normally "just
  307: work" correctly.
  308: 
  309: =item * B<here>: default: empty string
  310: 
  311: A Symb identifying where to place the 'here' marker. The empty
  312: string means no marker.
  313: 
  314: =item * B<indentString>: default: 25 pixel whitespace image
  315: 
  316: A string identifying the indentation string to use. 
  317: 
  318: =item * B<queryString>: default: empty
  319: 
  320: A string which will be prepended to the query string used when the
  321: folders are opened or closed. You can use this to pass
  322: application-specific values.
  323: 
  324: =item * B<url>: default: none
  325: 
  326: The url the folders will link to, which should be the current
  327: page. Required if the resource info column is shown, and you 
  328: are allowing the user to open and close folders.
  329: 
  330: =item * B<currentJumpIndex>: default: no jumping
  331: 
  332: Describes the currently-open row number to cause the browser to jump
  333: to, because the user just opened that folder. By default, pulled from
  334: the Jump information in the env{'form.*'}.
  335: 
  336: =item * B<printKey>: default: false
  337: 
  338: If true, print the key that appears on the top of the standard
  339: navmaps.
  340: 
  341: =item * B<printCloseAll>: default: true
  342: 
  343: If true, print the "Close all folders" or "open all folders"
  344: links.
  345: 
  346: =item * B<filterFunc>: default: sub {return 1;} (accept everything)
  347: 
  348: A function that takes the resource object as its only parameter and
  349: returns a true or false value. If true, the resource is displayed. If
  350: false, it is simply skipped in the display.
  351: 
  352: =item * B<suppressEmptySequences>: default: false
  353: 
  354: If you're using a filter function, and displaying sequences to orient
  355: the user, then frequently some sequences will be empty. Setting this to
  356: true will cause those sequences not to display, so as not to confuse the
  357: user into thinking that if the sequence is there there should be things
  358: under it; for example, see the "Show Uncompleted Homework" view on the
  359: B<NAV> screen.
  360: 
  361: =item * B<suppressNavmap>: default: false
  362: 
  363: If true, will not display Navigate Content resources. 
  364: 
  365: =back
  366: 
  367: =head2 Additional Info
  368: 
  369: In addition to the parameters you can pass to the renderer, which will
  370: be passed through unchange to the column renderers, the renderer will
  371: generate the following information which your renderer may find
  372: useful:
  373: 
  374: =over 4
  375: 
  376: =item * B<counter>: 
  377: 
  378: Contains the number of rows printed. Useful after calling the render 
  379: function, as you can detect whether anything was printed at all.
  380: 
  381: =item * B<isNewBranch>:
  382: 
  383: Useful for renderers: If this resource is currently the first resource
  384: of a new branch, this will be true. The Resource column (leftmost in the
  385: navmaps screen) uses this to display the "new branch" icon 
  386: 
  387: =back
  388: 
  389: =cut
  390: 
  391: 
  392: =head1 SUBROUTINES
  393: 
  394: =over
  395: 
  396: =item update()
  397: 
  398: =item addToFilter()
  399: 
  400: Convenience functions: Returns a string that adds or subtracts
  401: the second argument from the first hash, appropriate for the 
  402: query string that determines which folders to recurse on
  403: 
  404: =item removeFromFilter()
  405: 
  406: =item getLinkForResource()
  407: 
  408: Convenience function: Given a stack returned from getStack on the iterator,
  409: return the correct src() value.
  410: 
  411: =item getDescription()
  412: 
  413: Convenience function: This separates the logic of how to create
  414: the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
  415: etc.) into a separate function. It takes a resource object as the
  416: first parameter, and the part number of the resource as the second.
  417: It's basically a big switch statement on the status of the resource.
  418: 
  419: =item dueInLessThan24Hours()
  420: 
  421: Convenience function, so others can use it: Is the problem due in less than 24 hours, and still can be done?
  422: 
  423: =item lastTry()
  424: 
  425: Convenience function, so others can use it: Is there only one try remaining for the
  426: part, with more than one try to begin with, not due yet and still can be done?
  427: 
  428: =item graceEndsUnder24Hours()
  429: 
  430: Convenience function, so others can use it: Is the problem past-due with a grace period
  431: which ends in less than 24 hours, and still can be done?
  432: 
  433: =item advancedUser()
  434: 
  435: This puts a human-readable name on the env variable.
  436: 
  437: =item timeToHumanString()
  438: 
  439: timeToHumanString takes a time number and converts it to a
  440: human-readable representation, meant to be used in the following
  441: manner:
  442: 
  443: =over 4
  444: 
  445: =item * print "Due $timestring"
  446: 
  447: =item * print "Open $timestring"
  448: 
  449: =item * print "Answer available $timestring"
  450: 
  451: =back
  452: 
  453: Very, very, very, VERY English-only... goodness help a localizer on
  454: this func...
  455: 
  456: =item resource()
  457: 
  458: returns 0
  459: 
  460: =item communication_status()
  461: 
  462: returns 1
  463: 
  464: =item quick_status()
  465: 
  466: returns 2
  467: 
  468: =item long_status()
  469: 
  470: returns 3
  471: 
  472: =item part_status_summary()
  473: 
  474: returns 4
  475: 
  476: =item render_resource()
  477: 
  478: =item render_communication_status()
  479: 
  480: =item render_quick_status()
  481: 
  482: =item render_long_status()
  483: 
  484: =item render_parts_summary_status()
  485: 
  486: =item setDefault()
  487: 
  488: =item cmp_title()
  489: 
  490: =item render()
  491: 
  492: =item add_linkitem()
  493: 
  494: =item show_linkitems_toolbar()
  495: 
  496: =back
  497: 
  498: =cut
  499: 
  500: package Apache::lonnavmaps;
  501: 
  502: use strict;
  503: use GDBM_File;
  504: use Apache::loncommon();
  505: use Apache::lonenc();
  506: use Apache::lonlocal;
  507: use Apache::lonnet;
  508: use Apache::lonmap;
  509: 
  510: use POSIX qw (ceil floor strftime);
  511: use Time::HiRes qw( gettimeofday tv_interval );
  512: use LONCAPA;
  513: use DateTime();
  514: use HTML::Entities;
  515: 
  516: # For debugging
  517: 
  518: #use Data::Dumper;
  519: 
  520: 
  521: # symbolic constants
  522: sub SYMB { return 1; }
  523: sub URL { return 2; }
  524: sub NOTHING { return 3; }
  525: 
  526: # Some data
  527: 
  528: my $resObj = "Apache::lonnavmaps::resource";
  529: 
  530: # Keep these mappings in sync with lonquickgrades, which usesthe colors
  531: # instead of the icons.
  532: my %statusIconMap = 
  533:     (
  534:      $resObj->CLOSED       => '',
  535:      $resObj->OPEN         => 'navmap.open.gif',
  536:      $resObj->CORRECT      => 'navmap.correct.gif',
  537:      $resObj->PARTIALLY_CORRECT      => 'navmap.partial.gif',
  538:      $resObj->INCORRECT    => 'navmap.wrong.gif',
  539:      $resObj->ATTEMPTED    => 'navmap.ellipsis.gif',
  540:      $resObj->ERROR        => ''
  541:      );
  542: 
  543: my %iconAltTags =   #texthash does not work here
  544:     ( 'navmap.correct.gif'  => 'Correct',
  545:       'navmap.wrong.gif'    => 'Incorrect',
  546:       'navmap.open.gif'     => 'Is Open',
  547:       'navmap.partial.gif'  => 'Partially Correct',
  548:       'navmap.ellipsis.gif' => 'Attempted',
  549:      );
  550: 
  551: # Defines a status->color mapping, null string means don't color
  552: my %colormap = 
  553:     ( $resObj->NETWORK_FAILURE        => '',
  554:       $resObj->CORRECT                => '',
  555:       $resObj->EXCUSED                => '#3333FF',
  556:       $resObj->PAST_DUE_ANSWER_LATER  => '',
  557:       $resObj->PAST_DUE_NO_ANSWER     => '',
  558:       $resObj->PAST_DUE_ATMPT_ANS     => '',
  559:       $resObj->PAST_DUE_ATMPT_NOANS   => '',
  560:       $resObj->PAST_DUE_NO_ATMT_ANS   => '',
  561:       $resObj->PAST_DUE_NO_ATMT_NOANS => '',
  562:       $resObj->ANSWER_OPEN            => '#006600',
  563:       $resObj->OPEN_LATER             => '',
  564:       $resObj->TRIES_LEFT             => '',
  565:       $resObj->INCORRECT              => '',
  566:       $resObj->OPEN                   => '',
  567:       $resObj->NOTHING_SET            => '',
  568:       $resObj->ATTEMPTED              => '',
  569:       $resObj->CREDIT_ATTEMPTED       => '',
  570:       $resObj->ANSWER_SUBMITTED       => '',
  571:       $resObj->PARTIALLY_CORRECT      => '#006600'
  572:       );
  573: # And a special case in the nav map; what to do when the assignment
  574: # is not yet done and due in less than 24 hours
  575: my $hurryUpColor = "#FF0000";
  576: 
  577: sub addToFilter {
  578:     my $hashIn = shift;
  579:     my $addition = shift;
  580:     my %hash = %$hashIn;
  581:     $hash{$addition} = 1;
  582: 
  583:     return join (",", keys(%hash));
  584: }
  585: 
  586: sub removeFromFilter {
  587:     my $hashIn = shift;
  588:     my $subtraction = shift;
  589:     my %hash = %$hashIn;
  590: 
  591:     delete $hash{$subtraction};
  592:     return join(",", keys(%hash));
  593: }
  594: 
  595: sub getLinkForResource {
  596:     my $stack = shift;
  597:     my $res;
  598: 
  599:     # Check to see if there are any pages in the stack
  600:     foreach $res (@$stack) {
  601:         if (defined($res)) {
  602: 	    my $anchor;
  603: 	    if ($res->is_page()) {
  604: 		foreach my $item (@$stack) { if (defined($item)) { $anchor = $item; }  }
  605: 		if ($anchor->encrypted() && !&advancedUser()) {
  606: 		    $anchor='LC_'.$anchor->id();
  607: 		} else {
  608: 		    $anchor=&escape($anchor->shown_symb());
  609: 		}
  610: 		return ($res->link(),$res->shown_symb(),$anchor);
  611: 	    }
  612:             # in case folder was skipped over as "only sequence"
  613: 	    my ($map,$id,$src)=&Apache::lonnet::decode_symb($res->symb());
  614: 	    if ($map=~/\.page$/) {
  615: 		my $url=&Apache::lonnet::clutter($map);
  616: 		$anchor=&escape($res->shown_symb());
  617: 		return ($url,$res->shown_symb(),$anchor);
  618: 	    }
  619:         }
  620:     }
  621: 
  622:     # Failing that, return the src of the last resource that is defined
  623:     # (when we first recurse on a map, it puts an undefined resource
  624:     # on the bottom because $self->{HERE} isn't defined yet, and we
  625:     # want the src for the map anyhow)
  626:     foreach my $item (@$stack) {
  627:         if (defined($item)) { $res = $item; }
  628:     }
  629: 
  630:     if ($res) {
  631: 	return ($res->link(),$res->shown_symb());
  632:     }
  633:     return;
  634: }
  635: 
  636: 
  637: 
  638: sub getDescription {
  639:     my $res = shift;
  640:     my $part = shift;
  641:     my $status = $res->status($part);
  642: 
  643:     my $open = $res->opendate($part);
  644:     my $due = $res->duedate($part);
  645:     my $overdue = $res->overduedate($part);
  646:     my $answer = $res->answerdate($part);
  647: 
  648:     if ($status == $res->NETWORK_FAILURE) { 
  649:         return &mt("Having technical difficulties; please check status later"); 
  650:     }
  651:     if ($status == $res->NOTHING_SET) {
  652:         return &Apache::lonhtmlcommon::direct_parm_link(&mt('Not currently assigned'),$res->symb(),'opendate',$part);
  653:     }
  654:     if ($status == $res->OPEN_LATER) {
  655:         return &mt("Open [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($open,'start'),$res->symb(),'opendate',$part));
  656:     }
  657:     my $slotinfo;
  658:     if ($res->simpleStatus($part) == $res->OPEN) {
  659:         unless (&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) {
  660:             my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
  661:             my $slotmsg;
  662:             if ($slot_status == $res->UNKNOWN) {
  663:                 $slotmsg = &mt('Reservation status unknown');
  664:             } elsif ($slot_status == $res->RESERVED) {
  665:                 $slotmsg = &mt('Reserved - ends [_1]',
  666:                            timeToHumanString($slot_time,'end'));
  667:             } elsif ($slot_status == $res->RESERVED_LOCATION) {
  668:                 $slotmsg = &mt('Reserved - specific location(s) - ends [_1]',
  669:                            timeToHumanString($slot_time,'end'));
  670:             } elsif ($slot_status == $res->RESERVED_LATER) {
  671:                 $slotmsg = &mt('Reserved - next open [_1]',
  672:                            timeToHumanString($slot_time,'start'));
  673:             } elsif ($slot_status == $res->RESERVABLE) {
  674:                 $slotmsg = &mt('Reservable, reservations close [_1]',
  675:                            timeToHumanString($slot_time,'end'));
  676:             } elsif ($slot_status == $res->NEEDS_CHECKIN) {
  677:                 $slotmsg = &mt('Reserved, check-in needed - ends [_1]',
  678:                            timeToHumanString($slot_time,'end'));
  679:             } elsif ($slot_status == $res->RESERVABLE_LATER) {
  680:                 $slotmsg = &mt('Reservable, reservations open [_1]',
  681:                            timeToHumanString($slot_time,'start'));
  682:             } elsif ($slot_status == $res->NOT_IN_A_SLOT) {
  683:                 $slotmsg = &mt('Reserve a time/place to work');
  684:             } elsif ($slot_status == $res->NOTRESERVABLE) {
  685:                 $slotmsg = &mt('Reservation not available');
  686:             } elsif ($slot_status == $res->WAITING_FOR_GRADE) {
  687:                 $slotmsg = &mt('Submission in grading queue');
  688:             }
  689:             if ($slotmsg) {
  690:                 if ($res->is_task() || !$due) {
  691:                      return $slotmsg;
  692:                 }
  693:                 $slotinfo = ('&nbsp;' x 2).'('.$slotmsg.')';
  694:             }
  695:         }
  696:     }
  697:     if ($status == $res->OPEN) {
  698:         if ($due) {
  699:             my $now = time;
  700:             if (($now >= $due) && ($overdue) && ($now < $overdue)) {
  701:                 if ($res->is_practice()) {
  702:                     return &mt("Closes [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($overdue,'start'),$res->symb(),'duedate',$part)).$slotinfo;
  703:                 } else {
  704:                     return &mt("Grace period ends [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($overdue,'end'),$res->symb(),'grace',$part)).$slotinfo;
  705:                 }
  706:             } else {
  707:                 if ($res->is_practice()) {
  708:                     return &mt("Closes [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'start'),$res->symb(),'duedate',$part)).$slotinfo;
  709:                 } else {
  710:                     return &mt("Due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'duedate',$part)).$slotinfo;
  711:                 }
  712:             }
  713:         } else {
  714:             return &Apache::lonhtmlcommon::direct_parm_link(&mt("Open, no due date"),$res->symb(),'duedate',$part).$slotinfo;
  715:         }
  716:     }
  717:     if (($status == $res->PAST_DUE_ANSWER_LATER) || ($status == $res->PAST_DUE_ATMPT_ANS) || ($status == $res->PAST_DUE_NO_ATMT_ANS)) {
  718:         return &mt("Answer open [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($answer,'start'),$res->symb(),'answerdate',$part));
  719:     }
  720:     if (($status == $res->PAST_DUE_NO_ANSWER) || ($status == $res->PAST_DUE_ATMPT_NOANS) || ($status == $res->PAST_DUE_NO_ATMT_NOANS)) {
  721: 	if ($res->is_practice()) {
  722: 	    return &mt("Closed [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'start'),$res->symb(),'answerdate,duedate',$part));
  723: 	} else {
  724: 	    return &mt("Was due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'answerdate,duedate',$part));
  725: 	}
  726:     }
  727:     if (($status == $res->ANSWER_OPEN || $status == $res->PARTIALLY_CORRECT)
  728: 	&& $res->handgrade($part) ne 'yes') {
  729:         my $msg = &mt('Answer available');
  730:         my $parmlist = 'answerdate,duedate';
  731:         if (($res->is_tool) && ($res->is_gradable())) {
  732:             if (($status == $res->PARTIALLY_CORRECT) && ($res->parmval('retrypartial',$part))) {
  733:                 $msg = &mt('Grade received');
  734:                 $parmlist = 'retrypartial';
  735:             } else {
  736:                 $msg = &mt('Grade available');
  737:             }
  738:         }
  739:         return &Apache::lonhtmlcommon::direct_parm_link($msg,$res->symb(),$parmlist,$part);
  740:     }
  741:     if ($status == $res->EXCUSED) {
  742:         return &mt("Excused by instructor");
  743:     }
  744:     if ($status == $res->ATTEMPTED) {
  745:         if ($res->is_anonsurvey($part) || $res->is_survey($part)) {
  746:             return &mt("Survey submission recorded");
  747:         } else {
  748:             return &mt("Answer submitted, not yet graded");
  749:         }
  750:     }
  751:     if ($status == $res->CREDIT_ATTEMPTED) {
  752:         if ($res->is_anonsurvey($part) || $res->is_survey($part)) {
  753:             return &mt("Credit for survey submission");
  754:         }
  755:     }
  756:     if ($status == $res->TRIES_LEFT) {
  757:         my $tries = $res->tries($part);
  758:         my $maxtries = $res->maxtries($part);
  759:         my $triesString = "";
  760:         if ($tries && $maxtries) {
  761:             $triesString = '<span class="LC_fontsize_medium"><i>('.&mt('[_1] of [quant,_2,try,tries] used',$tries,$maxtries).')</i></span>';
  762:             if ($maxtries > 1 && $maxtries - $tries == 1) {
  763:                 $triesString = "<b>$triesString</b>";
  764:             }
  765:         }
  766:         if ($due) {
  767:             my $now = time;
  768:             if (($now >= $due) && ($overdue) && ($now < $overdue)) {
  769:                 return &mt("Grace period ends [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($overdue,'end'),$res->symb(),'grace',$part)).
  770: 		       " $triesString";
  771:             } else {
  772:                 return &mt("Due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'duedate',$part)) .
  773:                        " $triesString";
  774:             }
  775:         } else {
  776:             return &Apache::lonhtmlcommon::direct_parm_link(&mt("No due date"),$res->symb(),'duedate',$part)." $triesString";
  777:         }
  778:     }
  779:     if ($status == $res->ANSWER_SUBMITTED) {
  780:         return &mt('Answer submitted');
  781:     }
  782: }
  783: 
  784: 
  785: sub dueInLessThan24Hours {
  786:     my $res = shift;
  787:     my $part = shift;
  788:     my $status = $res->status($part);
  789: 
  790:     return ($status == $res->OPEN() ||
  791:             $status == $res->TRIES_LEFT()) &&
  792: 	    $res->duedate($part) && $res->duedate($part) < time()+(24*60*60) &&
  793: 	    $res->duedate($part) > time();
  794: }
  795: 
  796: 
  797: sub lastTry {
  798:     my $res = shift;
  799:     my $part = shift;
  800: 
  801:     my $tries = $res->tries($part);
  802:     my $maxtries = $res->maxtries($part);
  803:     return $tries && $maxtries && $maxtries > 1 &&
  804:         $maxtries - $tries == 1 && $res->duedate($part) &&
  805:         $res->duedate($part) > time();
  806: }
  807: 
  808: sub graceEndsUnder24Hours {
  809:     my $res = shift;
  810:     my $part = shift;
  811:     my $status = $res->status($part);
  812:     my $now = time();
  813: 
  814:     return ($status == $res->OPEN() ||
  815:             $status == $res->TRIES_LEFT()) &&
  816:             $res->duedate($part) && $res->duedate($part) < $now &&
  817:             $res->overduedate($part) && $res->overduedate($part) < time()+(24*60*60) &&
  818:             $res->duedate($part) && $res->duedate($part) < $now+(24*60*60) &&
  819:             $res->overduedate($part) > $now;
  820: }
  821: 
  822: sub advancedUser {
  823:     return $env{'request.role.adv'};
  824: }
  825: 
  826: sub timeToHumanString {
  827:     my ($time,$type,$format) = @_;
  828: 
  829:     # zero, '0' and blank are bad times
  830:     if (!$time) {
  831:         return &mt('never');
  832:     }
  833:     unless (&Apache::lonlocal::current_language()=~/^en/) {
  834: 	return &Apache::lonlocal::locallocaltime($time);
  835:     } 
  836:     my $now = time();
  837: 
  838:     # Positive = future
  839:     my $delta = $time - $now;
  840: 
  841:     my $minute = 60;
  842:     my $hour = 60 * $minute;
  843:     my $day = 24 * $hour;
  844:     my $week = 7 * $day;
  845:     my $inPast = 0;
  846: 
  847:     # Logic in comments:
  848:     # Is it now? (extremely unlikely)
  849:     if ( $delta == 0 ) {
  850:         return "this instant";
  851:     }
  852: 
  853:     if ($delta < 0) {
  854:         $inPast = 1;
  855:         $delta = -$delta;
  856:     }
  857: 
  858:     if ( $delta > 0 ) {
  859: 
  860:         my $tense = $inPast ? " ago" : "";
  861:         my $prefix = $inPast ? "" : "in ";
  862:         
  863:         # Less than a minute
  864:         if ( $delta < $minute ) {
  865:             if ($delta == 1) { return "${prefix}1 second$tense"; }
  866:             return "$prefix$delta seconds$tense";
  867:         }
  868: 
  869:         # Less than an hour
  870:         if ( $delta < $hour ) {
  871:             # If so, use minutes; or minutes, seconds (if format requires)
  872:             my $minutes = floor($delta / 60);
  873:             if (($format ne '') && ($format =~ /\%(T|S)/)) {
  874:                 my $display;
  875:                 if ($minutes == 1) {
  876:                     $display = "${prefix}1 minute";
  877:                 } else {
  878:                     $display = "$prefix$minutes minutes";
  879:                 }
  880:                 my $seconds = $delta % $minute;
  881:                 if ($seconds == 0) {
  882:                     $display .= $tense;
  883:                 } elsif ($seconds == 1) {
  884:                     $display .= ", 1 second$tense";
  885:                 } else {
  886:                     $display .= ", $seconds seconds$tense";
  887:                 }
  888:                 return $display;
  889:             }
  890:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
  891:             return "$prefix$minutes minutes$tense";
  892:         }
  893:         
  894:         # Is it less than 24 hours away? If so,
  895:         # display hours + minutes, (and + seconds, if format specified it)  
  896:         if ( $delta < $hour * 24) {
  897:             my $hours = floor($delta / $hour);
  898:             my $minutes = floor(($delta % $hour) / $minute);
  899:             my $hourString = "$hours hours";
  900:             my $minuteString = ", $minutes minutes";
  901:             if ($hours == 1) {
  902:                 $hourString = "1 hour";
  903:             }
  904:             if ($minutes == 1) {
  905:                 $minuteString = ", 1 minute";
  906:             }
  907:             if ($minutes == 0) {
  908:                 $minuteString = "";
  909:             }
  910:             if (($format ne '') && ($format =~ /\%(T|S)/)) {
  911:                 my $display = "$prefix$hourString$minuteString";
  912:                 my $seconds = $delta-(($hours * $hour)+($minutes * $minute));
  913:                 if ($seconds == 0) {
  914:                     $display .= $tense;
  915:                 } elsif ($seconds == 1) {
  916:                     $display .= ", 1 second$tense";
  917:                 } else {
  918:                     $display .= ", $seconds seconds$tense";
  919:                 }
  920:                 return $display;
  921:             }
  922:             return "$prefix$hourString$minuteString$tense";
  923:         }
  924: 
  925:         # Date/time is more than 24 hours away
  926: 
  927: 	my $dt = DateTime->from_epoch(epoch => $time)
  928: 	                 ->set_time_zone(&Apache::lonlocal::gettimezone());
  929: 
  930: 	# If there's a caller supplied format, use it, unless it only displays
  931:         # H:M:S or H:M.
  932: 
  933: 	if (($format ne '') && ($format ne '%T') && ($format ne '%R')) {
  934: 	    my $timeStr = $dt->strftime($format);
  935: 	    return $timeStr.' ('.$dt->time_zone_short_name().')';
  936: 	}
  937: 
  938:         # Less than 5 days away, display day of the week and
  939:         # HH:MM
  940: 
  941:         if ( $delta < $day * 5 ) {
  942:             my $timeStr = $dt->strftime("%A, %b %e at %I:%M %P (%Z)");
  943:             $timeStr =~ s/12:00 am/00:00/;
  944:             $timeStr =~ s/12:00 pm/noon/;
  945:             return ($inPast ? "last " : "this ") .
  946:                 $timeStr;
  947:         }
  948:         
  949: 	my $conjunction='on';
  950: 	if ($type eq 'start') {
  951: 	    $conjunction='at';
  952: 	} elsif ($type eq 'end') {
  953: 	    $conjunction='by';
  954: 	}
  955:         # Is it this year?
  956: 	my $dt_now = DateTime->from_epoch(epoch => $now)
  957: 	                     ->set_time_zone(&Apache::lonlocal::gettimezone());
  958:         if ( $dt->year() == $dt_now->year()) {
  959:             # Return on Month Day, HH:MM meridian
  960:             my $timeStr = $dt->strftime("$conjunction %A, %b %e at %I:%M %P (%Z)");
  961:             $timeStr =~ s/12:00 am/00:00/;
  962:             $timeStr =~ s/12:00 pm/noon/;
  963:             return $timeStr;
  964:         }
  965: 
  966:         # Not this year, so show the year
  967:         my $timeStr = 
  968: 	    $dt->strftime("$conjunction %A, %b %e %Y at %I:%M %P (%Z)");
  969:         $timeStr =~ s/12:00 am/00:00/;
  970:         $timeStr =~ s/12:00 pm/noon/;
  971:         return $timeStr;
  972:     }
  973: }
  974: 
  975: 
  976: sub resource { return 0; }
  977: sub communication_status { return 1; }
  978: sub quick_status { return 2; }
  979: sub long_status { return 3; }
  980: sub part_status_summary { return 4; }
  981: 
  982: sub render_resource {
  983:     my ($resource, $part, $params) = @_;
  984: 
  985:     my $editmapLink;
  986:     my $nonLinkedText = ''; # stuff after resource title not in link
  987: 
  988:     my $link = $params->{"resourceLink"};
  989:     if ($resource->ext()) {
  990:         $link =~ s/\#.+(\?)/$1/g;
  991:     }
  992: 
  993:     #  The URL part is not escaped at this point, but the symb is... 
  994: 
  995:     my $src = $resource->src();
  996:     my $it = $params->{"iterator"};
  997:     my $filter = $it->{FILTER};
  998: 
  999:     my $title = $resource->compTitle();
 1000: 
 1001:     my $partLabel = "";
 1002:     my $newBranchText = "";
 1003:     my $location=&Apache::loncommon::lonhttpdurl("/adm/lonIcons");
 1004:     # If this is a new branch, label it so
 1005:     if ($params->{'isNewBranch'}) {
 1006:         $newBranchText = "<img src='$location/branch.gif' alt=".mt('Branch')." />";
 1007:     }
 1008: 
 1009:     my $whitespace = $location.'/whitespace_21.gif';
 1010:     my ($nomodal,$linkopen,$linkclose);
 1011:     unless ($resource->is_map() || $params->{'resource_nolink'}) {
 1012:         $linkopen = "<img src='$whitespace' alt='' />";
 1013:         $linkclose = "</a>";
 1014:         if (($params->{'modalLink'}) && (!$resource->is_sequence())) {
 1015:             if ($link =~m{^(?:|/adm/wrapper)/ext/([^#]+)}) {
 1016:                 my $exturl = $1;
 1017:                 if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
 1018:                     $nomodal = 1;
 1019:                 }
 1020:             } elsif (($link eq "/public/$LONCAPA::match_domain/$LONCAPA::match_courseid/syllabus") &&
 1021:                      ($env{'request.course.id'}) && ($ENV{'SERVER_PORT'} == 443) &&
 1022:                      ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 1023:                 $nomodal = 1;
 1024:             }
 1025:             my $esclink = &js_escape($link);
 1026:             if ($nomodal) {
 1027:                 $linkopen .= "<a href=\"#\" onclick=\"javascript:window.open('$esclink','resourcepreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1'); return false;\" />";
 1028:             } else {
 1029:                 $linkopen .= "<a href=\"$link\" onclick=\"javascript:openMyModal('$esclink',600,500,'yes','true'); return false;\">";
 1030:             }
 1031:         } else {
 1032:             $linkopen .= "<a href=\"$link\">";
 1033:         }
 1034:     }
 1035: 
 1036:     # Default icon: unknown page
 1037:     my $icon = "<img class=\"LC_contentImage\" src='$location/unknown.gif' alt='' />";
 1038:     
 1039:     if ($resource->is_problem()) {
 1040:         if ($part eq '0' || $params->{'condensed'}) {
 1041: 	    $icon = '<img class="LC_contentImage" src="'.$location.'/';
 1042: 	    if ($resource->is_task()) {
 1043: 		$icon .= 'task.gif" alt="'.&mt('Task');
 1044: 	    } else {
 1045: 		$icon .= 'problem.gif" alt="'.&mt('Problem');
 1046: 	    }
 1047: 	    $icon .='" />';
 1048:         } else {
 1049:             $icon = $params->{'indentString'};
 1050:         }
 1051:     } else {
 1052: 	$icon = "<img class=\"LC_contentImage\" src='".&Apache::loncommon::icon($resource->src)."' alt='' />";
 1053:     }
 1054: 
 1055:     # Display the correct map icon to open or shut map
 1056:     if ($resource->is_map()) {
 1057:         my $mapId = $resource->map_pc();
 1058:         my $nowOpen = !defined($filter->{$mapId});
 1059:         if ($it->{CONDITION}) {
 1060:             $nowOpen = !$nowOpen;
 1061:         }
 1062: 	my $folderType;
 1063: 	if (&advancedUser() && $resource->is_missing_map()) {
 1064: 	    $folderType = 'none';
 1065: 	} else {
 1066: 	    $folderType = $resource->is_sequence() ? 'folder' : 'page';
 1067: 	}
 1068:         my $title=$resource->title;
 1069: 		$title=~s/\"/\&qout;/g;
 1070:         if (!$params->{'resource_no_folder_link'}) {
 1071:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
 1072:             $icon = "<img src='$location/arrow." . ($nowOpen ? 'closed' : 'open') . ".gif' alt='' />"
 1073:                     ."<img class=\"LC_contentImage\" src='$location/$icon' alt=\""
 1074:                     .($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" />";			
 1075:             $linkopen = "<a href=\"" . $params->{'url'} . '?' . 
 1076:                 $params->{'queryString'} . '&amp;filter=';
 1077:             $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
 1078:                 addToFilter($filter, $mapId) :
 1079:                 removeFromFilter($filter, $mapId);
 1080:             $linkopen .= "&amp;condition=" . $it->{CONDITION} . '&amp;hereType='
 1081:                 . $params->{'hereType'} . '&amp;here=' .
 1082:                 &escape($params->{'here'}) . 
 1083:                 '&amp;jump=' .
 1084:                 &escape($resource->symb()) . 
 1085:                 "&amp;folderManip=1\">";
 1086:             $linkclose = '</a>';
 1087:         } else {
 1088:             # Don't allow users to manipulate folder
 1089:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
 1090:             $icon = "<img class=\"LC_space\" src='$whitespace' alt='' />"."<img class=\"LC_contentImage\" src='$location/$icon' alt=\"".($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" />";
 1091:             if ($params->{'caller'} eq 'sequence') {
 1092:                 $linkopen = "<a href=\"$link\">";
 1093:                 $linkclose = '</a>';
 1094:             } else {
 1095:                 $linkopen = "";
 1096:                 $linkclose = "";
 1097:             }
 1098:         }
 1099:         if (((&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) ||
 1100:               (&Apache::lonnet::allowed('cev',$env{'request.course.id'}))) &&
 1101:             ($resource->symb=~/\_\_\_[^\_]+\_\_\_uploaded/)) {
 1102:             if (!$params->{'map_no_edit_link'}) {
 1103:                 my $icon = &Apache::loncommon::lonhttpdurl('/res/adm/pages').'/editmap.png';
 1104:                 $editmapLink='&nbsp;'.
 1105:                          '<a href="/adm/coursedocs?command=directnav&amp;symb='.&escape($resource->symb()).'">'.
 1106:                          '<img src="'.$icon.'" alt="'.&mt('Edit Content').'" title="'.&mt('Edit Content').'" />'.
 1107:                          '</a>';
 1108:             }
 1109:         }
 1110:         if ($params->{'mapHidden'} || $resource->randomout()) {
 1111:             $nonLinkedText .= ' <span class="LC_warning">('.&mt('hidden').')</span> ';
 1112:         } elsif ($params->{'mapUnlisted'}) {
 1113:             $nonLinkedText .= ' <span class="LC_warning">('.&mt('unlisted').')</span> ';
 1114:         } elsif ($params->{'mapHiddenDeepLink'} || $resource->deeplinkout()) {
 1115:             $nonLinkedText .= ' <span class="LC_warning">('.&mt('not shown').')</span> ';
 1116:         }
 1117:     } else {
 1118:         if ($resource->randomout()) {
 1119:             $nonLinkedText .= ' <span class="LC_warning">('.&mt('hidden').')</span> ';
 1120:         } elsif ($resource->deeplinkout()) {
 1121:             $nonLinkedText .= ' <span class="LC_warning">('.&mt('not shown').')</span> ';
 1122:         } else {
 1123:             my $deeplink = $resource->deeplink($params->{caller});
 1124:             if ((($deeplink eq 'absent') || ($deeplink eq 'grades')) &&
 1125:                   &advancedUser()) {
 1126:                 $nonLinkedText .= ' <span class="LC_warning">('.&mt('unlisted').')</span> ';
 1127:             } elsif (($deeplink) && ($deeplink) ne 'full') {
 1128:                 if (&advancedUser()) {
 1129:                     $nonLinkedText .= ' <span class="LC_warning">('.&mt('deep-link access').
 1130:                                       ')</span> ';
 1131:                 } else {
 1132:                     $nonLinkedText .= ' <span class="LC_warning">('.&mt('access via external site').
 1133:                                       ')</span> ';
 1134:                 }
 1135:             }
 1136:         }
 1137:     }
 1138:     if (!$resource->condval()) {
 1139:         $nonLinkedText .= ' <span class="LC_info">('.&mt('conditionally hidden').')</span> ';
 1140:     }
 1141:     if (($resource->is_practice()) && ($resource->is_raw_problem())) {
 1142:         $nonLinkedText .=' <span class="LC_info"><b>'.&mt('not graded').'</b></span>';
 1143:     }
 1144: 
 1145:     # We're done preparing and finally ready to start the rendering
 1146:     my $result = '<td class="LC_middle">';
 1147:     my $newfolderType = $resource->is_sequence() ? 'folder' : 'page';
 1148: 	
 1149:     my $indentLevel = $params->{'indentLevel'};
 1150:     if ($newBranchText) { $indentLevel--; }
 1151: 
 1152:     # print indentation
 1153:     for (my $i = 0; $i < $indentLevel; $i++) {
 1154:         $result .= $params->{'indentString'};
 1155:     }
 1156: 
 1157:     # Decide what to display
 1158:     $result .= "$newBranchText$linkopen$icon";
 1159:     
 1160:     my $curMarkerBegin = '';
 1161:     my $curMarkerEnd = '';
 1162: 
 1163:     # Is this the current resource?
 1164:     if (!$params->{'displayedHereMarker'} && 
 1165:         $resource->symb() eq $params->{'here'} ) {
 1166:         unless ($resource->is_map()) {
 1167:             $curMarkerBegin = '<span class="LC_current_nav_location">';
 1168:             $curMarkerEnd = '</span>';
 1169:         }
 1170: 	$params->{'displayedHereMarker'} = 1;
 1171:     }
 1172: 
 1173:     if ($resource->is_problem() && $part ne '0' && 
 1174:         !$params->{'condensed'}) {
 1175: 	my $displaypart=$resource->part_display($part);
 1176:         $partLabel = " (".&mt('Part: [_1]', $displaypart).")";
 1177: 	if ($link!~/\#/) { $link.='#'.&escape($part); }
 1178:         $title = "";
 1179:     }
 1180: 
 1181:     if ($params->{'condensed'} && $resource->countParts() > 1) {
 1182:         $nonLinkedText .= ' ('.&mt('[_1] parts', $resource->countParts()).')';
 1183:     }
 1184: 
 1185:     if (!$params->{'resource_nolink'} && !$resource->is_sequence() && !$resource->is_empty_sequence) {
 1186:         $linkclose = '</a>';
 1187:         if ($params->{'modalLink'}) {
 1188:             my $esclink = &js_escape($link);
 1189:             if ($nomodal) {
 1190:                 $linkopen = "<a href=\"#\" onclick=\"javascript:window.open('$esclink','resourcepreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1'); return false;\" />";
 1191:             } else {
 1192:                 $linkopen = "<a href=\"$link\" onclick=\"javascript:openMyModal('$esclink',600,500,'yes','true'); return false;\">";
 1193:             }
 1194:         } else {
 1195:             $linkopen = "<a href=\"$link\">";
 1196:         }
 1197:     }
 1198:     $result .= "$curMarkerBegin$title$partLabel$curMarkerEnd$linkclose$editmapLink$nonLinkedText</td>";
 1199: 
 1200:     return $result;
 1201: }
 1202: 
 1203: sub render_communication_status {
 1204:     my ($resource, $part, $params) = @_;
 1205:     my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
 1206: 
 1207:     my $link = $params->{"resourceLink"};
 1208:     my $linkopen = "<a href=\"$link\">";
 1209:     my $linkclose = "</a>";
 1210:     my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc");
 1211: 
 1212:     if ($resource->hasDiscussion()) {
 1213:         $discussionHTML = $linkopen .
 1214:             '<img alt="'.&mt('New Discussion').'" src="'.$location.'/chat.gif" title="'.&mt('New Discussion').'"/>' .
 1215:             $linkclose;
 1216:     }
 1217:     
 1218:     if ($resource->getFeedback()) {
 1219:         my $feedback = $resource->getFeedback();
 1220:         foreach my $msgid (split(/\,/, $feedback)) {
 1221:             if ($msgid) {
 1222:                 $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
 1223:                     . &escape($msgid) . '">'
 1224:                     . '<img alt="'.&mt('New E-mail').'" src="'.$location.'/feedback.gif" title="'.&mt('New E-mail').'"/></a>';
 1225:             }
 1226:         }
 1227:     }
 1228:     
 1229:     if ($resource->getErrors()) {
 1230:         my $errors = $resource->getErrors();
 1231:         my $errorcount = 0;
 1232:         foreach my $msgid (split(/,/, $errors)) {
 1233:             last if ($errorcount>=10); # Only output 10 bombs maximum
 1234:             if ($msgid) {
 1235:                 $errorcount++;
 1236:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
 1237:                     . &escape($msgid) . '">'
 1238:                     . '<img alt="'.&mt('New Error').'" src="'.$location.'/bomb.gif" title="'.&mt('New Error').'"/></a>';
 1239:             }
 1240:         }
 1241:     }
 1242: 
 1243:     if ($params->{'multipart'} && $part != '0') {
 1244: 	$discussionHTML = $feedbackHTML = $errorHTML = '';
 1245:     }
 1246:     return "<td class=\"LC_middle\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
 1247: 
 1248: }
 1249: sub render_quick_status {
 1250:     my ($resource, $part, $params) = @_;
 1251:     my $result = "";
 1252:     my $firstDisplayed = !$params->{'condensed'} && 
 1253:         $params->{'multipart'} && $part eq "0";
 1254: 
 1255:     my $link = $params->{"resourceLink"};
 1256:     my $linkopen = "<a href=\"$link\">";
 1257:     my $linkclose = "</a>";
 1258: 	
 1259: 	$result .= '<td class="LC_middle">';
 1260:     if ($resource->is_gradable() &&
 1261:         !$firstDisplayed) {
 1262:         my $icon = $statusIconMap{$resource->simpleStatus($part)};
 1263:         my $alt = $iconAltTags{$icon};
 1264:         if ($icon) {
 1265: 	    my $location=
 1266: 		&Apache::loncommon::lonhttpdurl("/adm/lonIcons/$icon");
 1267: 		$result .= $linkopen.'<img src="'.$location.'" alt="'.&mt($alt).'" title="'.&mt($alt).'" />'.$linkclose;            
 1268:         } else {
 1269:             $result .= "&nbsp;";
 1270:         }
 1271:     } else { # not problem, no icon
 1272:         $result .= "&nbsp;";
 1273:     }
 1274: 	$result .= "</td>\n";
 1275:     return $result;
 1276: }
 1277: sub render_long_status {
 1278:     my ($resource, $part, $params) = @_;
 1279:     my $result = '<td class="LC_middle LC_right">';
 1280:     my $firstDisplayed = !$params->{'condensed'} && 
 1281:         $params->{'multipart'} && $part eq "0";
 1282:                 
 1283:     my $color;
 1284:     my $info = '';
 1285:     if ($resource->is_gradable() || $resource->is_practice()) {
 1286:         $color = $colormap{$resource->status};
 1287: 
 1288:         if (dueInLessThan24Hours($resource, $part)) {
 1289:             $color = $hurryUpColor;
 1290:             $info = ' title="'.&mt('Due in less than 24 hours!').'"';
 1291:         } elsif (graceEndsUnder24Hours($resource, $part)) {
 1292:             $color = $hurryUpColor;
 1293:             $info = ' title="'.&mt('Grace period ends in less than 24 hours!').'"';
 1294:         } elsif (lastTry($resource, $part)) {
 1295:             unless (($resource->problemstatus($part) eq 'no') ||
 1296:                     ($resource->problemstatus($part) eq 'no_feedback_ever')) {
 1297:                 $color = $hurryUpColor;
 1298:                 $info = ' title="'.&mt('One try remaining!').'"';
 1299:             }
 1300:          }
 1301:     }
 1302: 
 1303:     if (($resource->kind() eq "res") &&
 1304:         ($resource->is_raw_problem() || $resource->is_gradable()) &&
 1305:         !$firstDisplayed) {
 1306:         if ($color) {$result .= '<span style="color:'.$color.'"'.$info.'><b>'; }
 1307:         $result .= getDescription($resource, $part);
 1308:         if ($color) {$result .= "</b></span>"; }
 1309:     }
 1310:     if ($resource->is_map() && &advancedUser() && $resource->randompick()) {
 1311:         $result .= &mt('(randomly select [_1])', $resource->randompick());
 1312:     }
 1313:     if ($resource->is_map() && &advancedUser() && $resource->randomorder()) {
 1314:         $result .= &mt('(randomly ordered)');
 1315:     }
 1316: 
 1317:     # Debugging code
 1318:     #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) .
 1319:     #	' - Part: ' . $part;
 1320: 
 1321:     $result .= "</td>\n";
 1322:     
 1323:     return $result;
 1324: }
 1325: 
 1326: # Colors obtained by taking the icons, matching the colors, and
 1327: # possibly reducing the Value (HSV) of the color, if it's too bright
 1328: # for text, generally by one third or so.
 1329: my %statusColors = 
 1330:     (
 1331:      $resObj->CLOSED => '#000000',
 1332:      $resObj->OPEN   => '#998b13',
 1333:      $resObj->CORRECT => '#26933f',
 1334:      $resObj->INCORRECT => '#c48207',
 1335:      $resObj->ATTEMPTED => '#a87510',
 1336:      $resObj->ERROR => '#000000'
 1337:      );
 1338: my %statusStrings = 
 1339:     (
 1340:      $resObj->CLOSED => 'Not yet open',
 1341:      $resObj->OPEN   => 'Open',
 1342:      $resObj->CORRECT => 'Correct',
 1343:      $resObj->INCORRECT => 'Incorrect',
 1344:      $resObj->ATTEMPTED => 'Attempted',
 1345:      $resObj->ERROR => 'Network Error'
 1346:      );
 1347: my @statuses = ($resObj->CORRECT, $resObj->ATTEMPTED, $resObj->INCORRECT, $resObj->OPEN, $resObj->CLOSED, $resObj->ERROR);
 1348: 
 1349: sub render_parts_summary_status {
 1350:     my ($resource, $part, $params) = @_;
 1351:     if (!$resource->is_gradable() && !$resource->contains_problem) { return '<td></td>'; }
 1352:     if ($params->{showParts}) { 
 1353: 	return '<td></td>';
 1354:     }
 1355: 
 1356:     my $td = "<td align='right'>\n";
 1357:     my $endtd = "</td>\n";
 1358:     my @probs;
 1359: 
 1360:     if ($resource->contains_problem) {
 1361: 	@probs=$resource->retrieveResources($resource,sub { $_[0]->is_problem() },1,0);
 1362:     } else {
 1363: 	@probs=($resource);
 1364:     }
 1365:     my $return;
 1366:     my %overallstatus;
 1367:     my $totalParts;
 1368:     foreach my $resource (@probs) {
 1369: 	# If there is a single part, just show the simple status
 1370: 	if ($resource->singlepart()) {
 1371: 	    my $status = $resource->simpleStatus(${$resource->parts}[0]);
 1372: 	    $overallstatus{$status}++;
 1373: 	    $totalParts++;
 1374: 	    next;
 1375: 	}
 1376: 	# Now we can be sure the $part doesn't really matter.
 1377: 	my $statusCount = $resource->simpleStatusCount();
 1378: 	my @counts;
 1379: 	foreach my $status (@statuses) {
 1380: 	    # decouple display order from the simpleStatusCount order
 1381: 	    my $slot = Apache::lonnavmaps::resource::statusToSlot($status);
 1382: 	    if ($statusCount->[$slot]) {
 1383: 		$overallstatus{$status}+=$statusCount->[$slot];
 1384: 		$totalParts+=$statusCount->[$slot];
 1385: 	    }
 1386: 	}
 1387:     }
 1388:     $return.= $td . $totalParts . ' parts: ';
 1389:     foreach my $status (@statuses) {
 1390:         if ($overallstatus{$status}) {
 1391:             $return.='<span style="color:' . $statusColors{$status}
 1392:                    . '">' . $overallstatus{$status} . ' '
 1393:                    . $statusStrings{$status} . '</span>';
 1394:         }
 1395:     }
 1396:     $return.= $endtd;
 1397:     return $return;
 1398: }
 1399: 
 1400: my @preparedColumns = (\&render_resource, \&render_communication_status,
 1401:                        \&render_quick_status, \&render_long_status,
 1402: 		       \&render_parts_summary_status);
 1403: 
 1404: sub setDefault {
 1405:     my ($val, $default) = @_;
 1406:     if (!defined($val)) { return $default; }
 1407:     return $val;
 1408: }
 1409: 
 1410: sub cmp_title {
 1411:     my ($atitle,$btitle) = (lc($_[0]->compTitle),lc($_[1]->compTitle));
 1412:     $atitle=~s/^\s*//;
 1413:     $btitle=~s/^\s*//;
 1414:     return $atitle cmp $btitle;
 1415: }
 1416: 
 1417: sub render {
 1418:     my $args = shift;
 1419:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
 1420:     # Configure the renderer.
 1421:     my $cols = $args->{'cols'};
 1422:     if (!defined($cols)) {
 1423:         # no columns, no nav maps.
 1424:         return '';
 1425:     }
 1426:     my $legend = '';
 1427:     my $tools = '';
 1428:     my $result = '';
 1429:     my $tools_printed = 0;
 1430:     my $tablestarted = 0;
 1431:     my $navmap;
 1432:     if (defined($args->{'navmap'})) {
 1433:         $navmap = $args->{'navmap'};
 1434:     }
 1435: 
 1436:     my $r = $args->{'r'};
 1437:     my $queryString = $args->{'queryString'};
 1438:     my $jump = $args->{'jump'};
 1439:     my $here = $args->{'here'};
 1440:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
 1441:     my $closeAllPages = setDefault($args->{'closeAllPages'}, 0);
 1442:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
 1443:                              # before the current resource when using #current
 1444: 
 1445:     # If we were passed 'here' information, we are not rendering
 1446:     # after a folder manipulation, and we were not passed an
 1447:     # iterator, make sure we open the folders to show the "here"
 1448:     # marker
 1449:     my $filterHash = {};
 1450:     # Figure out what we're not displaying
 1451:     foreach my $item (split(/\,/, $env{"form.filter"})) {
 1452:         if ($item) {
 1453:             $filterHash->{$item} = "1";
 1454:         }
 1455:     }
 1456: 
 1457:     # Filter: Remember filter function and add our own filter: Refuse
 1458:     # to show hidden resources unless the user can see them.
 1459:     my $userCanSeeHidden = advancedUser();
 1460:     my $filterFunc = setDefault($args->{'filterFunc'},
 1461:                                 sub {return 1;});
 1462:     if (!$userCanSeeHidden) {
 1463:         # Without renaming the filterfunc, the server seems to go into
 1464:         # an infinite loop
 1465:         my $oldFilterFunc = $filterFunc;
 1466:         $filterFunc = sub { my $res = shift; return !$res->randomout() &&
 1467:                                 ($res->deeplink($args->{'caller'}) ne 'absent') &&
 1468:                                 ($res->deeplink($args->{'caller'}) ne 'grades') &&
 1469:                                 !$res->deeplinkout() &&
 1470:                                 &$oldFilterFunc($res);};
 1471:     }
 1472: 
 1473:     my $condition = 0;
 1474:     if ($env{'form.condition'}) {
 1475:         $condition = 1;
 1476:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.course.id'}) && (!$userCanSeeHidden)) {
 1477:         if (!defined($navmap)) {
 1478:             $navmap = Apache::lonnavmaps::navmap->new();
 1479:         }
 1480:         if (defined($navmap)) {
 1481:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1482:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1483:             my $symb = &Apache::loncommon::symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 1484:             if ($symb) {
 1485:                 my $deeplink;
 1486:                 my $res = $navmap->getBySymb($symb);
 1487:                 if ($res->is_map()) {
 1488:                     my $mapname = &Apache::lonnet::declutter($res->src());
 1489:                     $mapname = &Apache::lonnet::deversion($mapname);
 1490:                     $deeplink = $navmap->get_mapparam(undef,$mapname,"0.deeplink");
 1491:                 } else {
 1492:                     $deeplink = $res->deeplink();
 1493:                 }
 1494:                 if ($deeplink ne '') {
 1495:                     if ((split(/,/,$deeplink))[1] eq 'hide') {
 1496:                         if ($res->is_map()) {
 1497:                             map { $filterHash->{$_} = 1 if $_ } split(/,/,$res->map_hierarchy());
 1498:                         } else {
 1499:                             my $mapurl = (&Apache::lonnet::decode_symb($symb))[0];
 1500:                             my $map = $navmap->getResourceByUrl($mapurl);
 1501:                             map { $filterHash->{$_} = 1 if $_ } split(/,/,$map->map_hierarchy());
 1502:                         }
 1503:                     }
 1504:                 }
 1505:             }
 1506:         }
 1507:     }
 1508: 
 1509:     if (!$env{'form.folderManip'} && !defined($args->{'iterator'}) && !$args->{'nocurrloc'}) {
 1510:         # Step 1: Check to see if we have a navmap
 1511:         if (!defined($navmap)) {
 1512:             $navmap = Apache::lonnavmaps::navmap->new();
 1513: 	    if (!defined($navmap)) {
 1514: 		# no longer in course
 1515: 		return '<span class="LC_error">'.&mt('No course selected').'</span><br />
 1516:                         <a href="/adm/roles">'.&mt('Select a course').'</a><br />';
 1517: 	    }
 1518: 	}
 1519: 
 1520:         # Step two: Locate what kind of here marker is necessary
 1521:         # Determine where the "here" marker is and where the screen jumps to.
 1522: 
 1523:         if ($env{'form.postsymb'} ne '') {
 1524:             $here = $jump = &Apache::lonnet::symbclean($env{'form.postsymb'});
 1525:         } elsif ($env{'form.postdata'} ne '') {
 1526:             # couldn't find a symb, is there a URL?
 1527:             my $currenturl = $env{'form.postdata'};
 1528:             #$currenturl=~s/^http\:\/\///;
 1529:             #$currenturl=~s/^[^\/]+//;
 1530:             unless ($args->{'caller'} eq 'sequence') {
 1531:                 $here = $jump = &Apache::lonnet::symbread($currenturl);
 1532:             }
 1533: 	}
 1534: 	if (($here eq '') && ($args->{'caller'} ne 'sequence')) {
 1535: 	    my $last;
 1536: 	    if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 1537:                     &GDBM_READER(),0640)) {
 1538: 		$last=$hash{'last_known'};
 1539: 		untie(%hash);
 1540: 	    }
 1541: 	    if ($last) { $here = $jump = $last; }
 1542: 	}
 1543: 
 1544:         # Step three: Ensure the folders are open
 1545:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
 1546:         my $curRes;
 1547:         my $found = 0;
 1548:         my $here_is_navmaps = 0; 
 1549:         if ($here =~ m{___\d+___adm/navmaps$}) {
 1550:             $here_is_navmaps = 1;
 1551:         }
 1552:         
 1553:         # We only need to do this if we need to open the maps to show the
 1554:         # current position. This will change the counter so we can't count
 1555:         # for the jump marker with this loop.
 1556:         while ($here && ($curRes = $mapIterator->next()) && !$found && !$here_is_navmaps) {
 1557:             if (ref($curRes) && $curRes->symb() eq $here) {
 1558:                 my $mapStack = $mapIterator->getStack();
 1559:                 
 1560:                 # Ensure the parent maps are open
 1561:                 for my $map (@{$mapStack}) {
 1562:                     if ($condition) {
 1563:                         undef $filterHash->{$map->map_pc()};
 1564:                     } else {
 1565:                         $filterHash->{$map->map_pc()} = 1;
 1566:                     }
 1567:                 }
 1568:                 $found = 1;
 1569:             }
 1570:         }            
 1571:     }        
 1572: 
 1573:     if ( !defined($args->{'iterator'}) && $env{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
 1574:         # If this is a click on a folder or something, we want to preserve the "here"
 1575:         # from the querystring, and get the new "jump" marker
 1576:         $here = $env{'form.here'};
 1577:         $jump = $env{'form.jump'};
 1578:     } 
 1579:     
 1580:     my $it = $args->{'iterator'};
 1581:     if (!defined($it)) {
 1582:         # Construct a default iterator based on $env{'form.'} information
 1583:         
 1584:         # Step 1: Check to see if we have a navmap
 1585:         if (!defined($navmap)) {
 1586:             $navmap = Apache::lonnavmaps::navmap->new();
 1587:             if (!defined($navmap)) {
 1588:                 # no longer in course
 1589:                 return '<span class="LC_error">'.&mt('No course selected').'</span><br />
 1590:                         <a href="/adm/roles">'.&mt('Select a course').'</a><br />';
 1591:             }
 1592:         }
 1593: 
 1594:         # See if we're being passed a specific map
 1595:         if ($args->{'iterator_map'}) {
 1596:             my $map = $args->{'iterator_map'};
 1597:             $map = $navmap->getResourceByUrl($map);
 1598:             if (ref($map)) {
 1599:                 my $firstResource = $map->map_start();
 1600:                 my $finishResource = $map->map_finish();
 1601:                 $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
 1602:             } else {
 1603:                 return;
 1604:             }
 1605:         } else {
 1606:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition,undef,$args->{'include_top_level_map'});
 1607:         }
 1608:     }
 1609: 
 1610:     # (re-)Locate the jump point, if any
 1611:     # Note this does not take filtering or hidden into account... need
 1612:     # to be fixed?
 1613:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
 1614:     my $curRes;
 1615:     my $foundJump = 0;
 1616:     my $counter = 0;
 1617: 
 1618:     while (($curRes = $mapIterator->next()) && !$foundJump) {
 1619:         if (ref($curRes)) { $counter++; }
 1620:         # Speed up display after course initialization
 1621:         # when $jump is empty. Note: we still need
 1622:         # $counter to be 1 in that case if there is at
 1623:         # least one resource.
 1624:         last if (($jump eq '') && ($counter));
 1625: 
 1626:         if (ref($curRes) && $jump eq $curRes->symb()) {
 1627:             
 1628:             # This is why we have to use the main iterator instead of the
 1629:             # potentially faster DFS: The count has to be the same, so
 1630:             # the order has to be the same, which DFS won't give us.
 1631:             $args->{'currentJumpIndex'} = $counter;
 1632:             $foundJump = 1;
 1633:         }
 1634:     }
 1635: 
 1636:     my $showParts = setDefault($args->{'showParts'}, 1);
 1637:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
 1638:     # keeps track of when the current resource is found,
 1639:     # so we can back up a few and put the anchor above the
 1640:     # current resource
 1641:     my $printKey = $args->{'printKey'};
 1642:     my $printCloseAll = $args->{'printCloseAll'};
 1643:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
 1644: 
 1645:     # Print key?
 1646:     if ($printKey) {
 1647:         my $location = &Apache::loncommon::lonhttpdurl("/adm/lonMisc");
 1648:         $legend = '<div class="LC_navtools">'."\n".
 1649:                   '<span class="LC_middle LC_right">'.&mt('Key').':</span>'.
 1650:                   '<span class="LC_middle LC_center">&nbsp;&nbsp;'.
 1651:                   '<img src="'.$location.'/chat.gif" alt="" /> '.&mt('Unread Discussion').
 1652:                   '&nbsp;&nbsp;'.
 1653:                   '<img src="'.$location.'/feedback.gif" alt="" /> '.
 1654:                   &mt('New message (click to open)').
 1655:                   '</span></div>'.
 1656:                   '<div style="padding:0;clear:both;margin:0;border:0"></div>'."\n";
 1657:     }
 1658: 
 1659:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
 1660: 	my ($link,$text);
 1661:         if ($condition) {
 1662: 	    $link='navmaps?condition=0&amp;filter=&amp;'.$queryString.
 1663: 		'&amp;here='.&escape($here);
 1664: 	    $text='Close all folders';
 1665:         } else {
 1666: 	    $link='navmaps?condition=1&amp;filter=&amp;'.$queryString.
 1667: 		'&amp;here='.&escape($here);
 1668: 	    $text='Open all folders';
 1669:         }
 1670: 	if ($args->{'caller'} eq 'navmapsdisplay') {
 1671:             unless ($args->{'notools'}) {
 1672:                 &add_linkitem($args->{'linkitems'},'changefolder',
 1673:                               "location.href='$link'",$text);
 1674:             }
 1675: 	} else {
 1676: 	    $tools = '<a href="'.$link.'">'.&mt($text).'</a>';
 1677: 	}
 1678:         $tools .= "\n";
 1679:     }
 1680: 
 1681:     # Check for any unread discussions in all resources.
 1682:     if (($args->{'caller'} eq 'navmapsdisplay') && (!$args->{'notools'})) {
 1683:         my $markread = 'Mark all posts read';
 1684: 	&add_linkitem($args->{'linkitems'},'clearbubbles',
 1685: 		      'document.clearbubbles.submit()',
 1686: 		      $markread);
 1687: 	my $time=time;
 1688:         my $submit = &mt($markread);
 1689:         my $querystr = &HTML::Entities::encode($ENV{'QUERY_STRING'},'<>&"');
 1690: 	$tools .= (<<END);
 1691:     <form name="clearbubbles" method="post" action="/adm/feedback" aria-hidden="true">
 1692: 	<input type="hidden" name="navurl" value="$querystr" />
 1693: 	<input type="hidden" name="navtime" value="$time" />
 1694: END
 1695:         if ($args->{'sort'} eq 'discussion') {
 1696: 	    my $totdisc = 0;
 1697: 	    my $haveDisc = '';
 1698: 	    my @allres=$navmap->retrieveResources();
 1699: 	    foreach my $resource (@allres) {
 1700: 		if ($resource->hasDiscussion()) {
 1701: 		    $haveDisc .= $resource->wrap_symb().':';
 1702: 		    $totdisc ++;
 1703: 		}
 1704: 	    }
 1705: 	    if ($totdisc > 0) {
 1706: 		$haveDisc =~ s/:$//;
 1707: 		$tools .= (<<END);
 1708: 	<input type="hidden" name="navmaps" value="$haveDisc" />
 1709: END
 1710:             }
 1711: 	}
 1712: 	$tools .= <<END;
 1713:         <input type="submit" value="$submit" class="LC_visually_hidden" tabindex="-1" disabled="disabled" />
 1714:     </form>
 1715: END
 1716:     }
 1717:     if (($args->{'caller'} eq 'navmapsdisplay') && ($env{'request.course.id'})) {
 1718:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1719:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1720:         if ($env{'course.'.$env{'request.course.id'}.'.url'} eq
 1721:             "uploaded/$cdom/$cnum/default.sequence") {
 1722:             if ((&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) ||
 1723:                 (&Apache::lonnet::allowed('cev',$env{'request.course.id'}))) {
 1724:                 &add_linkitem($args->{'linkitems'},'edittoplevel',
 1725:                               "javascript:gocmd('/adm/coursedocs','editdocs');",
 1726:                               'Content Editor');
 1727:             }
 1728:             if ($counter) {
 1729:                 &add_linkitem($args->{'linkitems'},'printout',
 1730:                               "javascript:gopost('/adm/printout','/adm/navmaps');",
 1731:                               'Prepare a printable document');
 1732:             }
 1733:         }
 1734:     }
 1735: 
 1736:     if ($args->{'caller'} eq 'navmapsdisplay') {
 1737:         $tools .= &show_linkitems_toolbar($args,$condition);
 1738:     } elsif ($args->{'sort_html'}) { 
 1739:         $tools .= $args->{'sort_html'}; 
 1740:     }
 1741: 
 1742:     #$tools .= "<br />\n";
 1743:     # End parameter setting
 1744: 
 1745:     # Data
 1746: 
 1747:     my $res = "Apache::lonnavmaps::resource";
 1748:     my %condenseStatuses =
 1749:         ( $res->NETWORK_FAILURE    => 1,
 1750:           $res->NOTHING_SET        => 1,
 1751:           $res->CORRECT            => 1 );
 1752: 
 1753:     # Shared variables
 1754:     $args->{'counter'} = 0; # counts the rows
 1755:     $args->{'indentLevel'} = 0;
 1756:     $args->{'isNewBranch'} = 0;
 1757:     $args->{'condensed'} = 0;
 1758:     $args->{'deeplinknolist'} = 0;
 1759: 
 1760:     my $location = &Apache::loncommon::lonhttpdurl("/adm/lonIcons/whitespace_21.gif");
 1761:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='$location' alt='' />");
 1762:     $args->{'displayedHereMarker'} = 0;
 1763: 
 1764:     # If we're suppressing empty sequences, look for them here.
 1765:     # We also do this even if $args->{'suppressEmptySequences'}
 1766:     # is not true, so we can hide empty sequences for which the
 1767:     # hiddenresource parameter is set to yes (at map level), or
 1768:     # mark as hidden for users who have $userCanSeeHidden.  
 1769:     # Use DFS for speed, since structure actually doesn't matter,
 1770:     # except what map has what resources.
 1771:     #
 1772:     # To ensure the "Selected Resources from selected folder in course"
 1773:     # printout generation option will work in sessions launched via a
 1774:     # deep link, the value of $args->{'filterFunc'} included in the 
 1775:     # call to lonnavmaps::render() is omitted from the filter function
 1776:     # used with the DFS Iterator when $args->{'caller'} is 'printout'.
 1777:     #
 1778:     # As a result $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} can be
 1779:     # set to 1 for folder(s) which include resources only accessible
 1780:     # for sessions launched via a deep link, when the current session 
 1781:     # is of that type.
 1782: 
 1783:     my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
 1784:                                                      $it->{FIRST_RESOURCE},
 1785:                                                      $it->{FINISH_RESOURCE},
 1786:                                                      {}, undef, 1);
 1787:     my $dfsFilterFunc;
 1788:     if ($args->{'caller'} eq 'printout') {
 1789:         $dfsFilterFunc = sub { my $res = shift; return !$res->randomout() &&
 1790:                               ($res->deeplink($args->{'caller'}) ne 'absent') &&
 1791:                               ($res->deeplink($args->{'caller'}) ne 'grades') &&
 1792:                               !$res->deeplinkout();};
 1793:     } else {
 1794:         $dfsFilterFunc = $filterFunc;
 1795:     }
 1796:     my $depth = 0;
 1797:     $dfsit->next();
 1798:     my $curRes = $dfsit->next();
 1799:     while ($depth > -1) {
 1800:         if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
 1801:         if ($curRes == $dfsit->END_MAP()) { $depth--; }
 1802: 
 1803:         if (ref($curRes)) { 
 1804:             # Parallel pre-processing: Do sequences have non-filtered-out children?
 1805:             if ($curRes->is_map()) {
 1806:                 $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
 1807:                 # Sequences themselves do not count as visible children,
 1808:                 # unless those sequences also have visible children.
 1809:                 # This means if a sequence appears, there's a "promise"
 1810:                 # that there's something under it if you open it, somewhere.
 1811:             } elsif ($curRes->src()) {
 1812:                 # Not a sequence: if it's filtered, ignore it, otherwise
 1813:                 # rise up the stack and mark the sequences as having children
 1814:                 if (&$dfsFilterFunc($curRes)) {
 1815:                     for my $sequence (@{$dfsit->getStack()}) {
 1816:                         next unless ($sequence->is_map());
 1817:                         $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
 1818:                     }
 1819:                 }
 1820:             }
 1821:         }
 1822:     } continue {
 1823:         $curRes = $dfsit->next();
 1824:     }
 1825: 
 1826:     my $displayedJumpMarker = 0;
 1827:     # Set up iteration.
 1828:     my $now = time();
 1829:     my $in24Hours = $now + 24 * 60 * 60;
 1830:     my $rownum = 0;
 1831: 
 1832:     # export "here" marker information
 1833:     $args->{'here'} = $here;
 1834: 
 1835:     $args->{'indentLevel'} = -1; # first BEGIN_MAP takes this to 0
 1836:     my @resources;
 1837:     my $code='';# sub { !(shift->is_map();) };
 1838:     if ($args->{'sort'} eq 'title') {
 1839:         my $oldFilterFunc = $filterFunc;
 1840: 	my $filterFunc= 
 1841: 	    sub {
 1842: 		my ($res)=@_;
 1843: 		if ($res->is_map()) { return 0;}
 1844: 		return &$oldFilterFunc($res);
 1845: 	    };
 1846: 	@resources=$navmap->retrieveResources(undef,$filterFunc);
 1847: 	@resources= sort { &cmp_title($a,$b) } @resources;
 1848:     } elsif ($args->{'sort'} eq 'duedate') {
 1849: 	my $oldFilterFunc = $filterFunc;
 1850: 	my $filterFunc= 
 1851: 	    sub {
 1852: 		my ($res)=@_;
 1853: 		if (!$res->is_problem()) { return 0;}
 1854: 		return &$oldFilterFunc($res);
 1855: 	    };
 1856: 	@resources=$navmap->retrieveResources(undef,$filterFunc);
 1857: 	@resources= sort {
 1858: 	    if ($a->duedate ne $b->duedate) {
 1859: 	        return $a->duedate cmp $b->duedate;
 1860: 	    }
 1861: 	    my $value=&cmp_title($a,$b);
 1862: 	    return $value;
 1863: 	} @resources;
 1864:     } elsif ($args->{'sort'} eq 'discussion') {
 1865: 	my $oldFilterFunc = $filterFunc;
 1866: 	my $filterFunc= 
 1867: 	    sub {
 1868: 		my ($res)=@_;
 1869: 		if (!$res->hasDiscussion() &&
 1870: 		    !$res->getFeedback() &&
 1871: 		    !$res->getErrors()) { return 0;}
 1872: 		return &$oldFilterFunc($res);
 1873: 	    };
 1874: 	@resources=$navmap->retrieveResources(undef,$filterFunc);
 1875: 	@resources= sort { &cmp_title($a,$b) } @resources;
 1876:     } else {
 1877: 	#unknow sort mechanism or default
 1878: 	undef($args->{'sort'});
 1879:     }
 1880: 
 1881:     # Determine if page will be served with https in case
 1882:     # it contains a syllabus which uses an external URL
 1883:     # which points at an http site.
 1884: 
 1885:     my ($is_ssl,$cdom,$cnum,$hostname);
 1886:     if ($ENV{'SERVER_PORT'} == 443) {
 1887:         $is_ssl = 1;
 1888:         if ($r) {
 1889:             $hostname = $r->hostname();
 1890:         } else {
 1891:             $hostname = $ENV{'SERVER_NAME'};
 1892:         }
 1893:     }
 1894:     if ($env{'request.course.id'}) {
 1895:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1896:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1897:     }
 1898: 
 1899:     my $inhibitmenu;
 1900:     if ($args->{'modalLink'}) {
 1901:         $inhibitmenu = '&amp;inhibitmenu=yes';
 1902:     }
 1903: 
 1904:     while (1) {
 1905: 	if ($args->{'sort'}) {
 1906: 	    $curRes = shift(@resources);
 1907: 	} else {
 1908: 	    $curRes = $it->next($closeAllPages);
 1909: 	}
 1910: 	if (!$curRes) { last; }
 1911: 
 1912:         # Maintain indentation level.
 1913:         if ($curRes == $it->BEGIN_MAP() ||
 1914:             $curRes == $it->BEGIN_BRANCH() ) {
 1915:             $args->{'indentLevel'}++;
 1916:         }
 1917:         if ($curRes == $it->END_MAP() ||
 1918:             $curRes == $it->END_BRANCH() ) {
 1919:             $args->{'indentLevel'}--;
 1920:         }
 1921:         # Notice new branches
 1922:         if ($curRes == $it->BEGIN_BRANCH()) {
 1923:             $args->{'isNewBranch'} = 1;
 1924:         }
 1925: 
 1926:         # If this isn't an actual resource, continue on
 1927:         if (!ref($curRes)) {
 1928:             next;
 1929:         }
 1930: 
 1931:         # If this has been filtered out, continue on
 1932:         if (!(&$filterFunc($curRes))) {
 1933:             if (!$userCanSeeHidden && !$curRes->randomout && $curRes->deeplinkout) {
 1934:                 $args->{'deeplinknolist'} ++;
 1935:             }
 1936:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
 1937:             next;
 1938:         } 
 1939: 
 1940:         # If this is an empty sequence and we're filtering them, continue on
 1941:         $args->{'mapHidden'} = 0;
 1942:         $args->{'mapUnlisted'} = 0;
 1943:         $args->{'mapHiddenDeepLink'} = 0;
 1944:         if (($curRes->is_map()) && (!$curRes->{DATA}->{HAS_VISIBLE_CHILDREN})) {
 1945:             if ($args->{'suppressEmptySequences'}) {
 1946:                 next;
 1947:             } else {
 1948:                 my $mapname = &Apache::lonnet::declutter($curRes->src());
 1949:                 $mapname = &Apache::lonnet::deversion($mapname); 
 1950:                 if (lc($navmap->get_mapparam(undef,$mapname,"0.hiddenresource")) eq 'yes') {
 1951:                     if ($userCanSeeHidden) {
 1952:                         $args->{'mapHidden'} = 1;
 1953:                     } else {
 1954:                         next;
 1955:                     }
 1956:                 } elsif ($curRes->deeplinkout) {
 1957:                     if ($userCanSeeHidden) {
 1958:                         $args->{'mapHiddenDeepLink'} = 1;
 1959:                     } else {
 1960:                         $args->{'deeplinknolist'} ++;
 1961:                         next;
 1962:                     }
 1963:                 } else {
 1964:                     my $deeplink = $navmap->get_mapparam(undef,$mapname,"0.deeplink");
 1965:                     my ($state,$others,$listed) = split(/,/,$deeplink);
 1966:                     if (($listed eq 'absent') || ($listed eq 'grades')) {
 1967:                         if ($userCanSeeHidden) {
 1968:                             $args->{'mapUnlisted'} = 1;
 1969:                         } else {
 1970:                             $args->{'deeplinknolist'} ++;
 1971:                             next;
 1972:                         }
 1973:                     }
 1974:                 }
 1975:             }
 1976:         }
 1977: 
 1978:         # If we're suppressing navmaps and this is a navmap, continue on
 1979:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
 1980:             next;
 1981:         }
 1982: 
 1983:         $args->{'counter'}++;
 1984:         unless ($tablestarted) {
 1985:             $result.=&Apache::loncommon::start_data_table("LC_tableOfContent").
 1986:                      &Apache::loncommon::start_data_table_header_row('LC_visually_hidden').
 1987:                      '<th>'.&mt('Resource or Folder').'</th>'.
 1988:                      '<th>'.&mt('Alerts').'</th>'.
 1989:                      '<th>'.&mt('Status Icon').'</th>'.
 1990:                      '<th>'.&mt('Date/Completion Status').'</th>'.
 1991:                      &Apache::loncommon::end_data_table_row()."\n";
 1992:                      $tablestarted = 1;
 1993:         }
 1994: 
 1995:         # Does it have multiple parts?
 1996:         $args->{'multipart'} = 0;
 1997:         $args->{'condensed'} = 0;
 1998:         my @parts;
 1999:             
 2000:         # Decide what parts to show.
 2001:         if ($curRes->is_problem() && $showParts) {
 2002:             @parts = @{$curRes->parts()};
 2003:             $args->{'multipart'} = $curRes->multipart();
 2004:             
 2005:             if ($condenseParts) { # do the condensation
 2006:                 if (!$args->{'condensed'}) {
 2007:                     # Decide whether to condense based on similarity
 2008:                     my $status = $curRes->status($parts[0]);
 2009:                     my $due = $curRes->duedate($parts[0]);
 2010:                     my $open = $curRes->opendate($parts[0]);
 2011:                     my $statusAllSame = 1;
 2012:                     my $dueAllSame = 1;
 2013:                     my $openAllSame = 1;
 2014:                     for (my $i = 1; $i < scalar(@parts); $i++) {
 2015:                         if ($curRes->status($parts[$i]) != $status){
 2016:                             $statusAllSame = 0;
 2017:                         }
 2018:                         if ($curRes->duedate($parts[$i]) != $due ) {
 2019:                             $dueAllSame = 0;
 2020:                         }
 2021:                         if ($curRes->opendate($parts[$i]) != $open) {
 2022:                             $openAllSame = 0;
 2023:                         }
 2024:                     }
 2025:                     # $*allSame is true if all the statuses were
 2026:                     # the same. Now, if they are all the same and
 2027:                     # match one of the statuses to condense, or they
 2028:                     # are all open with the same due date, or they are
 2029:                     # all OPEN_LATER with the same open date, display the
 2030:                     # status of the first non-zero part (to get the 'correct'
 2031:                     # status right, since 0 is never 'correct' or 'open').
 2032:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
 2033:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
 2034:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
 2035:                         @parts = ($parts[0]);
 2036:                         $args->{'condensed'} = 1;
 2037:                     }
 2038:                 }
 2039: 		# Multipart problem with one part: always "condense" (happens
 2040: 		#  to match the desirable behavior)
 2041: 		if ($curRes->countParts() == 1) {
 2042: 		    @parts = ($parts[0]);
 2043: 		    $args->{'condensed'} = 1;
 2044: 		}
 2045:             }
 2046:         }
 2047:         # If deep-link parameter is set (and is not set to full) suppress link
 2048:         # unless privileged user, tinyurl used for login resolved to a map, and
 2049:         # the resource is within the map.
 2050:         if ((!$curRes->deeplink($args->{'caller'})) ||
 2051:             ($curRes->deeplink($args->{'caller'}) eq 'full') || &advancedUser()) {
 2052:             $args->{'resource_nolink'} = 0;
 2053:         } else {
 2054:             $args->{'resource_nolink'} = 1;
 2055:         }
 2056: 
 2057:         # If the multipart problem was condensed, "forget" it was multipart
 2058:         if (scalar(@parts) == 1) {
 2059:             $args->{'multipart'} = 0;
 2060:         } else {
 2061:             # Add part 0 so we display it correctly.
 2062:             unshift @parts, '0';
 2063:         }
 2064: 	
 2065: 	{
 2066: 	    my ($src,$symb,$anchor,$stack);
 2067: 	    if ($args->{'sort'}) {
 2068: 		my $it = $navmap->getIterator(undef, undef, undef, 1);
 2069: 		while ( my $res=$it->next()) {
 2070: 		    if (ref($res) &&
 2071: 			$res->symb() eq  $curRes->symb()) { last; }
 2072: 		}
 2073: 		$stack=$it->getStack();
 2074: 	    } else {
 2075: 		$stack=$it->getStack();
 2076: 	    }
 2077: 	    ($src,$symb,$anchor)=getLinkForResource($stack);
 2078:             my $srcHasQuestion = $src =~ /\?/;
 2079:             if ($env{'request.course.id'}) {
 2080:                 if (($is_ssl) && ($src =~ m{^\Q/public/$cdom/$cnum/syllabus\E($|\?)}) &&
 2081:                     ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 2082:                     unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 2083:                         if ($hostname ne '') {
 2084:                             $src = 'http://'.$hostname.$src;
 2085:                         }
 2086:                         $src .= ($srcHasQuestion? '&amp;' : '?') . 'usehttp=1';
 2087:                         $srcHasQuestion = 1;
 2088:                     }
 2089:                 } elsif (($is_ssl) && ($src =~ m{^\Q/adm/wrapper/ext/\E(?!https:)})) {
 2090:                     unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 2091:                         if ($hostname ne '') {
 2092:                             $src = 'http://'.$hostname.$src;
 2093:                         }
 2094:                         $src .= ($srcHasQuestion? '&amp;' : '?') . 'usehttp=1';
 2095:                         $srcHasQuestion = 1;
 2096:                     }
 2097:                 }
 2098:             }
 2099: 	    if (defined($anchor)) { $anchor='#'.$anchor; }
 2100: 	    if (($args->{'caller'} eq 'sequence') && ($curRes->is_map())) {
 2101: 	        $args->{"resourceLink"} = $src.($srcHasQuestion?'&amp;':'?') .'navmap=1';
 2102: 	    } else {
 2103: 	        $args->{"resourceLink"} = $src.
 2104: 		    ($srcHasQuestion?'&amp;':'?') .
 2105: 		    'symb=' . &escape($symb).$inhibitmenu.$anchor;
 2106: 	    }
 2107: 	}
 2108:         # Now, we've decided what parts to show. Loop through them and
 2109:         # show them.
 2110:         foreach my $part (@parts) {
 2111:             $rownum ++;
 2112:             
 2113:             $result .= &Apache::loncommon::start_data_table_row();
 2114: 
 2115:             # Set up some data about the parts that the cols might want
 2116:             my $filter = $it->{FILTER};
 2117: 
 2118:             # Now, display each column.
 2119:             foreach my $col (@$cols) {
 2120:                 my $colHTML = '';
 2121:                 if (ref($col)) {
 2122:                     $colHTML .= &$col($curRes, $part, $args);
 2123:                 } else {
 2124:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
 2125:                 }
 2126: 
 2127:                 # If this is the first column and it's time to print
 2128:                 # the anchor, do so
 2129:                 if ($col == $cols->[0] && 
 2130:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
 2131:                     $currentJumpDelta) {
 2132:                     # Jam the anchor after the <td> tag;
 2133:                     # necessary for valid HTML (which Mozilla requires)
 2134:                     $colHTML =~ s/\>/\>\<a name="curloc" \>\<\/a\>/;
 2135:                     $displayedJumpMarker = 1;
 2136:                 }
 2137:                 $result .= $colHTML . "\n";
 2138:             }
 2139:             $result .= &Apache::loncommon::end_data_table_row();
 2140:             $args->{'isNewBranch'} = 0;
 2141:         }
 2142: 
 2143:         if ($r && $rownum % 20 == 0) {
 2144:             unless ($tools_printed) {
 2145:                 $r->print($legend.$tools);
 2146:                 $legend = "";
 2147:                 $tools = "";
 2148:                 $tools_printed = 1;
 2149:             }
 2150:             $r->print($result);
 2151:             $result = "";
 2152:             $r->rflush();
 2153:         }
 2154:     } continue {
 2155: 	if ($r) {
 2156: 	    # If we have the connection, make sure the user is still connected
 2157: 	    my $c = $r->connection;
 2158: 	    if ($c->aborted()) {
 2159: 		# Who cares what we do, nobody will see it anyhow.
 2160: 		return '';
 2161: 	    }
 2162: 	}
 2163:     }
 2164: 
 2165:     if ($tablestarted) {
 2166:         $result .= &Apache::loncommon::end_data_table();
 2167:     }
 2168:     
 2169:     # Print out the part that jumps to #curloc if it exists
 2170:     # delay needed because the browser is processing the jump before
 2171:     # it finishes rendering, so it goes to the wrong place!
 2172:     # onload might be better, but this routine has no access to that.
 2173:     # On mozilla, the 0-millisecond timeout seems to prevent this;
 2174:     # it's quite likely this might fix other browsers, too, and 
 2175:     # certainly won't hurt anything.
 2176:     if ($displayedJumpMarker) {
 2177:         $result .= &Apache::lonhtmlcommon::scripttag("
 2178: if (location.href.indexOf('#curloc')==-1) {
 2179:     setTimeout(\"location += '#curloc';\", 0)
 2180: }
 2181: ");
 2182:     }
 2183: 
 2184:     if ($r) {
 2185:         unless ($tools_printed) {
 2186:             if (($args->{'counter'}) || ($userCanSeeHidden) ||
 2187:                 (($args->{'caller'} eq 'navmapsdisplay') &&
 2188:                  ($env{'form.showOnlyHomework'} ||
 2189:                   $ENV{QUERY_STRING} =~ /^jumpToFirstHomework/))) {
 2190:                 $r->print($legend.$tools);
 2191:             }
 2192:             $legend = "";
 2193:             $tools = "";
 2194:             $tools_printed = 1;
 2195:         }
 2196:         $r->print($result);
 2197:         $result = "";
 2198:         $r->rflush();
 2199:     }
 2200:         
 2201:     return $legend.$tools.$result;
 2202: }
 2203: 
 2204: sub add_linkitem {
 2205:     my ($linkitems,$name,$cmd,$text)=@_;
 2206:     $$linkitems{$name}{'cmd'}=$cmd;
 2207:     $$linkitems{$name}{'text'}=&mt($text);
 2208: }
 2209: 
 2210: sub show_linkitems_toolbar {
 2211:     my ($args,$condition) = @_;
 2212:     my $result;
 2213:     if (ref($args) eq 'HASH') {
 2214:         if (ref($args->{'linkitems'}) eq 'HASH') {
 2215:             my $numlinks = scalar(keys(%{$args->{'linkitems'}}));
 2216:             if ($numlinks > 1) {
 2217:                 $result = '<div class="LC_navtools">'.
 2218:                           &Apache::loncommon::help_open_menu('Navigation Screen','Navigation_Screen',
 2219:                                                              undef,'RAT').
 2220:                           '</div><div class="LC_navtools">&nbsp;'.&mt('Tools:').'</div>';
 2221:             }
 2222:             $result .= '<div class="LC_navtools">'."\n".
 2223:                        '<ul id="LC_toolbar">';
 2224:             my @linkorder = ('firsthomework','everything','uncompleted',
 2225:                              'changefolder','clearbubbles','printout','edittoplevel');
 2226:             foreach my $link (@linkorder) {
 2227:                 if (ref($args->{'linkitems'}{$link}) eq 'HASH') {
 2228:                     if ($args->{'linkitems'}{$link}{'text'} ne '') {
 2229:                         $args->{'linkitems'}{$link}{'cmd'}=~s/"/'/g;
 2230:                         if ($args->{'linkitems'}{$link}{'cmd'}) {
 2231:                             my $link_id = 'LC_content_toolbar_'.$link;
 2232:                             if ($link eq 'changefolder') {
 2233:                                 if ($condition) {
 2234:                                     $link_id='LC_content_toolbar_changefolder_toggled';
 2235:                                 } else {
 2236:                                     $link_id='LC_content_toolbar_changefolder';
 2237:                                 }
 2238:                             }
 2239:                             $result .= '<li><a href="#" '.
 2240:                                        'onclick="'.$args->{'linkitems'}{$link}{'cmd'}.'" '.
 2241:                                        'id="'.$link_id.'" '.
 2242:                                        'class="LC_toolbarItem" '.
 2243:                                        'title="'.$args->{'linkitems'}{$link}{'text'}.'">'.
 2244:                                        '</a></li>'."\n";
 2245:                         }
 2246:                     }
 2247:                 }
 2248:             }
 2249:             $result .= '</ul>'.
 2250:                        '</div>';
 2251:             if (($numlinks==1) && (exists($args->{'linkitems'}{'edittoplevel'}))) {
 2252:                 $result .= '<div class="LC_navtools">'.
 2253:                            '&nbsp;<a href="'.$args->{'linkitems'}{'edittoplevel'}{'cmd'}.'">'.
 2254:                            &mt('Content Editor').'</a></div>';
 2255:             }
 2256:         }
 2257:         if ($args->{'sort_html'}) {
 2258:             $result .= '<div class="LC_navtools">&nbsp;&nbsp;&nbsp;'.
 2259:                        $args->{'sort_html'}.'</div>';
 2260:         }
 2261:     }
 2262:     if ($result) {
 2263:         $result = '<div class="LC_navtools">'.$result.'</div>'."\n".
 2264:                   '<div style="padding:0;clear:both;margin:0;border:0"></div>'."\n";
 2265:     }
 2266:     return $result;
 2267: }
 2268: 
 2269: 1;
 2270: 
 2271: 
 2272: 
 2273: 
 2274: 
 2275: 
 2276: 
 2277: 
 2278: 
 2279: package Apache::lonnavmaps::navmap;
 2280: 
 2281: =pod
 2282: 
 2283: =head1 Object: Apache::lonnavmaps::navmap
 2284: 
 2285: =head2 Overview
 2286: 
 2287: The navmap object's job is to provide access to the resources
 2288: in the course as Apache::lonnavmaps::resource objects, and to
 2289: query and manage the relationship between those resource objects.
 2290: 
 2291: Generally, you'll use the navmap object in one of three basic ways.
 2292: In order of increasing complexity and power:
 2293: 
 2294: =over 4
 2295: 
 2296: =item * C<$navmap-E<gt>getByX>, where X is B<Id>, B<Symb> or B<MapPc> and getResourceByUrl. This provides
 2297:     various ways to obtain resource objects, based on various identifiers.
 2298:     Use this when you want to request information about one object or 
 2299:     a handful of resources you already know the identities of, from some
 2300:     other source. For more about Ids, Symbs, and MapPcs, see the
 2301:     Resource documentation. Note that Url should be a B<last resort>,
 2302:     not your first choice; it only really works when there is only one
 2303:     instance of the resource in the course, which only applies to
 2304:     maps, and even that may change in the future (see the B<getResourceByUrl>
 2305:     documentation for more details.)
 2306: 
 2307: =item * C<my @resources = $navmap-E<gt>retrieveResources(args)>. This
 2308:     retrieves resources matching some criterion and returns them
 2309:     in a flat array, with no structure information. Use this when
 2310:     you are manipulating a series of resources, based on what map
 2311:     the are in, but do not care about branching, or exactly how
 2312:     the maps and resources are related. This is the most common case.
 2313: 
 2314: =item * C<$it = $navmap-E<gt>getIterator(args)>. This allows you traverse
 2315:     the course's navmap in various ways without writing the traversal
 2316:     code yourself. See iterator documentation below. Use this when
 2317:     you need to know absolutely everything about the course, including
 2318:     branches and the precise relationship between maps and resources.
 2319: 
 2320: =back
 2321: 
 2322: =head2 Creation And Destruction
 2323: 
 2324: To create a navmap object, use the following function:
 2325: 
 2326: =over 4
 2327: 
 2328: =item * B<Apache::lonnavmaps::navmap-E<gt>new>():
 2329: 
 2330: Creates a new navmap object. Returns the navmap object if this is
 2331: successful, or B<undef> if not.
 2332: 
 2333: =back
 2334: 
 2335: =head2 Methods
 2336: 
 2337: =over 4
 2338: 
 2339: =item * B<getIterator>(first, finish, filter, condition):
 2340: 
 2341: See iterator documentation below.
 2342: 
 2343: =cut
 2344: 
 2345: use strict;
 2346: use GDBM_File;
 2347: use Apache::lonnet;
 2348: use LONCAPA;
 2349: 
 2350: sub new {
 2351:     # magic invocation to create a class instance
 2352:     my $proto = shift;
 2353:     my $class = ref($proto) || $proto;
 2354:     my $self = {};
 2355:     bless($self);		# So we can call change_user if necessary
 2356: 
 2357:     $self->{USERNAME} = shift || $env{'user.name'};
 2358:     $self->{DOMAIN}   = shift || $env{'user.domain'};
 2359:     $self->{SECTION}  = shift;
 2360:     $self->{CODE}     = shift;
 2361:     $self->{NOHIDE}   = shift;
 2362: 
 2363: 
 2364:     if (($self->{SECTION} eq '') && ($env{'request.course.sec'} ne '')) {
 2365:         if (($self->{USERNAME} eq $env{'user.name'}) &&
 2366:             ($self->{USERNAME} eq $env{'user.domain'})) {
 2367:             $self->{SECTION} = $env{'request.course.sec'};
 2368:         }
 2369:     }
 2370: 
 2371:     # Resource cache stores navmap resources as we reference them. We generate
 2372:     # them on-demand so we don't pay for creating resources unless we use them.
 2373:     $self->{RESOURCE_CACHE} = {};
 2374: 
 2375:     # Network failure flag, if we accessed the course or user opt and
 2376:     # failed
 2377:     $self->{NETWORK_FAILURE} = 0;
 2378: 
 2379:     # We can only tie the nav hash as done below if the username/domain
 2380:     # match the env one. Otherwise change_user does everything we need...since we can't
 2381:     # assume there are course hashes for the specific requested user:domain
 2382:     # Note: change_user is also called if we need the nav hash when printing CODEd 
 2383:     # assignments or printing an exam, in which the enclosing folder for the items in
 2384:     # the exam has hidden set.
 2385:     #
 2386: 
 2387:     if (($self->{USERNAME} eq $env{'user.name'}) && ($self->{DOMAIN} eq $env{'user.domain'}) &&
 2388:          !$self->{CODE} && !$self->{NOHIDE}) {
 2389: 	
 2390: 	# tie the nav hash
 2391: 	
 2392: 	my %navmaphash;
 2393: 	my %parmhash;
 2394: 	my $courseFn = $env{"request.course.fn"};
 2395: 	if (!(tie(%navmaphash, 'GDBM_File', "${courseFn}.db",
 2396: 		  &GDBM_READER(), 0640))) {
 2397: 	    return undef;
 2398: 	}
 2399: 	
 2400: 	if (!(tie(%parmhash, 'GDBM_File', "${courseFn}_parms.db",
 2401: 		  &GDBM_READER(), 0640)))
 2402: 	{
 2403: 	    untie %{$self->{PARM_HASH}};
 2404: 	    return undef;
 2405: 	}
 2406: 	
 2407: 	$self->{NAV_HASH} = \%navmaphash;
 2408: 	$self->{PARM_HASH} = \%parmhash;
 2409: 	$self->{PARM_CACHE} = {};
 2410:     } else {
 2411: 	$self->change_user($self->{USERNAME}, $self->{DOMAIN}, $self->{SECTION}, $self->{CODE}, $self->{NOHIDE});
 2412:     }
 2413: 
 2414:     return $self;
 2415: }
 2416: 
 2417: #
 2418: #  In some instances it is useful to be able to dynamically change the
 2419: # username/domain associated with a navmap (e.g. to navigate for someone
 2420: # else besides the current user...if sufficiently privileged.
 2421: # Parameters:
 2422: #    user    - New user.
 2423: #    domain  - Domain to which the user belongs.
 2424: #    section - Section to which the user belongs.
 2425: #    code    - Anonymous CODE in use.
 2426: # Implicit inputs:
 2427: #   
 2428: sub change_user {
 2429:     my $self = shift;
 2430:     $self->{USERNAME} = shift;
 2431:     $self->{DOMAIN}   = shift;
 2432:     $self->{SECTION}  = shift;
 2433:     $self->{CODE}     = shift;
 2434:     $self->{NOHIDE}   = shift;
 2435: 
 2436:     # If the hashes are already tied make sure to break that bond:
 2437: 
 2438:     untie %{$self->{NAV_HASH}}; 
 2439:     untie %{$self->{PARM_HASH}};
 2440: 
 2441:     # The assumption is that we have to
 2442:     # use lonmap here to re-read the hash and from it reconstruct
 2443:     # new big and parameter hashes.  An implicit assumption at this time
 2444:     # is that the course file is probably not created locally yet
 2445:     # an that we will therefore just read without tying.
 2446: 
 2447:     my ($cdom, $cnum) = split(/\_/, $env{'request.course.id'});
 2448: 
 2449:     my %big_hash;
 2450:     &Apache::lonmap::loadmap($cnum, $cdom, $self->{USERNAME}, $self->{DOMAIN}, $self->{CODE}, $self->{NOHIDE}, \%big_hash);
 2451:     $self->{NAV_HASH} = \%big_hash;
 2452: 
 2453: 
 2454: 
 2455:     # Now clear the parm cache and reconstruct the parm hash from the big_hash
 2456:     # param.xxxx keys.
 2457: 
 2458:     $self->{PARM_CACHE} = {};
 2459:     
 2460:     my %parm_hash = {};
 2461:     foreach my $key (keys(%big_hash)) {
 2462: 	if ($key =~ /^param\./) {
 2463: 	    my $param_key = $key;
 2464: 	    $param_key =~ s/^param\.//;
 2465: 	    $parm_hash{$param_key} = $big_hash{$key};
 2466: 	}
 2467:     }
 2468: 
 2469:     $self->{PARM_HASH} = \%parm_hash;
 2470: 
 2471: }
 2472: 
 2473: sub generate_course_user_opt {
 2474:     my $self = shift;
 2475:     if ($self->{COURSE_USER_OPT_GENERATED}) { return; }
 2476: 
 2477:     my $uname=$self->{USERNAME};
 2478:     my $udom=$self->{DOMAIN};
 2479: 
 2480:     my $cid=$env{'request.course.id'};
 2481:     my $cdom=$env{'course.'.$cid.'.domain'};
 2482:     my $cnum=$env{'course.'.$cid.'.num'};
 2483:     
 2484: # ------------------------------------------------- Get coursedata (if present)
 2485:     my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
 2486:     # Check for network failure
 2487:     if (!ref($courseopt)) {
 2488: 	if ( $courseopt =~ /no.such.host/i || $courseopt =~ /con_lost/i) {
 2489: 	    $self->{NETWORK_FAILURE} = 1;
 2490: 	}
 2491: 	undef($courseopt);
 2492:     }
 2493: 
 2494: # --------------------------------------------------- Get userdata (if present)
 2495: 	
 2496:     my $useropt=&Apache::lonnet::get_userresdata($uname,$udom);
 2497:     # Check for network failure
 2498:     if (!ref($useropt)) {
 2499: 	if ( $useropt =~ /no.such.host/i || $useropt =~ /con_lost/i) {
 2500: 	    $self->{NETWORK_FAILURE} = 1;
 2501: 	}
 2502: 	undef($useropt);
 2503:     }
 2504: 
 2505:     $self->{COURSE_OPT} = $courseopt;
 2506:     $self->{USER_OPT} = $useropt;
 2507: 
 2508:     $self->{COURSE_USER_OPT_GENERATED} = 1;
 2509:     
 2510:     return;
 2511: }
 2512: 
 2513: 
 2514: 
 2515: sub generate_email_discuss_status {
 2516:     my $self = shift;
 2517:     my $symb = shift;
 2518:     if ($self->{EMAIL_DISCUSS_GENERATED}) { return; }
 2519: 
 2520:     my $cid=$env{'request.course.id'};
 2521:     my $cdom=$env{'course.'.$cid.'.domain'};
 2522:     my $cnum=$env{'course.'.$cid.'.num'};
 2523:     
 2524:     my %emailstatus = &Apache::lonnet::dump('email_status',$self->{DOMAIN},$self->{USERNAME});
 2525:     my $logoutTime = $emailstatus{'logout'};
 2526:     my $courseLeaveTime = $emailstatus{'logout_'.$env{'request.course.id'}};
 2527:     $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
 2528: 			   $courseLeaveTime : $logoutTime);
 2529:     my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 2530: 					       $cdom, $cnum);
 2531:     my %lastread = &Apache::lonnet::dump('nohist_'.$cid.'_discuss',
 2532:                                         $self->{DOMAIN},$self->{USERNAME},'lastread');
 2533:     my %lastreadtime = ();
 2534:     foreach my $key (keys(%lastread)) {
 2535:         my $shortkey = $key;
 2536:         $shortkey =~ s/_lastread$//;
 2537:         $lastreadtime{$shortkey} = $lastread{$key};
 2538:     }
 2539: 
 2540:     my %feedback=();
 2541:     my %error=();
 2542:     my @keys = &Apache::lonnet::getkeys('nohist_email',$self->{DOMAIN},
 2543: 					$self->{USERNAME});
 2544:     
 2545:     foreach my $msgid (@keys) {
 2546: 	if ((!$emailstatus{$msgid}) || ($emailstatus{$msgid} eq 'new')) {
 2547:             my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
 2548:                 $symb,$error) = &Apache::lonmsg::unpackmsgid(&LONCAPA::escape($msgid));
 2549:             &Apache::lonenc::check_decrypt(\$symb); 
 2550:             if (($fromcid ne '') && ($fromcid ne $cid)) {
 2551:                 next;
 2552:             }
 2553:             if (defined($symb)) {
 2554:                 if (defined($error) && $error == 1) {
 2555:                     $error{$symb}.=','.$msgid;
 2556:                 } else {
 2557:                     $feedback{$symb}.=','.$msgid;
 2558:                 }
 2559:             } else {
 2560:                 my $plain=
 2561:                     &LONCAPA::unescape(&LONCAPA::unescape($msgid));
 2562:                 if ($plain=~/ \[([^\]]+)\]\:/) {
 2563:                     my $url=$1;
 2564:                     if ($plain=~/\:Error \[/) {
 2565:                         $error{$url}.=','.$msgid;
 2566:                     } else {
 2567:                         $feedback{$url}.=','.$msgid;
 2568:                     }
 2569:                 }
 2570:             }
 2571: 	}
 2572:     }
 2573:     
 2574:     #symbs of resources that have feedbacks (will be urls pre-2.3)
 2575:     $self->{FEEDBACK} = \%feedback;
 2576:     #or errors (will be urls pre 2.3)
 2577:     $self->{ERROR_MSG} = \%error;
 2578:     $self->{DISCUSSION_TIME} = \%discussiontime;
 2579:     $self->{EMAIL_STATUS} = \%emailstatus;
 2580:     $self->{LAST_READ} = \%lastreadtime;
 2581:     
 2582:     $self->{EMAIL_DISCUSS_GENERATED} = 1;
 2583: }
 2584: 
 2585: sub get_user_data {
 2586:     my $self = shift;
 2587:     if ($self->{RETRIEVED_USER_DATA}) { return; }
 2588: 
 2589:     # Retrieve performance data on problems
 2590:     my %student_data = Apache::lonnet::currentdump($env{'request.course.id'},
 2591: 						   $self->{DOMAIN},
 2592: 						   $self->{USERNAME});
 2593:     $self->{STUDENT_DATA} = \%student_data;
 2594: 
 2595:     $self->{RETRIEVED_USER_DATA} = 1;
 2596: }
 2597: 
 2598: sub get_discussion_data {
 2599:     my $self = shift;
 2600:     if ($self->{RETRIEVED_DISCUSSION_DATA}) {
 2601: 	return $self->{DISCUSSION_DATA};
 2602:     }
 2603: 
 2604:     $self->generate_email_discuss_status();    
 2605: 
 2606:     my $cid=$env{'request.course.id'};
 2607:     my $cdom=$env{'course.'.$cid.'.domain'};
 2608:     my $cnum=$env{'course.'.$cid.'.num'};
 2609:     # Retrieve discussion data for resources in course
 2610:     my %discussion_data = &Apache::lonnet::dumpstore($cid,$cdom,$cnum);
 2611: 
 2612: 
 2613:     $self->{DISCUSSION_DATA} = \%discussion_data;
 2614:     $self->{RETRIEVED_DISCUSSION_DATA} = 1;
 2615:     return $self->{DISCUSSION_DATA};
 2616: }
 2617: 
 2618: 
 2619: # Internal function: Takes a key to look up in the nav hash and implements internal
 2620: # memory caching of that key.
 2621: sub navhash {
 2622:     my $self = shift; my $key = shift;
 2623:     return $self->{NAV_HASH}->{$key};
 2624: }
 2625: 
 2626: =pod
 2627: 
 2628: =item * B<courseMapDefined>(): Returns true if the course map is defined, 
 2629:     false otherwise. Undefined course maps indicate an error somewhere in
 2630:     LON-CAPA, and you will not be able to proceed with using the navmap.
 2631:     See the B<NAV> screen for an example of using this.
 2632: 
 2633: =cut
 2634: 
 2635: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 2636: sub courseMapDefined {
 2637:     my $self = shift;
 2638:     my $uri = &Apache::lonnet::clutter($env{'request.course.uri'});
 2639: 
 2640:     my $firstres = $self->navhash("map_start_$uri");
 2641:     my $lastres = $self->navhash("map_finish_$uri");
 2642:     return $firstres && $lastres;
 2643: }
 2644: 
 2645: sub getIterator {
 2646:     my $self = shift;
 2647:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 2648:                                                      shift, undef, shift,
 2649: 						     shift, shift, shift);
 2650:     return $iterator;
 2651: }
 2652: 
 2653: # Private method: Does the given resource (as a symb string) have
 2654: # current discussion? Returns 0 if chat/mail data not extracted.
 2655: sub hasDiscussion {
 2656:     my $self = shift;
 2657:     my $symb = shift;
 2658:     $self->generate_email_discuss_status();
 2659: 
 2660:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 2661: 
 2662:     #return defined($self->{DISCUSSION_TIME}->{$symb});
 2663: 
 2664:     # backward compatibility (bulletin boards used to be 'wrapped')
 2665:     my $ressymb = $self->wrap_symb($symb);
 2666:     if ( defined ( $self->{LAST_READ}->{$ressymb} ) ) {
 2667:         return $self->{DISCUSSION_TIME}->{$ressymb} > $self->{LAST_READ}->{$ressymb};
 2668:     } else {
 2669: #        return $self->{DISCUSSION_TIME}->{$ressymb} >  $self->{LAST_CHECK}; # v.1.1 behavior 
 2670:         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).
 2671:     }
 2672: }
 2673: 
 2674: sub last_post_time {
 2675:     my $self = shift;
 2676:     my $symb = shift;
 2677:     my $ressymb = $self->wrap_symb($symb);
 2678:     return $self->{DISCUSSION_TIME}->{$ressymb};
 2679: }
 2680: 
 2681: sub discussion_info {
 2682:     my $self = shift;
 2683:     my $symb = shift;
 2684:     my $filter = shift;
 2685: 
 2686:     $self->get_discussion_data();
 2687: 
 2688:     my $ressymb = $self->wrap_symb($symb);
 2689:     # keys used to store bulletinboard postings use 'unwrapped' symb. 
 2690:     my $discsymb = &escape($self->unwrap_symb($ressymb));
 2691:     my $version = $self->{DISCUSSION_DATA}{'version:'.$discsymb};
 2692:     if (!$version) { return; }
 2693: 
 2694:     my $prevread = $self->{LAST_READ}{$ressymb};
 2695: 
 2696:     my $count = 0;
 2697:     my $hiddenflag = 0;
 2698:     my $deletedflag = 0;
 2699:     my ($hidden,$deleted,%info);
 2700: 
 2701:     for (my $id=$version; $id>0; $id--) {
 2702: 	my $vkeys=$self->{DISCUSSION_DATA}{$id.':keys:'.$discsymb};
 2703: 	my @keys=split(/:/,$vkeys);
 2704: 	if (grep(/^hidden$/ ,@keys)) {
 2705: 	    if (!$hiddenflag) {
 2706: 		$hidden = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':hidden'};
 2707: 		$hiddenflag = 1;
 2708: 	    }
 2709: 	} elsif (grep(/^deleted$/,@keys)) {
 2710: 	    if (!$deletedflag) {
 2711: 		$deleted = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':deleted'};
 2712: 		$deletedflag = 1;
 2713: 	    }
 2714: 	} else {
 2715: 	    if (($hidden !~/\.$id\./) && ($deleted !~/\.$id\./)) {
 2716:                 if ($filter eq 'unread') {
 2717: 		    if ($prevread >= $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'}) {
 2718:                         next;
 2719:                     }
 2720:                 }
 2721: 		$count++;
 2722: 		$info{$count}{'subject'} =
 2723: 		    $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':subject'};
 2724:                 $info{$count}{'id'} = $id;
 2725:                 $info{$count}{'timestamp'} = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'};
 2726:             }
 2727: 	}
 2728:     }
 2729:     if (wantarray) {
 2730: 	return ($count,%info);
 2731:     }
 2732:     return $count;
 2733: }
 2734: 
 2735: sub wrap_symb {
 2736:     my $self = shift;
 2737:     my $symb = shift;
 2738:     if ($symb =~ m-___(adm/[^/]+/[^/]+/)(\d+)(/bulletinboard)$-) {
 2739:         unless ($symb =~ m|adm/wrapper/adm|) {
 2740:             $symb = 'bulletin___'.$2.'___adm/wrapper/'.$1.$2.$3;
 2741:         }
 2742:     }
 2743:     return $symb;
 2744: }
 2745: 
 2746: sub unwrap_symb {
 2747:     my $self = shift;
 2748:     my $ressymb = shift;
 2749:     my $discsymb = $ressymb;
 2750:     if ($ressymb =~ m-^(bulletin___\d+___)adm/wrapper/(adm/[^/]+/[^/]+/\d+/bulletinboard)$-) {
 2751:          $discsymb = $1.$2;
 2752:     }
 2753:     return $discsymb;
 2754: }
 2755: 
 2756: # Private method: Does the given resource (as a symb string) have
 2757: # current feedback? Returns the string in the feedback hash, which
 2758: # will be false if it does not exist.
 2759: 
 2760: sub getFeedback { 
 2761:     my $self = shift;
 2762:     my $symb = shift;
 2763:     my $source = shift;
 2764: 
 2765:     $self->generate_email_discuss_status();
 2766: 
 2767:     if (!defined($self->{FEEDBACK})) { return ""; }
 2768:     
 2769:     my $feedback;
 2770:     if ($self->{FEEDBACK}->{$symb}) {
 2771:         $feedback = $self->{FEEDBACK}->{$symb};
 2772:         if ($self->{FEEDBACK}->{$source}) {
 2773:             $feedback .= ','.$self->{FEEDBACK}->{$source};
 2774:         }
 2775:     } else {
 2776:         if ($self->{FEEDBACK}->{$source}) {
 2777:             $feedback = $self->{FEEDBACK}->{$source};
 2778:         }
 2779:     }
 2780:     return $feedback;
 2781: }
 2782: 
 2783: # Private method: Get the errors for that resource (by source).
 2784: sub getErrors { 
 2785:     my $self = shift;
 2786:     my $symb = shift;
 2787:     my $src = shift;
 2788: 
 2789:     $self->generate_email_discuss_status();
 2790: 
 2791:     if (!defined($self->{ERROR_MSG})) { return ""; }
 2792: 
 2793:     my $errors;
 2794:     if ($self->{ERROR_MSG}->{$symb}) {
 2795:         $errors = $self->{ERROR_MSG}->{$symb};
 2796:         if ($self->{ERROR_MSG}->{$src}) {
 2797:             $errors .= ','.$self->{ERROR_MSG}->{$src};
 2798:         }
 2799:     } else {
 2800:         if ($self->{ERROR_MSG}->{$src}) {
 2801:             $errors = $self->{ERROR_MSG}->{$src};
 2802:         }
 2803:     }
 2804:     return $errors;
 2805: }
 2806: 
 2807: =pod
 2808: 
 2809: =item * B<getById>(id):
 2810: 
 2811: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
 2812: object for that resource. This method, or other methods that use it
 2813: (as in the resource object) is the only proper way to obtain a
 2814: resource object.
 2815: 
 2816: =item * B<getBySymb>(symb):
 2817: 
 2818: Based on the symb of the resource, get a resource object for that
 2819: resource. This is one of the proper ways to get a resource object.
 2820: 
 2821: =item * B<getByMapPc>(map_pc):
 2822: 
 2823: Based on the map_pc of the resource, get a resource object for
 2824: the given map. This is one of the proper ways to get a resource object.
 2825: 
 2826: =cut
 2827: 
 2828: # The strategy here is to cache the resource objects, and only construct them
 2829: # as we use them. The real point is to prevent reading any more from the tied
 2830: # hash than we have to, which should hopefully alleviate speed problems.
 2831: 
 2832: sub getById {
 2833:     my $self = shift;
 2834:     my $id = shift;
 2835: 
 2836:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 2837:     {
 2838:         return $self->{RESOURCE_CACHE}->{$id};
 2839:     }
 2840: 
 2841:     # resource handles inserting itself into cache.
 2842:     # Not clear why the quotes are necessary, but as of this
 2843:     # writing it doesn't work without them.
 2844:     return "Apache::lonnavmaps::resource"->new($self, $id);
 2845: }
 2846: 
 2847: sub getBySymb {
 2848:     my $self = shift;
 2849:     my $symb = shift;
 2850: 
 2851:     my ($mapUrl, $id, $filename) = &Apache::lonnet::decode_symb($symb);
 2852:     my $map = $self->getResourceByUrl($mapUrl);
 2853:     my $returnvalue = undef;
 2854:     if (ref($map)) {
 2855:         $returnvalue = $self->getById($map->map_pc() .'.'.$id);
 2856:     }
 2857:     return $returnvalue;
 2858: }
 2859: 
 2860: sub getByMapPc {
 2861:     my $self = shift;
 2862:     my $map_pc = shift;
 2863:     my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
 2864:     $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
 2865:     return $self->getById($map_id);
 2866: }
 2867: 
 2868: =pod
 2869: 
 2870: =item * B<firstResource>():
 2871: 
 2872: Returns a resource object reference corresponding to the first
 2873: resource in the navmap.
 2874: 
 2875: =cut
 2876: 
 2877: sub firstResource {
 2878:     my $self = shift;
 2879:     my $firstResource = $self->navhash('map_start_' .
 2880:                      &Apache::lonnet::clutter($env{'request.course.uri'}));
 2881:     return $self->getById($firstResource);
 2882: }
 2883: 
 2884: =pod
 2885: 
 2886: =item * B<finishResource>():
 2887: 
 2888: Returns a resource object reference corresponding to the last resource
 2889: in the navmap.
 2890: 
 2891: =cut
 2892: 
 2893: sub finishResource {
 2894:     my $self = shift;
 2895:     my $firstResource = $self->navhash('map_finish_' .
 2896:                      &Apache::lonnet::clutter($env{'request.course.uri'}));
 2897:     return $self->getById($firstResource);
 2898: }
 2899: 
 2900: # Parmval reads the parm hash and cascades the lookups. parmval_real does
 2901: # the actual lookup; parmval caches the results.
 2902: sub parmval {
 2903:     my $self = shift;
 2904:     my ($what,$symb,$recurse)=@_;
 2905:     my $hashkey = $what."|||".$symb;
 2906:     my $cache = $self->{PARM_CACHE};
 2907:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
 2908:         if (ref($self->{PARM_CACHE}->{$hashkey}) eq 'ARRAY') { 
 2909:             if (defined($self->{PARM_CACHE}->{$hashkey}->[0])) {
 2910:                 if (wantarray) {
 2911:                     return @{$self->{PARM_CACHE}->{$hashkey}};
 2912:                 } else {
 2913:                     return $self->{PARM_CACHE}->{$hashkey}->[0];
 2914:                 }
 2915:             }
 2916:         } else {
 2917:             return $self->{PARM_CACHE}->{$hashkey};
 2918:         }
 2919:     }
 2920: 
 2921:     my $result = $self->parmval_real($what, $symb, $recurse);
 2922:     $self->{PARM_CACHE}->{$hashkey} = $result;
 2923:     if (wantarray) {
 2924:         return @{$result};
 2925:     }
 2926:     return $result->[0];
 2927: }
 2928: 
 2929: 
 2930: sub parmval_real {
 2931:     my $self = shift;
 2932:     my ($what,$symb,$recurse) = @_;
 2933: 
 2934: 
 2935:     # Make sure the {USER_OPT} and {COURSE_OPT} hashes are populated
 2936:     $self->generate_course_user_opt();
 2937: 
 2938:     my $cid=$env{'request.course.id'};
 2939:     my $csec=$self->{SECTION};
 2940:     my $cgroup='';
 2941:     my @cgrps=split(/:/,$env{'request.course.groups'});
 2942:     if (@cgrps > 0) {
 2943:         @cgrps = sort(@cgrps);
 2944:         $cgroup = $cgrps[0];
 2945:     } 
 2946:     my $uname=$self->{USERNAME};
 2947:     my $udom=$self->{DOMAIN};
 2948: 
 2949:     unless ($symb) { return ['']; }
 2950:     my $result='';
 2951: 
 2952:     my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
 2953:     $mapname = &Apache::lonnet::deversion($mapname);
 2954:     my $toolsymb = '';
 2955:     if ($fn =~ /ext\.tool$/) {
 2956:         $toolsymb = $symb;
 2957:     }
 2958:     my ($recursed,@recurseup); 
 2959:     
 2960: # ----------------------------------------------------- Cascading lookup scheme
 2961:     my $rwhat=$what;
 2962:     $what=~s/^parameter\_//;
 2963:     $what=~s/\_/\./;
 2964: 
 2965:     my $symbparm=$symb.'.'.$what;
 2966:     my $recurseparm=$mapname.'___(rec).'.$what;
 2967:     my $mapparm=$mapname.'___(all).'.$what;
 2968:     my $usercourseprefix=$cid;
 2969:     
 2970: 
 2971: 
 2972:     my $grplevel=$usercourseprefix.'.['.$cgroup.'].'.$what;
 2973:     my $grplevelr=$usercourseprefix.'.['.$cgroup.'].'.$symbparm;
 2974:     my $grpleveli=$usercourseprefix.'.['.$cgroup.'].'.$recurseparm;
 2975:     my $grplevelm=$usercourseprefix.'.['.$cgroup.'].'.$mapparm;
 2976: 
 2977: 
 2978:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 2979:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 2980:     my $secleveli=$usercourseprefix.'.['.$csec.'].'.$recurseparm;
 2981:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 2982: 
 2983: 
 2984:     my $courselevel= $usercourseprefix.'.'.$what;
 2985:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 2986:     my $courseleveli=$usercourseprefix.'.'.$recurseparm;
 2987:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 2988: 
 2989: 
 2990:     my $useropt = $self->{USER_OPT};
 2991:     my $courseopt = $self->{COURSE_OPT};
 2992:     my $parmhash = $self->{PARM_HASH};
 2993: 
 2994: # ---------------------------------------------------------- first, check user
 2995:     if ($uname and defined($useropt)) {
 2996:         if (defined($$useropt{$courselevelr})) { return [$$useropt{$courselevelr},'resource']; }
 2997:         if (defined($$useropt{$courselevelm})) { return [$$useropt{$courselevelm},'map']; }
 2998:         if (defined($$useropt{$courseleveli})) { return [$$useropt{$courseleveli},'map']; }
 2999:         unless ($recursed) {
 3000:             @recurseup = $self->recurseup_maps($mapname);
 3001:             $recursed = 1;
 3002:         }
 3003:         foreach my $item (@recurseup) {
 3004:             my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
 3005:             if (defined($$useropt{$norecursechk})) {
 3006:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3007:                     return [$$useropt{$norecursechk},'map'];
 3008:                 } else {
 3009:                     last;
 3010:                 }
 3011:             }
 3012:             my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
 3013:             if (defined($$useropt{$recursechk})) { return [$$useropt{$recursechk},'map']; } 
 3014:         }
 3015:         if (defined($$useropt{$courselevel})) { return [$$useropt{$courselevel},'course']; }
 3016:     }
 3017: 
 3018: # ------------------------------------------------------- second, check course
 3019:     if ($cgroup ne '' and defined($courseopt)) {
 3020:         if (defined($$courseopt{$grplevelr})) { return [$$courseopt{$grplevelr},'resource']; }
 3021:         if (defined($$courseopt{$grplevelm})) { return [$$courseopt{$grplevelm},'map']; }
 3022:         if (defined($$courseopt{$grpleveli})) { return [$$courseopt{$grpleveli},'map']; } 
 3023:         unless ($recursed) {
 3024:             @recurseup = $self->recurseup_maps($mapname);
 3025:             $recursed = 1;
 3026:         }
 3027:         foreach my $item (@recurseup) {
 3028:             my $norecursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(all).'.$what;
 3029:             if (defined($$courseopt{$norecursechk})) {
 3030:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3031:                     return [$$courseopt{$norecursechk},'map'];
 3032:                 } else {
 3033:                    last;
 3034:                 }
 3035:             }
 3036:             my $recursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(rec).'.$what;
 3037:             if (defined($$courseopt{$recursechk})) { return [$$courseopt{$recursechk},'map']; }      
 3038:         }
 3039:         if (defined($$courseopt{$grplevel})) { return [$$courseopt{$grplevel},'course']; }
 3040:     }
 3041: 
 3042:     if ($csec ne '' and defined($courseopt)) {
 3043:         if (defined($$courseopt{$seclevelr})) { return [$$courseopt{$seclevelr},'resource']; }
 3044:         if (defined($$courseopt{$seclevelm})) { return [$$courseopt{$seclevelm},'map']; }
 3045:         if (defined($$courseopt{$secleveli})) { return [$$courseopt{$secleveli},'map']; } 
 3046:         unless ($recursed) {
 3047:             @recurseup = $self->recurseup_maps($mapname);
 3048:             $recursed = 1;
 3049:         }
 3050:         foreach my $item (@recurseup) {
 3051:             my $norecursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(all).'.$what;
 3052:             if (defined($$courseopt{$norecursechk})) {
 3053:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3054:                     return [$$courseopt{$norecursechk},'map'];
 3055:                 } else {
 3056:                     last;
 3057:                 }
 3058:             }
 3059:             my $recursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(rec).'.$what;
 3060:             if (defined($$courseopt{$recursechk})) { return [$$courseopt{$recursechk},'map']; }
 3061:         }
 3062:         if (defined($$courseopt{$seclevel})) { return [$$courseopt{$seclevel},'course']; }
 3063:     }
 3064: 
 3065:     if (defined($courseopt)) {
 3066:         if (defined($$courseopt{$courselevelr})) { return [$$courseopt{$courselevelr},'resource']; }
 3067:     }
 3068: 
 3069: # ----------------------------------------------------- third, check map parms
 3070: 
 3071:     my $thisparm=$$parmhash{$symbparm};
 3072:     if (defined($thisparm)) { return [$thisparm,'map']; }
 3073: 
 3074: # ----------------------------------------------------- fourth , check default
 3075: 
 3076:     my $meta_rwhat=$rwhat;
 3077:     $meta_rwhat=~s/\./_/g;
 3078:     my $default=&Apache::lonnet::metadata($fn,$meta_rwhat,$toolsymb);
 3079:     if (defined($default)) { return [$default,'resource']}
 3080:     $default=&Apache::lonnet::metadata($fn,'parameter_'.$meta_rwhat,$toolsymb);
 3081:     if (defined($default)) { return [$default,'resource']}
 3082: # --------------------------------------------------- fifth, check more course
 3083:     if (defined($courseopt)) {
 3084:         if (defined($$courseopt{$courselevelm})) { return [$$courseopt{$courselevelm},'map']; }
 3085:         if (defined($$courseopt{$courseleveli})) { return [$$courseopt{$courseleveli},'map']; }
 3086:         unless ($recursed) {
 3087:             @recurseup = $self->recurseup_maps($mapname);
 3088:             $recursed = 1;
 3089:         }
 3090:         foreach my $item (@recurseup) {
 3091:             my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
 3092:             if (defined($$courseopt{$norecursechk})) {
 3093:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3094:                     return [$$courseopt{$norecursechk},'map'];
 3095:                 } else {
 3096:                     last;
 3097:                 }
 3098:             }
 3099:             my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
 3100:             if (defined($$courseopt{$recursechk})) {
 3101:                 return [$$courseopt{$recursechk},'map'];
 3102:             }
 3103:         }
 3104:         if (defined($$courseopt{$courselevel})) {
 3105:            my $ret = [$$courseopt{$courselevel},'course'];
 3106:            return $ret;
 3107:        }
 3108:     }
 3109: # --------------------------------------------------- sixth , cascade up parts
 3110: 
 3111:     my ($space,@qualifier)=split(/\./,$rwhat);
 3112:     my $qualifier=join('.',@qualifier);
 3113:     unless ($space eq '0') {
 3114: 	my @parts=split(/_/,$space);
 3115: 	my $id=pop(@parts);
 3116: 	my $part=join('_',@parts);
 3117: 	if ($part eq '') { $part='0'; }
 3118:        my @partgeneral=$self->parmval($part.".$qualifier",$symb,1);
 3119:        if (defined($partgeneral[0])) { return \@partgeneral; }
 3120:     }
 3121:     if ($recurse) { return []; }
 3122:     my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$rwhat,$toolsymb);
 3123:     if (defined($pack_def)) { return [$pack_def,'resource']; }
 3124:     return [''];
 3125: }
 3126: 
 3127: sub recurseup_maps {
 3128:     my ($self,$mapname,$getsymb,$inclusive) = @_;
 3129:     my @recurseup;
 3130:     if ($mapname) {
 3131:         my $res = $self->getResourceByUrl($mapname);
 3132:         if (ref($res)) {
 3133:             my @pcs = split(/,/,$res->map_hierarchy());
 3134:             shift(@pcs);
 3135:             if (@pcs) {
 3136:                 if ($getsymb) {
 3137:                     @recurseup = map { &Apache::lonnet::declutter($self->getByMapPc($_)->symb()); } reverse(@pcs);
 3138:                 } else {
 3139:                     @recurseup = map { &Apache::lonnet::declutter($self->getByMapPc($_)->src()); } reverse(@pcs);
 3140:                 }
 3141:             }
 3142:             if ($inclusive) {
 3143:                 if ($getsymb) {
 3144:                     unshift(@recurseup,$res->symb());
 3145:                 } else {
 3146:                     unshift(@recurseup,$mapname);
 3147:                 }
 3148:             }
 3149:         }
 3150:     }
 3151:     return @recurseup;
 3152: }
 3153: 
 3154: sub recursed_crumbs {
 3155:     my ($self,$mapurl,$restitle) = @_;
 3156:     my (@revmapinfo,@revmapres);
 3157:     my $mapres = $self->getResourceByUrl($mapurl);
 3158:     if (ref($mapres)) {
 3159:         @revmapres = map { $self->getByMapPc($_); } split(/,/,$mapres->map_breadcrumbs());
 3160:         shift(@revmapres);
 3161:     }
 3162:     my $allowedlength = 60;
 3163:     my $minlength = 5;
 3164:     my $allowedtitle = 30;
 3165:     if (($env{'environment.icons'} eq 'iconsonly') && (!$env{'browser.mobile'})) {
 3166:         $allowedlength = 100;
 3167:         $allowedtitle = 70;
 3168:     }
 3169:     if (length($restitle) > $allowedtitle) {
 3170:         $restitle = &truncate_crumb_text($restitle,$allowedtitle);
 3171:     }
 3172:     my $totallength = length($restitle);
 3173:     my @links;
 3174: 
 3175:     foreach my $map (@revmapres) {
 3176:         my $pc = $map->map_pc();
 3177:         next if ((!$pc) || ($pc == 1));
 3178:         push(@links,$map);
 3179:         my $text = $map->title();
 3180:         if ($text eq '') {
 3181:             $text = '...';
 3182:         }
 3183:         push(@revmapinfo,{'href' => $env{'request.use_absolute'}.$map->link().'?navmap=1','text' => $text,'no_mt' => 1,});
 3184:         $totallength += length($text);
 3185:     }
 3186:     my $numlinks = scalar(@links);
 3187:     if ($numlinks) {
 3188:         if ($totallength - $allowedlength > 0) {
 3189:             my $available = $allowedlength - length($restitle);
 3190:             my $avg = POSIX::ceil($available/$numlinks);
 3191:             if ($avg < $minlength) {
 3192:                 $avg = $minlength;
 3193:             }
 3194:             @revmapinfo = ();
 3195:             foreach my $map (@links) {
 3196:                 my $title = $map->title();
 3197:                 if ($title eq '') {
 3198:                     $title = '...';
 3199:                 }
 3200:                 my $showntitle = &truncate_crumb_text($title,$avg);
 3201:                 if ($showntitle ne '') {
 3202:                     push(@revmapinfo,{'href' => $env{'request.use_absolute'}.$map->link().'?navmap=1','text' => $showntitle,'no_mt' => 1,});
 3203:                 }
 3204:             }
 3205:         }
 3206:     }
 3207:     if ($restitle ne '') {
 3208:         push(@revmapinfo,{'text' => $restitle, 'no_mt' => 1});
 3209:     }
 3210:     return @revmapinfo;
 3211: }
 3212: 
 3213: sub truncate_crumb_text {
 3214:     my ($title,$limit) = @_;
 3215:     my $showntitle = '';
 3216:     if (length($title) > $limit) {
 3217:         my @words = split(/\b\s*/,$title);
 3218:         if (@words == 1) {
 3219:             $showntitle = substr($title,0,$limit).' ...';
 3220:         } else {
 3221:             my $linklength = 0;
 3222:             my $num = 0;
 3223:             foreach my $word (@words) {
 3224:                 $linklength += 1+length($word);
 3225:                 if ($word eq '-') {
 3226:                     $showntitle =~ s/ $//;
 3227:                     $showntitle .= $word;
 3228:                 } elsif ($linklength > $limit) {
 3229:                     if ($num < @words) {
 3230:                         $showntitle .= $word.' ...';
 3231:                         last;
 3232:                     } else {
 3233:                         $showntitle .= $word;
 3234:                     }
 3235:                 } else {
 3236:                     $showntitle .= $word.' ';
 3237:                 }
 3238:             }
 3239:             $showntitle =~ s/ $//;
 3240:         }
 3241:         return $showntitle;
 3242:     } else {
 3243:         return $title;
 3244:     }
 3245: }
 3246: 
 3247: #
 3248: #  Determines the open/close dates for printing a map that
 3249: #  encloses a resource.
 3250: #
 3251: sub map_printdates {
 3252:     my ($self, $res, $part) = @_;
 3253: 
 3254: 
 3255: 
 3256: 
 3257: 
 3258:     my $opendate = $self->get_mapparam($res->symb(),'',"$part.printstartdate");
 3259:     my $closedate= $self->get_mapparam($res->symb(),'',"$part.printenddate");
 3260: 
 3261: 
 3262:     return ($opendate, $closedate);
 3263: }
 3264: 
 3265: sub get_mapparam {
 3266:     my ($self, $symb, $mapname, $what) = @_;
 3267: 
 3268:     # Ensure the course option hash is populated:
 3269: 
 3270:     $self->generate_course_user_opt();
 3271: 
 3272:     # Get the course id and section if there is one.
 3273: 
 3274:     my $cid=$env{'request.course.id'};
 3275:     my $csec=$self->{SECTION};
 3276:     my $cgroup='';
 3277:     my @cgrps=split(/:/,$env{'request.course.groups'});
 3278:     if (@cgrps > 0) {
 3279:         @cgrps = sort(@cgrps);
 3280:         $cgroup = $cgrps[0];
 3281:     } 
 3282:     my $uname=$self->{USERNAME};
 3283:     my $udom=$self->{DOMAIN};
 3284: 
 3285:     unless ($symb || $mapname) { return; }
 3286:     my $result='';
 3287:     my ($recursed,@recurseup);
 3288: 
 3289: 
 3290:     # Figure out which map we are in.
 3291: 
 3292:     if ($symb && !$mapname) {
 3293:         my ($id,$fn);
 3294:         ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
 3295:         $mapname = &Apache::lonnet::deversion($mapname);
 3296:     }
 3297: 
 3298: 
 3299:     my $rwhat=$what;
 3300:     $what=~s/^parameter\_//;
 3301:     $what=~s/\_/\./;
 3302: 
 3303:     # Build the hash keys for the lookup:
 3304: 
 3305:     my $mapparm=$mapname.'___(all).'.$what;
 3306:     my $recurseparm=$mapname.'___(rec).'.$what; 
 3307:     my $usercourseprefix=$cid;
 3308: 
 3309: 
 3310:     my $grplevelm    = "$usercourseprefix.[$cgroup].$mapparm";
 3311:     my $seclevelm    = "$usercourseprefix.[$csec].$mapparm";
 3312:     my $courselevelm = "$usercourseprefix.$mapparm";
 3313: 
 3314:     my $grpleveli    = "$usercourseprefix.[$cgroup].$recurseparm";
 3315:     my $secleveli    = "$usercourseprefix.[$csec].$recurseparm";
 3316:     my $courseleveli = "$usercourseprefix.$recurseparm";
 3317: 
 3318:     # Get handy references to the hashes we need in $self:
 3319: 
 3320:     my $useropt = $self->{USER_OPT};
 3321:     my $courseopt = $self->{COURSE_OPT};
 3322:     my $parmhash = $self->{PARM_HASH};
 3323: 
 3324:     # Check per user 
 3325: 
 3326: 
 3327: 
 3328:     if ($uname and defined($useropt)) {
 3329: 	if (defined($$useropt{$courselevelm})) {
 3330: 	    return $$useropt{$courselevelm};
 3331: 	}
 3332:         if (defined($$useropt{$courseleveli})) {
 3333:             return $$useropt{$courseleveli};
 3334:         }
 3335:         unless ($recursed) {
 3336:             @recurseup = $self->recurseup_maps($mapname);
 3337:             $recursed = 1;
 3338:         }
 3339:         foreach my $item (@recurseup) {
 3340:             my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
 3341:             if (defined($$useropt{$norecursechk})) {
 3342:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3343:                     return $$useropt{$norecursechk};
 3344:                 } else {
 3345:                     last;
 3346:                 }
 3347:             }
 3348:             my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
 3349:             if (defined($$useropt{$recursechk})) {
 3350:                 return $$useropt{$recursechk};
 3351:             }
 3352:         }
 3353:     }
 3354: 
 3355:     # Check course -- group
 3356: 
 3357: 
 3358: 
 3359:     if ($cgroup ne '' and defined ($courseopt)) {
 3360: 	if (defined($$courseopt{$grplevelm})) {
 3361: 	    return $$courseopt{$grplevelm};
 3362: 	}
 3363:         if (defined($$courseopt{$grpleveli})) {
 3364:             return $$courseopt{$grpleveli};
 3365:         }
 3366:         unless ($recursed) {
 3367:             @recurseup = $self->recurseup_maps($mapname);
 3368:             $recursed = 1;
 3369:         }
 3370:         foreach my $item (@recurseup) {
 3371:             my $norecursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(all).'.$what;
 3372:             if (defined($$courseopt{$norecursechk})) {
 3373:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3374:                     return $$courseopt{$norecursechk};
 3375:                 } else {
 3376:                     last;
 3377:                 }
 3378:             }
 3379:             my $recursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(rec).'.$what;
 3380:             if (defined($$courseopt{$recursechk})) {
 3381:                 return $$courseopt{$recursechk};
 3382:             }
 3383:         }
 3384:     }
 3385: 
 3386:     # Check course -- section
 3387: 
 3388: 
 3389:     if ($csec ne '' and defined($courseopt)) {
 3390: 	if (defined($$courseopt{$seclevelm})) {
 3391: 	    return $$courseopt{$seclevelm};
 3392: 	}
 3393:         if (defined($$courseopt{$secleveli})) {
 3394:             return $$courseopt{$secleveli};
 3395:         }
 3396:         unless ($recursed) {
 3397:             @recurseup = $self->recurseup_maps($mapname);
 3398:             $recursed = 1;
 3399:         }
 3400:         foreach my $item (@recurseup) {
 3401:             my $norecursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(all).'.$what;
 3402:             if (defined($$courseopt{$norecursechk})) {
 3403:                 if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3404:                     return $$courseopt{$norecursechk};
 3405:                 } else {
 3406:                     last;
 3407:                 }
 3408:             }
 3409:             my $recursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(rec).'.$what;
 3410:             if (defined($$courseopt{$recursechk})) {
 3411:                 return $$courseopt{$recursechk};
 3412:             }
 3413:         }
 3414:     }
 3415:     # Check the map parameters themselves:
 3416: 
 3417:     if ($symb) {
 3418:         my $symbparm=$symb.'.'.$what;
 3419:         my $thisparm = $$parmhash{$symbparm};
 3420:         if (defined($thisparm)) {
 3421: 	    return $thisparm;
 3422:         }
 3423:     }
 3424: 
 3425: 
 3426:     # Additional course parameters:
 3427: 
 3428:     if (defined($courseopt)) {
 3429: 	if (defined($$courseopt{$courselevelm})) {
 3430: 	    return $$courseopt{$courselevelm};
 3431: 	}
 3432:         if (defined($$courseopt{$courseleveli})) {
 3433:             return $$courseopt{$courseleveli};
 3434:         }
 3435:         unless ($recursed) {
 3436:             @recurseup = $self->recurseup_maps($mapname);
 3437:             $recursed = 1;
 3438:         }
 3439:         if (@recurseup) {
 3440:             foreach my $item (@recurseup) {
 3441:                 my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
 3442:                 if (defined($$courseopt{$norecursechk})) {
 3443:                     if ($what =~ /\.(encrypturl|hiddenresource)$/) {
 3444:                         return $$courseopt{$norecursechk};
 3445:                     } else {
 3446:                         last;
 3447:                     }
 3448:                 }
 3449:                 my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
 3450:                 if (defined($$courseopt{$recursechk})) {
 3451:                     return $$courseopt{$recursechk};
 3452:                 }
 3453:             }
 3454:         }
 3455:     }
 3456:     return undef;		# Undefined if we got here.
 3457: }
 3458: 
 3459: sub course_printdates {
 3460:     my ($self, $symb,  $part) = @_;
 3461: 
 3462: 
 3463:     my $opendate  = $self->getcourseparam($symb, $part . '.printstartdate');
 3464:     my $closedate = $self->getcourseparam($symb, $part . '.printenddate');
 3465:     return ($opendate, $closedate);
 3466: 
 3467: }
 3468: 
 3469: sub getcourseparam {
 3470:     my ($self, $symb, $what) = @_;
 3471: 
 3472:     $self->generate_course_user_opt(); # If necessary populate the hashes.
 3473: 
 3474:     my $uname = $self->{USERNAME};
 3475:     my $udom  = $self->{DOMAIN};
 3476:     my $csec  = $self->{SECTION};
 3477:     
 3478:     # Course and group ids come from the env:
 3479: 
 3480:     my $cid   = $env{'request.course.id'};
 3481:     my $cgroup = '';		# Assume no group
 3482: 
 3483:     my @cgroups = split(/:/, $env{'request.course.groups'});
 3484:     if(@cgroups > 0) {
 3485: 	@cgroups = sort(@cgroups);
 3486: 	$cgroup  = $cgroups[0];	# There is a course group. 
 3487:    }
 3488:     my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
 3489:     $mapname = &Apache::lonnet::deversion($mapname);
 3490: 
 3491:     #
 3492:     # Make the various lookup keys:
 3493:     #
 3494: 
 3495:     $what=~s/^parameter\_//;
 3496:     $what=~s/\_/\./;
 3497: 
 3498:     # Local refs to the hashes we're going to look at:
 3499: 
 3500:     my $useropt   = $self->{USER_OPT};
 3501:     my $courseopt = $self->{COURSE_OPT};
 3502: 
 3503:     # 
 3504:     # We want the course level stuff from the way
 3505:     # parmval_real operates 
 3506:     # TODO: Factor some of this stuff out of
 3507:     # both parmval_real and here
 3508:     #
 3509:     my $courselevel = $cid . '.' .  $what;
 3510:     my $grplevel    = $cid . '.[' . $cgroup   . ']' . $what;
 3511:     my $seclevel    = $cid . '.[' . $csec     . ']' . $what;
 3512: 
 3513: 
 3514:     # Try for the user's course level option:
 3515: 
 3516:     if ($uname and defined($useropt)) {
 3517: 	if (defined($$useropt{$courselevel})) {
 3518: 	    return $$useropt{$courselevel};
 3519: 	}
 3520:     }
 3521:     # Try for the group's course level option:
 3522: 
 3523:     if ($cgroup ne '' and defined($courseopt)) {
 3524: 	if (defined($$courseopt{$grplevel})) {
 3525: 	    return $$courseopt{$grplevel};
 3526: 	}
 3527:     }
 3528: 
 3529:     #  Try for section level parameters:
 3530: 
 3531:     if ($csec ne '' and defined($courseopt)) {
 3532: 	if (defined($$courseopt{$seclevel})) {
 3533: 	    return $$courseopt{$seclevel};
 3534: 	}
 3535:     }
 3536:     # Try for 'additional' course parameters:
 3537: 
 3538:     if (defined($courseopt)) {
 3539: 	if (defined($$courseopt{$courselevel})) {
 3540: 	    return $$courseopt{$courselevel};
 3541: 	}
 3542:     }
 3543:     return undef;
 3544: 
 3545: }
 3546: 
 3547: 
 3548: =pod
 3549: 
 3550: =item * B<getResourceByUrl>(url,multiple):
 3551: 
 3552: Retrieves a resource object by URL of the resource, unless the optional
 3553: multiple parameter is included in which case an array of resource 
 3554: objects is returned. If passed a resource object, it will simply return  
 3555: it, so it is safe to use this method in code like
 3556: "$res = $navmap->getResourceByUrl($res)"
 3557: if you're not sure if $res is already an object, or just a URL. If the
 3558: resource appears multiple times in the course, only the first instance 
 3559: will be returned (useful for maps), unless the multiple parameter has
 3560: been included, in which case all instances are returned in an array.
 3561: 
 3562: =item * B<retrieveResources>(map, filterFunc, recursive, bailout, showall, noblockcheck):
 3563: 
 3564: The map is a specification of a map to retreive the resources from,
 3565: either as a url or as an object. The filterFunc is a reference to a
 3566: function that takes a resource object as its one argument and returns
 3567: true if the resource should be included, or false if it should not
 3568: be. If recursive is true, the map will be recursively examined,
 3569: otherwise it will not be. If bailout is true, the function will return
 3570: as soon as it finds a resource, if false it will finish. If showall is
 3571: true it will not hide maps that contain nothing but one other map. The 
 3572: noblockcheck arg is propagated to become the sixth arg in the call to
 3573: lonnet::allowed when checking a resource's availability during collection
 3574: of resources using the iterator. noblockcheck needs to be true if 
 3575: retrieveResources() was called by a routine that itself was called by 
 3576: lonnet::allowed, in order to avoid recursion.  By default the map  
 3577: is the top-level map of the course, filterFunc is a function that 
 3578: always returns 1, recursive is true, bailout is false, showall is
 3579: false. The resources will be returned in a list containing the
 3580: resource objects for the corresponding resources, with B<no structure 
 3581: information> in the list; regardless of branching, recursion, etc.,
 3582: it will be a flat list.
 3583: 
 3584: Thus, this is suitable for cases where you don't want the structure,
 3585: just a list of all resources. It is also suitable for finding out how
 3586: many resources match a given description; for this use, if all you
 3587: want to know is if I<any> resources match the description, the bailout
 3588: parameter will allow you to avoid potentially expensive enumeration of
 3589: all matching resources.
 3590: 
 3591: =item * B<hasResource>(map, filterFunc, recursive, showall):
 3592: 
 3593: Convenience method for
 3594: 
 3595:  scalar(retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0
 3596: 
 3597: which will tell whether the map has resources matching the description
 3598: in the filter function.
 3599: 
 3600: =item * B<usedVersion>(url):
 3601: 
 3602: Retrieves version infomation for a url. Returns the version (a number, or 
 3603: the string "mostrecent") for resources which have version information in  
 3604: the big hash.
 3605: 
 3606: =cut
 3607: 
 3608: 
 3609: sub getResourceByUrl {
 3610:     my $self = shift;
 3611:     my $resUrl = shift;
 3612:     my $multiple = shift;
 3613: 
 3614:     if (ref($resUrl)) { return $resUrl; }
 3615: 
 3616:     $resUrl = &Apache::lonnet::clutter($resUrl);
 3617:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
 3618:     if (!$resId) { return ''; }
 3619:     if ($multiple) {
 3620:         my @resources = ();
 3621:         my @resIds = split (/,/, $resId);
 3622:         foreach my $id (@resIds) {
 3623:             my $resourceId = $self->getById($id);
 3624:             if ($resourceId) { 
 3625:                 push(@resources,$resourceId);
 3626:             }
 3627:         }
 3628:         return @resources;
 3629:     } else {
 3630:         if ($resId =~ /,/) {
 3631:             $resId = (split (/,/, $resId))[0];
 3632:         }
 3633:         return $self->getById($resId);
 3634:     }
 3635: }
 3636: 
 3637: sub retrieveResources {
 3638:     my $self = shift;
 3639:     my $map = shift;
 3640:     my $filterFunc = shift;
 3641:     if (!defined ($filterFunc)) {
 3642:         $filterFunc = sub {return 1;};
 3643:     }
 3644:     my $recursive = shift;
 3645:     if (!defined($recursive)) { $recursive = 1; }
 3646:     my $bailout = shift;
 3647:     if (!defined($bailout)) { $bailout = 0; }
 3648:     my $showall = shift;
 3649:     my $noblockcheck = shift;
 3650:     # Create the necessary iterator.
 3651:     if (!ref($map)) { # assume it's a url of a map.
 3652:         $map = $self->getResourceByUrl($map);
 3653:     }
 3654: 
 3655:     # If nothing was passed, assume top-level map
 3656:     if (!$map) {
 3657: 	$map = $self->getById('0.0');
 3658:     }
 3659: 
 3660:     # Check the map's validity.
 3661:     if (!$map->is_map()) {
 3662:         # Oh, to throw an exception.... how I'd love that!
 3663:         return ();
 3664:     }
 3665: 
 3666:     # Get an iterator.
 3667:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
 3668:                                 undef, $recursive, $showall);
 3669: 
 3670:     my @resources = ();
 3671: 
 3672:     if (&$filterFunc($map)) {
 3673: 	push(@resources, $map);
 3674:     }
 3675: 
 3676:     # Run down the iterator and collect the resources.
 3677:     my $curRes;
 3678: 
 3679:     while ($curRes = $it->next(undef,$noblockcheck)) {
 3680:         if (ref($curRes)) {
 3681:             if (!&$filterFunc($curRes)) {
 3682:                 next;
 3683:             }
 3684: 
 3685:             push(@resources, $curRes);
 3686: 
 3687:             if ($bailout) {
 3688:                 return @resources;
 3689:             }
 3690:         }
 3691: 
 3692:     }
 3693: 
 3694:     return @resources;
 3695: }
 3696: 
 3697: sub hasResource {
 3698:     my $self = shift;
 3699:     my $map = shift;
 3700:     my $filterFunc = shift;
 3701:     my $recursive = shift;
 3702:     my $showall = shift;
 3703:     
 3704:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0;
 3705: }
 3706: 
 3707: sub usedVersion {
 3708:     my $self = shift;
 3709:     my $linkurl = shift;
 3710:     return $self->navhash("version_$linkurl");
 3711: }
 3712: 
 3713: sub isFirstResource {
 3714:     my $self = shift;
 3715:     my $map = shift;
 3716:     my $symb = shift;
 3717:     return unless (ref($map));
 3718:     my $isfirst;
 3719:     my $firstResource = $map->map_start();
 3720:     if (ref($firstResource)) {
 3721:         if ((!$firstResource->is_map()) && ($firstResource->src() ne ''))  {
 3722:             if ($firstResource->symb() eq $symb) {
 3723:                 $isfirst = 1;
 3724:             } else {
 3725:                 $isfirst = 0;
 3726:             }
 3727:         } else {
 3728:             my $it = $self->getIterator($firstResource,undef,undef,1);
 3729:             while ( my $res=$it->next()) {
 3730:                 if ((ref($res)) && ($res->src() ne '') && (!$res->is_map())) {
 3731:                     if ($res->symb() eq $symb) {
 3732:                         $isfirst = 1;
 3733:                     } else {
 3734:                         $isfirst = 0;
 3735:                     }
 3736:                     last;
 3737:                 }
 3738:             }
 3739:         }
 3740:     }
 3741:     return $isfirst;
 3742: }
 3743: 
 3744: sub isLastResource {
 3745:     my $self = shift;
 3746:     my $map = shift;
 3747:     my $symb = shift;
 3748:     return unless (ref($map));
 3749:     my $islast;
 3750:     my $lastResource = $map->map_finish();
 3751:     if (ref($lastResource)) {
 3752:         if ((!$lastResource->is_map()) && ($lastResource->src() ne ''))  {
 3753:             if ($lastResource->symb() eq $symb) {
 3754:                 $islast = 1;
 3755:             } else {
 3756:                 $islast = 0;
 3757:             }
 3758:         } else {
 3759:             my $currRes = $self->getBySymb($symb);
 3760:             if (ref($currRes)) {
 3761:                 my $it = $self->getIterator($currRes,undef,undef,1);
 3762:                 while ( my $res=$it->next()) {
 3763:                     if ((ref($res)) && ($res->src() ne '') && (!$res->is_map())) {
 3764:                         if ($res->symb() eq $symb) {
 3765:                             $islast = 1;
 3766:                         } else {
 3767:                             $islast = 0;
 3768:                         }
 3769:                         last;
 3770:                     }
 3771:                 }
 3772:             }
 3773:         }
 3774:     }
 3775:     return $islast;
 3776: }
 3777: 
 3778: 1;
 3779: 
 3780: package Apache::lonnavmaps::iterator;
 3781: use Scalar::Util qw(weaken);
 3782: use Apache::lonnet;
 3783: 
 3784: =pod
 3785: 
 3786: =back
 3787: 
 3788: =head1 Object: navmap Iterator
 3789: 
 3790: An I<iterator> encapsulates the logic required to traverse a data
 3791: structure. navmap uses an iterator to traverse the course map
 3792: according to the criteria you wish to use.
 3793: 
 3794: To obtain an iterator, call the B<getIterator>() function of a
 3795: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
 3796: directly.) This will return a reference to the iterator:
 3797: 
 3798: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 3799: 
 3800: To get the next thing from the iterator, call B<next>:
 3801: 
 3802: C<my $nextThing = $resourceIterator-E<gt>next()>
 3803: 
 3804: getIterator behaves as follows:
 3805: 
 3806: =over 4
 3807: 
 3808: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap, $deeplinklisted):
 3809: 
 3810: All parameters are optional. firstResource is a resource reference
 3811: corresponding to where the iterator should start. It defaults to
 3812: navmap->firstResource() for the corresponding nav map. finishResource
 3813: corresponds to where you want the iterator to end, defaulting to
 3814: navmap->finishResource(). filterHash is a hash used as a set
 3815: containing strings representing the resource IDs, defaulting to
 3816: empty. Condition is a 1 or 0 that sets what to do with the filter
 3817: hash: If a 0, then only resources that exist IN the filterHash will be
 3818: recursed on. If it is a 1, only resources NOT in the filterHash will
 3819: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
 3820: false (default), the iterator will only return the first level of map
 3821: that is not just a single, 'redirecting' map. If true, the iterator
 3822: will return all information, starting with the top-level map,
 3823: regardless of content. returnTopMap, if true (default false), will
 3824: cause the iterator to return the top-level map object (resource 0.0)
 3825: before anything else. deeplinklisted if true (default false), will
 3826: check "listed" status of a resource with a deeplink, and unless "absent"
 3827: will exclude deeplink checking when retrieving the browsePriv from
 3828: lonnet::allowed().
 3829: 
 3830: Thus, by default, only top-level resources will be shown. Change the
 3831: condition to a 1 without changing the hash, and all resources will be
 3832: shown. Changing the condition to 1 and including some values in the
 3833: hash will allow you to selectively suppress parts of the navmap, while
 3834: leaving it on 0 and adding things to the hash will allow you to
 3835: selectively add parts of the nav map. See the handler code for
 3836: examples.
 3837: 
 3838: The iterator will return either a reference to a resource object, or a
 3839: token representing something in the map, such as the beginning of a
 3840: new branch. The possible tokens are:
 3841: 
 3842: =over 4
 3843: 
 3844: =item * B<END_ITERATOR>:
 3845: 
 3846: The iterator has returned all that it's going to. Further calls to the
 3847: iterator will just produce more of these. This is a "false" value, and
 3848: is the only false value the iterator which will be returned, so it can
 3849: be used as a loop sentinel.
 3850: 
 3851: =item * B<BEGIN_MAP>:
 3852: 
 3853: A new map is being recursed into. This is returned I<after> the map
 3854: resource itself is returned.
 3855: 
 3856: =item * B<END_MAP>:
 3857: 
 3858: The map is now done.
 3859: 
 3860: =item * B<BEGIN_BRANCH>:
 3861: 
 3862: A branch is now starting. The next resource returned will be the first
 3863: in that branch.
 3864: 
 3865: =item * B<END_BRANCH>:
 3866: 
 3867: The branch is now done.
 3868: 
 3869: =back
 3870: 
 3871: The tokens are retreivable via methods on the iterator object, i.e.,
 3872: $iterator->END_MAP.
 3873: 
 3874: Maps can contain empty resources. The iterator will automatically skip
 3875: over such resources, but will still treat the structure
 3876: correctly. Thus, a complicated map with several branches, but
 3877: consisting entirely of empty resources except for one beginning or
 3878: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
 3879: but only one resource will be returned.
 3880: 
 3881: =back
 3882: 
 3883: =head2 Normal Usage
 3884: 
 3885: Normal usage of the iterator object is to do the following:
 3886: 
 3887:  my $it = $navmap->getIterator([your params here]);
 3888:  my $curRes;
 3889:  while ($curRes = $it->next()) {
 3890:    [your logic here]
 3891:  }
 3892: 
 3893: Note that inside of the loop, it's frequently useful to check if
 3894: "$curRes" is a reference or not with the reference function; only
 3895: resource objects will be references, and any non-references will 
 3896: be the tokens described above.
 3897: 
 3898: The next() routine can take two (optional) arguments:
 3899: closeAllPages - if true will not recurse down a .page
 3900: noblockcheck - passed to browsePriv() for passing as sixth arg to
 3901: call to lonnet::allowed. This needs to be set if retrieveResources
 3902: was already called from another routine called within lonnet::allowed, 
 3903: so as to prevent recursion.
 3904: 
 3905: Also note there is some old code floating around that tries to track
 3906: the depth of the iterator to see when it's done; do not copy that 
 3907: code. It is difficult to get right and harder to understand than
 3908: this. They should be migrated to this new style.
 3909: 
 3910: =cut
 3911: 
 3912: # Here are the tokens for the iterator:
 3913: 
 3914: sub END_ITERATOR { return 0; }
 3915: sub BEGIN_MAP { return 1; }    # begining of a new map
 3916: sub END_MAP { return 2; }      # end of the map
 3917: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 3918: sub END_BRANCH { return 4; }   # end of a branch
 3919: sub FORWARD { return 1; }      # go forward
 3920: sub BACKWARD { return 2; }
 3921: 
 3922: sub min {
 3923:     (my $a, my $b) = @_;
 3924:     if ($a < $b) { return $a; } else { return $b; }
 3925: }
 3926: 
 3927: sub new {
 3928:     # magic invocation to create a class instance
 3929:     my $proto = shift;
 3930:     my $class = ref($proto) || $proto;
 3931:     my $self = {};
 3932: 
 3933:     weaken($self->{NAV_MAP} = shift);
 3934:     return undef unless ($self->{NAV_MAP});
 3935: 
 3936:     $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
 3937:     $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};
 3938: 
 3939:     # Handle the parameters
 3940:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 3941:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 3942: 
 3943:     # If the given resources are just the ID of the resource, get the
 3944:     # objects
 3945:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 3946:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 3947:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 3948:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 3949: 
 3950:     $self->{FILTER} = shift;
 3951: 
 3952:     # A hash, used as a set, of resource already seen
 3953:     $self->{ALREADY_SEEN} = shift;
 3954:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 3955:     $self->{CONDITION} = shift;
 3956: 
 3957:     # Do we want to automatically follow "redirection" maps?
 3958:     $self->{FORCE_TOP} = shift;
 3959: 
 3960:     # Do we want to return the top-level map object (resource 0.0)?
 3961:     $self->{RETURN_0} = shift;
 3962:     # have we done that yet?
 3963:     $self->{HAVE_RETURNED_0} = 0;
 3964: 
 3965:     # Do we want to check the "listed" status for a resource for which
 3966:     # deeplinking applies.
 3967:     $self->{DEEPLINKLISTED} = shift;
 3968: 
 3969:     # Now, we need to pre-process the map, by walking forward and backward
 3970:     # over the parts of the map we're going to look at.
 3971: 
 3972:     # The processing steps are exactly the same, except for a few small 
 3973:     # changes, so I bundle those up in the following list of two elements:
 3974:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
 3975:     # first_resource).
 3976:     # This prevents writing nearly-identical code twice.
 3977:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
 3978:                         'FIRST_RESOURCE'],
 3979:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
 3980:                         'FINISH_RESOURCE'] );
 3981: 
 3982:     my $maxDepth = 0; # tracks max depth
 3983: 
 3984:     # If there is only one resource in this map, and it's a map, we
 3985:     # want to remember that, so the user can ask for the first map
 3986:     # that isn't just a redirector.
 3987:     my $resource; my $resourceCount = 0;
 3988: 
 3989:     # Documentation on this algorithm can be found in the CVS repository at 
 3990:     # /docs/lonnavdocs; these "**#**" markers correspond to documentation
 3991:     # in that file.
 3992:     # **1**
 3993: 
 3994:     foreach my $pass (@iterations) {
 3995:         my $direction = $pass->[0];
 3996:         my $valName = $pass->[1];
 3997:         my $nextResourceMethod = $pass->[2];
 3998:         my $firstResourceName = $pass->[3];
 3999: 
 4000:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
 4001:                                                             $self->{FIRST_RESOURCE},
 4002:                                                             $self->{FINISH_RESOURCE},
 4003:                                                             {}, undef, 0, $direction);
 4004:     
 4005:         # prime the recursion
 4006:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
 4007: 	$iterator->next();
 4008:         my $curRes = $iterator->next();
 4009: 	my $depth = 1;
 4010:         while ($depth > 0) {
 4011: 	    if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
 4012: 	    if ($curRes == $iterator->END_MAP()) { $depth--; }
 4013: 
 4014:             if (ref($curRes)) {
 4015:                 # If there's only one resource, this will save it
 4016:                 # we have to filter empty resources from consideration here,
 4017:                 # or even "empty", redirecting maps have two (start & finish)
 4018:                 # or three (start, finish, plus redirector)
 4019:                 if($direction == FORWARD && $curRes->src()) { 
 4020:                     $resource = $curRes; $resourceCount++; 
 4021:                 }
 4022:                 my $resultingVal = $curRes->{DATA}->{$valName};
 4023:                 my $nextResources = $curRes->$nextResourceMethod();
 4024:                 my $nextCount = scalar(@{$nextResources});
 4025: 
 4026:                 if ($nextCount == 1) { # **3**
 4027:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
 4028:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
 4029:                 }
 4030:                 
 4031:                 if ($nextCount > 1) { # **4**
 4032:                     foreach my $res (@{$nextResources}) {
 4033:                         my $current = $res->{DATA}->{$valName} || 999999999;
 4034:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
 4035:                     }
 4036:                 }
 4037:             }
 4038:             
 4039:             # Assign the final val (**2**)
 4040:             if (ref($curRes) && $direction == BACKWARD()) {
 4041:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
 4042:                                      $curRes->{DATA}->{BOT_UP_VAL});
 4043:                 
 4044:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
 4045:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
 4046:             }
 4047: 
 4048: 	    $curRes = $iterator->next();
 4049:         }
 4050:     }
 4051: 
 4052:     # Check: Was this only one resource, a map?
 4053:     if ($resourceCount == 1 && $resource->is_sequence() && !$self->{FORCE_TOP}) { 
 4054:         my $firstResource = $resource->map_start();
 4055:         my $finishResource = $resource->map_finish();
 4056: 	return Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 4057: 						 $finishResource, $self->{FILTER},
 4058: 						 $self->{ALREADY_SEEN}, 
 4059: 						 $self->{CONDITION},
 4060: 						 $self->{FORCE_TOP},
 4061:                                                  undef,$self->{DEEPLINKLISTED});
 4062:     }
 4063: 
 4064:     # Set up some bookkeeping information.
 4065:     $self->{CURRENT_DEPTH} = 0;
 4066:     $self->{MAX_DEPTH} = $maxDepth;
 4067:     $self->{STACK} = [];
 4068:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 4069:     $self->{FINISHED} = 0; # When true, the iterator has finished
 4070: 
 4071:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
 4072:         push @{$self->{STACK}}, [];
 4073:     }
 4074: 
 4075:     # Prime the recursion w/ the first resource **5**
 4076:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
 4077:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
 4078: 
 4079:     bless ($self);
 4080:     return $self;
 4081: }
 4082: 
 4083: sub next {
 4084:     my $self = shift;
 4085:     my $closeAllPages=shift;
 4086:     my $noblockcheck = shift;
 4087:     if ($self->{FINISHED}) {
 4088: 	return END_ITERATOR();
 4089:     }
 4090: 
 4091:     # If we want to return the top-level map object, and haven't yet,
 4092:     # do so.
 4093:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
 4094:         $self->{HAVE_RETURNED_0} = 1;
 4095: 	my $nextTopLevel = $self->{NAV_MAP}->getById('0.0');
 4096:         return $self->{NAV_MAP}->getById('0.0');
 4097:     }
 4098:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0_BEGIN_MAP}) {
 4099: 	$self->{HAVE_RETURNED_0_BEGIN_MAP} = 1;
 4100: 	return $self->BEGIN_MAP();
 4101:     }
 4102: 
 4103:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 4104:         # grab the next from the recursive iterator 
 4105:         my $next = $self->{RECURSIVE_ITERATOR}->next($closeAllPages);
 4106: 
 4107:         # is it a begin or end map? If so, update the depth
 4108:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 4109:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 4110: 
 4111:         # Are we back at depth 0? If so, stop recursing
 4112:         if ($self->{RECURSIVE_DEPTH} == 0) {
 4113:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 4114:         }
 4115:         return $next;
 4116:     }
 4117: 
 4118:     if (defined($self->{FORCE_NEXT})) {
 4119:         my $tmp = $self->{FORCE_NEXT};
 4120:         $self->{FORCE_NEXT} = undef;
 4121:         return $tmp;
 4122:     }
 4123: 
 4124:     # Have we not yet begun? If not, return BEGIN_MAP and
 4125:     # remember we've started.
 4126:     if ( !$self->{STARTED} ) { 
 4127:         $self->{STARTED} = 1;
 4128:         return $self->BEGIN_MAP();
 4129:     }
 4130: 
 4131:     # Here's the guts of the iterator.
 4132:     
 4133:     # Find the next resource, if any.
 4134:     my $found = 0;
 4135:     my $i = $self->{MAX_DEPTH};
 4136:     my $newDepth;
 4137:     my $here;
 4138:     while ( $i >= 0 && !$found ) {
 4139:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
 4140:             $here = pop @{$self->{STACK}->[$i]}; # **7**
 4141:             $found = 1;
 4142:             $newDepth = $i;
 4143:         }
 4144:         $i--;
 4145:     }
 4146: 
 4147:     # If we still didn't find anything, we're done.
 4148:     if ( !$found ) {
 4149:         # We need to get back down to the correct branch depth
 4150:         if ( $self->{CURRENT_DEPTH} > 0 ) {
 4151:             $self->{CURRENT_DEPTH}--;
 4152:             return END_BRANCH();
 4153:         } else {
 4154: 	    $self->{FINISHED} = 1;
 4155:             return END_MAP();
 4156:         }
 4157:     }
 4158: 
 4159:     # If this is not a resource, it must be an END_BRANCH marker we want
 4160:     # to return directly.
 4161:     if (!ref($here)) { # **8**
 4162:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
 4163:             $self->{CURRENT_DEPTH}--;
 4164:             return $here;
 4165:         }
 4166:     }
 4167: 
 4168:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
 4169:     $self->{HERE} = $here;
 4170: 
 4171:     # Get to the right level
 4172:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
 4173:         push @{$self->{STACK}->[$newDepth]}, $here;
 4174:         $self->{CURRENT_DEPTH}--;
 4175:         return END_BRANCH();
 4176:     }
 4177:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
 4178:         push @{$self->{STACK}->[$newDepth]}, $here;
 4179:         $self->{CURRENT_DEPTH}++;
 4180:         return BEGIN_BRANCH();
 4181:     }
 4182: 
 4183:     # If we made it here, we have the next resource, and we're at the
 4184:     # right branch level. So let's examine the resource for where
 4185:     # we can get to from here.
 4186: 
 4187:     # So we need to look at all the resources we can get to from here,
 4188:     # categorize them if we haven't seen them, remember if we have a new
 4189:     my $nextUnfiltered = $here->getNext();
 4190: 
 4191: 
 4192:     my $maxDepthAdded = -1;
 4193:     
 4194:     for (@$nextUnfiltered) {
 4195:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 4196:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
 4197:             push @{$self->{STACK}->[$depth]}, $_;
 4198:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
 4199:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
 4200:         }
 4201:     }
 4202: 
 4203:     # Is this the end of a branch? If so, all of the resources examined above
 4204:     # led to lower levels than the one we are currently at, so we push a END_BRANCH
 4205:     # marker onto the stack so we don't forget.
 4206:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
 4207:     # BC branch and gets to C, it will see F as the only next resource, but it's
 4208:     # one level lower. Thus, this is the end of the branch, since there are no
 4209:     # more resources added to this level or above.
 4210:     # We don't do this if the examined resource is the finish resource,
 4211:     # because the condition given above is true, but the "END_MAP" will
 4212:     # take care of things and we should already be at depth 0.
 4213:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
 4214:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
 4215:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
 4216:     }
 4217: 
 4218:     # That ends the main iterator logic. Now, do we want to recurse
 4219:     # down this map (if this resource is a map)?
 4220:     if ( ($self->{HERE}->is_sequence() || (!$closeAllPages && $self->{HERE}->is_page())) &&
 4221:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION}) &&
 4222:         ($env{'request.role.adv'} || !$self->{HERE}->randomout())) {
 4223:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 4224:         my $firstResource = $self->{HERE}->map_start();
 4225:         my $finishResource = $self->{HERE}->map_finish();
 4226:         $self->{RECURSIVE_ITERATOR} = 
 4227:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 4228:                                               $finishResource, $self->{FILTER},
 4229:                                               $self->{ALREADY_SEEN},
 4230: 					      $self->{CONDITION},
 4231: 					      $self->{FORCE_TOP},
 4232:                                               undef,$self->{DEEPLINKLISTED});
 4233:     }
 4234: 
 4235:     # If this is a blank resource, don't actually return it.
 4236:     # Should you ever find you need it, make sure to add an option to the code
 4237:     #  that you can use; other things depend on this behavior.
 4238:     my $browsePriv = $self->{HERE}->browsePriv($noblockcheck,$self->{DEEPLINKLISTED});
 4239:     if (!$self->{HERE}->src() || 
 4240:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
 4241:         return $self->next($closeAllPages);
 4242:     }
 4243: 
 4244:     return $self->{HERE};
 4245: 
 4246: }
 4247: 
 4248: =pod
 4249: 
 4250: The other method available on the iterator is B<getStack>, which
 4251: returns an array populated with the current 'stack' of maps, as
 4252: references to the resource objects. Example: This is useful when
 4253: making the navigation map, as we need to check whether we are under a
 4254: page map to see if we need to link directly to the resource, or to the
 4255: page. The first elements in the array will correspond to the top of
 4256: the stack (most inclusive map).
 4257: 
 4258: =cut
 4259: 
 4260: sub getStack {
 4261:     my $self=shift;
 4262: 
 4263:     my @stack;
 4264: 
 4265:     $self->populateStack(\@stack);
 4266: 
 4267:     return \@stack;
 4268: }
 4269: 
 4270: # Private method: Calls the iterators recursively to populate the stack.
 4271: sub populateStack {
 4272:     my $self=shift;
 4273:     my $stack = shift;
 4274: 
 4275:     push @$stack, $self->{HERE} if ($self->{HERE});
 4276: 
 4277:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 4278:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 4279:     }
 4280: }
 4281: 
 4282: 1;
 4283: 
 4284: package Apache::lonnavmaps::DFSiterator;
 4285: use Scalar::Util qw(weaken);
 4286: use Apache::lonnet;
 4287: 
 4288: # Not documented in the perldoc: This is a simple iterator that just walks
 4289: #  through the nav map and presents the resources in a depth-first search
 4290: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
 4291: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
 4292: #  useful for pre-processing of some kind, and is in fact used by the main
 4293: #  iterator that way, but that's about it.
 4294: # One could imagine merging this into the init routine of the main iterator,
 4295: #  but this might as well be left separate, since it is possible some other
 4296: #  use might be found for it. - Jeremy
 4297: 
 4298: # Unlike the main iterator, this DOES return all resources, even blank ones.
 4299: #  The main iterator needs them to correctly preprocess the map.
 4300: 
 4301: sub BEGIN_MAP { return 1; }    # begining of a new map
 4302: sub END_MAP { return 2; }      # end of the map
 4303: sub FORWARD { return 1; }      # go forward
 4304: sub BACKWARD { return 2; }
 4305: 
 4306: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
 4307: #         filter hash ref (or undef), already seen hash or undef, condition
 4308: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
 4309: sub new {
 4310:     # magic invocation to create a class instance
 4311:     my $proto = shift;
 4312:     my $class = ref($proto) || $proto;
 4313:     my $self = {};
 4314: 
 4315:     weaken($self->{NAV_MAP} = shift);
 4316:     return undef unless ($self->{NAV_MAP});
 4317: 
 4318:     $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
 4319:     $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};
 4320: 
 4321:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 4322:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 4323: 
 4324:     # If the given resources are just the ID of the resource, get the
 4325:     # objects
 4326:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 4327:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 4328:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 4329:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 4330: 
 4331:     $self->{FILTER} = shift;
 4332: 
 4333:     # A hash, used as a set, of resource already seen
 4334:     $self->{ALREADY_SEEN} = shift;
 4335:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 4336:     $self->{CONDITION} = shift;
 4337:     $self->{DIRECTION} = shift || FORWARD();
 4338: 
 4339:     # Flag: Have we started yet?
 4340:     $self->{STARTED} = 0;
 4341: 
 4342:     # Should we continue calling the recursive iterator, if any?
 4343:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 4344:     # The recursive iterator, if any
 4345:     $self->{RECURSIVE_ITERATOR} = undef;
 4346:     # Are we recursing on a map, or a branch?
 4347:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 4348:     # And the count of how deep it is, so that this iterator can keep track of
 4349:     # when to pick back up again.
 4350:     $self->{RECURSIVE_DEPTH} = 0;
 4351: 
 4352:     # For keeping track of our branches, we maintain our own stack
 4353:     $self->{STACK} = [];
 4354: 
 4355:     # Start with the first resource
 4356:     if ($self->{DIRECTION} == FORWARD) {
 4357:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
 4358:     } else {
 4359:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
 4360:     }
 4361: 
 4362:     bless($self);
 4363:     return $self;
 4364: }
 4365: 
 4366: sub next {
 4367:     my $self = shift;
 4368:     
 4369:     # Are we using a recursive iterator? If so, pull from that and
 4370:     # watch the depth; we want to resume our level at the correct time.
 4371:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 4372:         # grab the next from the recursive iterator
 4373:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 4374:         
 4375:         # is it a begin or end map? Update depth if so
 4376:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 4377:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 4378: 
 4379:         # Are we back at depth 0? If so, stop recursing.
 4380:         if ($self->{RECURSIVE_DEPTH} == 0) {
 4381:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 4382:         }
 4383:         
 4384:         return $next;
 4385:     }
 4386: 
 4387:     # Is there a current resource to grab? If not, then return
 4388:     # END_MAP, which will end the iterator.
 4389:     if (scalar(@{$self->{STACK}}) == 0) {
 4390:         return $self->END_MAP();
 4391:     }
 4392: 
 4393:     # Have we not yet begun? If not, return BEGIN_MAP and 
 4394:     # remember that we've started.
 4395:     if ( !$self->{STARTED} ) {
 4396:         $self->{STARTED} = 1;
 4397:         return $self->BEGIN_MAP;
 4398:     }
 4399: 
 4400:     # Get the next resource in the branch
 4401:     $self->{HERE} = pop @{$self->{STACK}};
 4402: 
 4403:     # remember that we've seen this, so we don't return it again later
 4404:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 4405:     
 4406:     # Get the next possible resources
 4407:     my $nextUnfiltered;
 4408:     if ($self->{DIRECTION} == FORWARD()) {
 4409:         $nextUnfiltered = $self->{HERE}->getNext();
 4410:     } else {
 4411:         $nextUnfiltered = $self->{HERE}->getPrevious();
 4412:     }
 4413:     my $next = [];
 4414: 
 4415:     # filter the next possibilities to remove things we've 
 4416:     # already seen.
 4417:     foreach my $item (@$nextUnfiltered) {
 4418:         if (!defined($self->{ALREADY_SEEN}->{$item->{ID}})) {
 4419:             push @$next, $item;
 4420:         }
 4421:     }
 4422: 
 4423:     while (@$next) {
 4424:         # copy the next possibilities over to the stack
 4425:         push @{$self->{STACK}}, shift @$next;
 4426:     }
 4427: 
 4428:     # If this is a map and we want to recurse down it... (not filtered out)
 4429:     if ($self->{HERE}->is_map() && 
 4430:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 4431:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 4432:         my $firstResource = $self->{HERE}->map_start();
 4433:         my $finishResource = $self->{HERE}->map_finish();
 4434: 
 4435:         $self->{RECURSIVE_ITERATOR} =
 4436:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
 4437:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 4438:                                              $self->{CONDITION}, $self->{DIRECTION});
 4439:     }
 4440: 
 4441:     return $self->{HERE};
 4442: }
 4443: 
 4444: # Identical to the full iterator methods of the same name. Hate to copy/paste
 4445: # but I also hate to "inherit" either iterator from the other.
 4446: 
 4447: sub getStack {
 4448:     my $self=shift;
 4449: 
 4450:     my @stack;
 4451: 
 4452:     $self->populateStack(\@stack);
 4453: 
 4454:     return \@stack;
 4455: }
 4456: 
 4457: # Private method: Calls the iterators recursively to populate the stack.
 4458: sub populateStack {
 4459:     my $self=shift;
 4460:     my $stack = shift;
 4461: 
 4462:     push @$stack, $self->{HERE} if ($self->{HERE});
 4463: 
 4464:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 4465:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 4466:     }
 4467: }
 4468: 
 4469: 1;
 4470: 
 4471: package Apache::lonnavmaps::resource;
 4472: use Scalar::Util qw(weaken);
 4473: use Apache::lonnet;
 4474: 
 4475: =pod
 4476: 
 4477: =head1 Object: resource 
 4478: 
 4479: X<resource, navmap object>
 4480: A resource object encapsulates a resource in a resource map, allowing
 4481: easy manipulation of the resource, querying the properties of the
 4482: resource (including user properties), and represents a reference that
 4483: can be used as the canonical representation of the resource by
 4484: lonnavmap clients like renderers.
 4485: 
 4486: A resource only makes sense in the context of a navmap, as some of the
 4487: data is stored in the navmap object.
 4488: 
 4489: You will probably never need to instantiate this object directly. Use
 4490: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
 4491: starting resource.
 4492: 
 4493: Resource objects respect the parameter_hiddenparts, which suppresses 
 4494: various parts according to the wishes of the map author. As of this
 4495: writing, there is no way to override this parameter, and suppressed
 4496: parts will never be returned, nor will their response types or ids be
 4497: stored.
 4498: 
 4499: =head2 Overview
 4500: 
 4501: A B<Resource> is the most granular type of object in LON-CAPA that can
 4502: be included in a course. It can either be a particular resource, like
 4503: an HTML page, external resource, problem, etc., or it can be a
 4504: container sequence, such as a "page" or a "map".
 4505: 
 4506: To see a sequence from the user's point of view, please see the
 4507: B<Creating a Course: Maps and Sequences> chapter of the Author's
 4508: Manual.
 4509: 
 4510: A Resource Object, once obtained from a navmap object via a B<getBy*>
 4511: method of the navmap, or from an iterator, allows you to query
 4512: information about that resource.
 4513: 
 4514: Generally, you do not ever want to create a resource object yourself,
 4515: so creation has been left undocumented. Always retrieve resources
 4516: from navmap objects.
 4517: 
 4518: =head3 Identifying Resources
 4519: 
 4520: X<big hash>Every resource is identified by a Resource ID in the big hash that is
 4521: unique to that resource for a given course. X<resource ID, in big hash>
 4522: The Resource ID has the form #.#, where the first number is the same
 4523: for every resource in a map, and the second is unique. For instance,
 4524: for a course laid out like this:
 4525: 
 4526:  * Problem 1
 4527:  * Map
 4528:    * Resource 2
 4529:    * Resource 3
 4530: 
 4531: C<Problem 1> and C<Map> will share a first number, and C<Resource 2>
 4532: C<Resource 3> will share a first number. The second number may end up
 4533: re-used between the two groups.
 4534: 
 4535: The resource ID is only used in the big hash, but can be used in the
 4536: context of a course to identify a resource easily. (For instance, the
 4537: printing system uses it to record which resources from a sequence you 
 4538: wish to print.)
 4539: 
 4540: X<symb> X<resource, symb>
 4541: All resources also have B<symb>s, which uniquely identify a resource
 4542: in a course. Many internal LON-CAPA functions expect a symb. A symb
 4543: carries along with it the URL of the resource, and the map it appears
 4544: in. Symbs are much larger than resource IDs.
 4545: 
 4546: =cut
 4547: 
 4548: sub new {
 4549:     # magic invocation to create a class instance
 4550:     my $proto = shift;
 4551:     my $class = ref($proto) || $proto;
 4552:     my $self = {};
 4553: 
 4554:     weaken($self->{NAV_MAP} = shift);
 4555:     $self->{ID} = shift;
 4556: 
 4557:     $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
 4558:     $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};
 4559: 
 4560:     # Store this new resource in the parent nav map's cache.
 4561:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 4562:     $self->{RESOURCE_ERROR} = 0;
 4563: 
 4564:     $self->{DUEDATE_CACHE} = undef;
 4565: 
 4566:     # A hash that can be used by two-pass algorithms to store data
 4567:     # about this resource in. Not used by the resource object
 4568:     # directly.
 4569:     $self->{DATA} = {};
 4570:     
 4571:     bless($self);
 4572:     
 4573:     # This is a speed optimization, to avoid calling symb() too often.
 4574:     $self->{SYMB} = $self->symb();
 4575: 
 4576:     return $self;
 4577: }
 4578: 
 4579: # private function: simplify the NAV_HASH lookups we keep doing
 4580: # pass the name, and to automatically append my ID, pass a true val on the
 4581: # second param
 4582: sub navHash {
 4583:     my $self = shift;
 4584:     my $param = shift;
 4585:     my $id = shift;
 4586:     my $arg = $param . ($id?$self->{ID}:"");
 4587:     if (ref($self) && ref($self->{NAV_MAP}) && defined($arg)) {
 4588:         return $self->{NAV_MAP}->navhash($arg);
 4589:     }
 4590:     return;
 4591: }
 4592: 
 4593: =pod
 4594: 
 4595: =head2 Methods
 4596: 
 4597: Once you have a resource object, here's what you can do with it:
 4598: 
 4599: =head3 Attribute Retrieval
 4600: 
 4601: Every resource has certain attributes that can be retrieved and used:
 4602: 
 4603: =over 4
 4604: 
 4605: =item * B<ID>: Every resource has an ID that is unique for that
 4606:     resource in the course it is in. The ID is actually in the hash
 4607:     representing the resource, so for a resource object $res, obtain
 4608:     it via C<$res->{ID}).
 4609: 
 4610: =item * B<compTitle>:
 4611: 
 4612: Returns a "composite title", that is equal to $res->title() if the
 4613: resource has a title, and is otherwise the last part of the URL (e.g.,
 4614: "problem.problem").
 4615: 
 4616: =item * B<ext>:
 4617: 
 4618: Returns true if the resource is external.
 4619: 
 4620: =item * B<kind>:
 4621: 
 4622: Returns the kind of the resource from the compiled nav map.
 4623: 
 4624: =item * B<randomout>:
 4625: 
 4626: Returns true if this resource was chosen to NOT be shown to the user
 4627: by the random map selection feature. In other words, this is usually
 4628: false.
 4629: 
 4630: =item * B<randompick>:
 4631: 
 4632: Returns the number of randomly picked items for a map if the randompick
 4633: feature is being used on the map. 
 4634: 
 4635: =item * B<randomorder>:
 4636: 
 4637: Returns true for a map if the randomorder feature is being used on the
 4638: map.
 4639: 
 4640: =item * B<src>:
 4641: 
 4642: Returns the source for the resource.
 4643: 
 4644: =item * B<symb>:
 4645: 
 4646: Returns the symb for the resource.
 4647: 
 4648: =item * B<title>:
 4649: 
 4650: Returns the title of the resource.
 4651: 
 4652: =back
 4653: 
 4654: =cut
 4655: 
 4656: # These info functions can be used directly, as they don't return
 4657: # resource information.
 4658: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
 4659: sub encrypted { my $self=shift; return $self->navHash("encrypted_", 1); }
 4660: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 4661: sub from { my $self=shift; return $self->navHash("from_", 1); }
 4662: # considered private and undocumented
 4663: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 4664: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 4665: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 4666: sub deeplinkout { my $self=shift; return $self->navHash("deeplinkout_", 1); }
 4667: sub randompick { 
 4668:     my $self = shift;
 4669:     my $randompick = $self->parmval('randompick');
 4670:     return $randompick;
 4671: }
 4672: sub randomorder { 
 4673:     my $self = shift;
 4674:     my $randomorder = $self->parmval('randomorder');
 4675:     return ($randomorder =~ /^yes$/i);
 4676: }
 4677: sub link {
 4678:     my $self=shift;
 4679:     if ($self->encrypted()) { return &Apache::lonenc::encrypted($self->src); }
 4680:     return $self->src;
 4681: }
 4682: sub src { 
 4683:     my $self=shift;
 4684:     return $self->navHash("src_", 1);
 4685: }
 4686: sub shown_symb {
 4687:     my $self=shift;
 4688:     if ($self->encrypted()) {return &Apache::lonenc::encrypted($self->{SYMB});}
 4689:     return $self->{SYMB};
 4690: }
 4691: sub id {
 4692:     my $self=shift;
 4693:     return $self->{ID};
 4694: }
 4695: sub enclosing_map_src {
 4696:     my $self=shift;
 4697:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 4698:     return $self->navHash('map_id_'.$first);
 4699: }
 4700: sub symb {
 4701:     my $self=shift;
 4702:     if (defined $self->{SYMB}) { return $self->{SYMB}; }
 4703:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 4704:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 4705:     my $symb = &Apache::lonnet::declutter($self->navHash('map_id_'.$first)) 
 4706:         . '___' . $second . '___' . $symbSrc;
 4707:     return &Apache::lonnet::symbclean($symb);
 4708: }
 4709: sub wrap_symb {
 4710:     my $self = shift;
 4711:     return $self->{NAV_MAP}->wrap_symb($self->{SYMB});
 4712: }
 4713: sub title { 
 4714:     my $self=shift; 
 4715:     if ($self->{ID} eq '0.0') {
 4716: 	# If this is the top-level map, return the title of the course
 4717: 	# since this map can not be titled otherwise.
 4718: 	return $env{'course.'.$env{'request.course.id'}.'.description'};
 4719:     }
 4720:     return $self->navHash("title_", 1); }
 4721: # considered private and undocumented
 4722: sub to { my $self=shift; return $self->navHash("to_", 1); }
 4723: sub condition {
 4724:     my $self=shift;
 4725:     my $undercond=$self->navHash("undercond_", 1);
 4726:     if (!defined($undercond)) { return 1; };
 4727:     my $condid=$self->navHash("condid_$undercond");
 4728:     if (!defined($condid)) { return 1; };
 4729:     my $condition=&Apache::lonnet::directcondval($condid);
 4730:     return $condition;
 4731: }
 4732: sub condval {
 4733:     my $self=shift;
 4734:     my ($pathname,$filename) = 
 4735: 	&Apache::lonnet::split_uri_for_cond($self->src());
 4736: 
 4737:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4738: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4739:     if ($match) {
 4740: 	return &Apache::lonnet::condval($1);
 4741:     }
 4742:     return 0;
 4743: }
 4744: sub compTitle {
 4745:     my $self = shift;
 4746:     my $title = $self->title();
 4747:     $title=~s/\&colon\;/\:/gs;
 4748:     if (!$title) {
 4749:         $title = $self->src();
 4750:         $title = substr($title, rindex($title, '/') + 1);
 4751:     }
 4752:     return $title;
 4753: }
 4754: 
 4755: =pod
 4756: 
 4757: B<Predicate Testing the Resource>
 4758: 
 4759: These methods are shortcuts to deciding if a given resource has a given property.
 4760: 
 4761: =over 4
 4762: 
 4763: =item * B<is_map>:
 4764: 
 4765: Returns true if the resource is a map type.
 4766: 
 4767: =item * B<is_problem>:
 4768: 
 4769: Returns true if the resource is a problem type, false
 4770: otherwise. (Looks at the extension on the src field; might need more
 4771: to work correctly.)
 4772: 
 4773: =item * B<is_page>:
 4774: 
 4775: Returns true if the resource is a page.
 4776: 
 4777: =item * B<is_sequence>:
 4778: 
 4779: Returns true if the resource is a sequence.
 4780: 
 4781: =back
 4782: 
 4783: =cut
 4784: 
 4785: sub hasResource {
 4786:    my $self = shift;
 4787:    return $self->{NAV_MAP}->hasResource(@_);
 4788: }
 4789: 
 4790: sub retrieveResources {
 4791:    my $self = shift;
 4792:    return $self->{NAV_MAP}->retrieveResources(@_);
 4793: }
 4794: 
 4795: sub is_exam {
 4796:     my ($self,$part) = @_;
 4797:     my $type = $self->parmval('type',$part);
 4798:     if ($type eq 'exam') {
 4799:         return 1;
 4800:     }
 4801:     if ($self->src() =~ /\.(exam)$/) {
 4802:         return 1;
 4803:     }
 4804:     return 0;
 4805: }
 4806: sub is_html {
 4807:     my $self=shift;
 4808:     my $src = $self->src();
 4809:     return ($src =~ /html$/);
 4810: }
 4811: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 4812: sub is_page {
 4813:     my $self=shift;
 4814:     my $src = $self->src();
 4815:     return $self->navHash("is_map_", 1) && 
 4816: 	$self->navHash("map_type_" . $self->map_pc()) eq 'page';
 4817: }
 4818: sub is_practice {
 4819:     my $self=shift;
 4820:     my ($part) = @_;
 4821:     my $type = $self->parmval('type',$part);
 4822:     if ($type eq 'practice') {
 4823:         return 1;
 4824:     }
 4825:     return 0;
 4826: }
 4827: sub is_problem {
 4828:     my $self=shift;
 4829:     my $src = $self->src();
 4830:     if ($src =~ /$LONCAPA::assess_re/) {
 4831: 	return !($self->is_practice());
 4832:     }
 4833:     return 0;
 4834: }
 4835: sub is_tool {
 4836:     my $self=shift;
 4837:     my $src = $self->src();
 4838:     return ($src =~ /ext\.tool$/);
 4839: }
 4840: sub is_gradable {
 4841:     my $self=shift;
 4842:     my $src = $self->src();
 4843:     if (($src =~ /$LONCAPA::assess_re/) ||
 4844:         (($self->is_tool()) && ($self->parmval('gradable',0) =~ /^yes$/i))) {
 4845:         return !($self->is_practice());
 4846:     }
 4847: }
 4848: #
 4849: #  The has below is the set of status that are considered 'incomplete'
 4850: #
 4851: my %incomplete_hash = 
 4852: (
 4853:  TRIES_LEFT()     => 1,
 4854:  OPEN()           => 1,
 4855:  ATTEMPTED()      => 1
 4856: 
 4857:  );
 4858: #
 4859: #  Return tru if a problem is incomplete... for now incomplete means that
 4860: #  any part of the problem is incomplete. 
 4861: #  Note that if the resources is not a problem, 0 is returned.
 4862: #
 4863: sub is_incomplete {
 4864:     my $self = shift;
 4865:     if ($self->is_problem()) {
 4866: 	foreach my $part (@{$self->parts()}) {
 4867: 	    if (exists($incomplete_hash{$self->status($part)})) {
 4868: 		return 1;
 4869: 	    }
 4870: 	}
 4871:     }
 4872:     return 0;
 4873:        
 4874: }
 4875: sub is_raw_problem {
 4876:     my $self=shift;
 4877:     my $src = $self->src();
 4878:     if ($src =~ /$LONCAPA::assess_re/) {
 4879:         return 1;
 4880:     }
 4881:     return 0;
 4882: }
 4883: 
 4884: sub contains_problem {
 4885:     my $self=shift;
 4886:     if ($self->is_page()) {
 4887: 	my $hasProblem=$self->hasResource($self,sub { $_[0]->is_problem() },1);
 4888: 	return $hasProblem;
 4889:     }
 4890:     return 0;
 4891: }
 4892: sub map_contains_problem {
 4893:     my $self=shift;
 4894:     if ($self->is_map()) {
 4895: 	my $has_problem=
 4896: 	    $self->hasResource($self,sub { $_[0]->is_problem() },1);
 4897: 	return $has_problem;
 4898:     }
 4899:     return 0;
 4900: }
 4901: sub is_sequence {
 4902:     my $self=shift;
 4903:     return $self->navHash("is_map_", 1) && 
 4904:     $self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
 4905: }
 4906: sub is_missing_map {
 4907:     my $self=shift;
 4908:     return $self->navHash("is_map_", 1) &&
 4909:     $self->navHash("map_type_" . $self->map_pc()) eq 'none';
 4910: }
 4911: sub is_survey {
 4912:     my $self = shift();
 4913:     my $part = shift();
 4914:     my $type = $self->parmval('type',$part);
 4915:     if (($type eq 'survey') || ($type eq 'surveycred')) {
 4916:         return 1;
 4917:     }
 4918:     if ($self->src() =~ /\.(survey)$/) {
 4919:         return 1;
 4920:     }
 4921:     return 0;
 4922: }
 4923: sub is_anonsurvey {
 4924:     my $self = shift();
 4925:     my $part = shift();
 4926:     my $type = $self->parmval('type',$part);
 4927:     if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4928:         return 1;
 4929:     }
 4930:     return 0;
 4931: }
 4932: sub is_task {
 4933:     my $self=shift;
 4934:     my $src = $self->src();
 4935:     return ($src =~ /\.(task)$/)
 4936: }
 4937: 
 4938: sub is_empty_sequence {
 4939:     my $self=shift;
 4940:     return !$self->is_page() && $self->navHash("is_map_", 1) && !$self->navHash("map_type_" . $self->map_pc());
 4941: }
 4942: 
 4943: # Private method: Shells out to the parmval in the nav map, handler parts.
 4944: sub parmval {
 4945:     my $self = shift;
 4946:     my $what = shift;
 4947:     my $part = shift;
 4948:     if (!defined($part)) { 
 4949:         $part = '0'; 
 4950:     }
 4951:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->{SYMB});
 4952: }
 4953: 
 4954: =pod
 4955: 
 4956: B<Map Methods>
 4957: 
 4958: These methods are useful for getting information about the map
 4959: properties of the resource, if the resource is a map (B<is_map>).
 4960: 
 4961: =over 4
 4962: 
 4963: =item * B<map_finish>:
 4964: 
 4965: Returns a reference to a resource object corresponding to the finish
 4966: resource of the map.
 4967: 
 4968: =item * B<map_pc>:
 4969: 
 4970: Returns the pc value of the map, which is the first number that
 4971: appears in the resource ID of the resources in the map, and is the
 4972: number that appears around the middle of the symbs of the resources in
 4973: that map.
 4974: 
 4975: =item * B<map_start>:
 4976: 
 4977: Returns a reference to a resource object corresponding to the start
 4978: resource of the map.
 4979: 
 4980: =item * B<map_type>:
 4981: 
 4982: Returns a string with the type of the map in it.
 4983: 
 4984: =item * B<map_hierarchy>:
 4985: 
 4986: Returns a string with a comma-separated ordered list of map_pc IDs
 4987: for the hierarchy of maps containing a map, with the top level
 4988: map first, then descending to deeper levels, with the enclosing map last.
 4989: 
 4990: =item * B<map_breadcrumbs>:
 4991: 
 4992: Same as map_hierarchy, except maps containing only a single itemm if
 4993: it's a map, or containing no items are omitted, unless it's the top
 4994: level map (map_pc = 1), which is always included.
 4995: 
 4996: =back
 4997: 
 4998: =cut
 4999: 
 5000: sub map_finish {
 5001:     my $self = shift;
 5002:     my $src = $self->src();
 5003:     $src = &Apache::lonnet::clutter($src);
 5004:     my $res = $self->navHash("map_finish_$src", 0);
 5005:     $res = $self->{NAV_MAP}->getById($res);
 5006:     return $res;
 5007: }
 5008: sub map_pc {
 5009:     my $self = shift;
 5010:     my $src = $self->src();
 5011:     return $self->navHash("map_pc_$src", 0);
 5012: }
 5013: sub map_start {
 5014:     my $self = shift;
 5015:     my $src = $self->src();
 5016:     $src = &Apache::lonnet::clutter($src);
 5017:     my $res = $self->navHash("map_start_$src", 0);
 5018:     $res = $self->{NAV_MAP}->getById($res);
 5019:     return $res;
 5020: }
 5021: sub map_type {
 5022:     my $self = shift;
 5023:     my $pc = $self->map_pc();
 5024:     return $self->navHash("map_type_$pc", 0);
 5025: }
 5026: sub map_hierarchy {
 5027:     my $self = shift;
 5028:     my $pc = $self->map_pc();
 5029:     return $self->navHash("map_hierarchy_$pc", 0);
 5030: }
 5031: sub map_breadcrumbs {
 5032:     my $self = shift;
 5033:     my $pc = $self->map_pc();
 5034:     return $self->navHash("map_breadcrumbs_$pc", 0);
 5035: }
 5036: 
 5037: #####
 5038: # Property queries
 5039: #####
 5040: 
 5041: # These functions will be responsible for returning the CORRECT
 5042: # VALUE for the parameter, no matter what. So while they may look
 5043: # like direct calls to parmval, they can be more than that.
 5044: # So, for instance, the duedate function should use the "duedatetype"
 5045: # information, rather than the resource object user.
 5046: 
 5047: =pod
 5048: 
 5049: =head2 Resource Parameters
 5050: 
 5051: In order to use the resource parameters correctly, the nav map must
 5052: have been instantiated with genCourseAndUserOptions set to true, so
 5053: the courseopt and useropt is read correctly. Then, you can call these
 5054: functions to get the relevant parameters for the resource. Each
 5055: function defaults to part "0", but can be directed to another part by
 5056: passing the part as the parameter.
 5057: 
 5058: These methods are responsible for getting the parameter correct, not
 5059: merely reflecting the contents of the GDBM hashes. As we move towards
 5060: dates relative to other dates, these methods should be updated to
 5061: reflect that. (Then, anybody using these methods will not have to update
 5062: their code.)
 5063: 
 5064: =over 4
 5065: 
 5066: 
 5067: =item * B<printable>
 5068: 
 5069: returns true if the current date is such that the 
 5070: specified resource part is printable.
 5071: 
 5072: 
 5073: =item * B<resprintable>
 5074: 
 5075: Returns true if all parts in the resource are printable making the
 5076: entire resource printable.
 5077: 
 5078: =item * B<acc>
 5079: 
 5080: Get the Client IP/Name Access Control information.
 5081: 
 5082: =item * B<answerdate>:
 5083: 
 5084: Get the answer-reveal date for the problem.
 5085: 
 5086: =item * B<awarded>: 
 5087: 
 5088: Gets the awarded value for the problem part. Requires genUserData set to
 5089: true when the navmap object was created.
 5090: 
 5091: =item * B<duedate>:
 5092: 
 5093: Get the due date for the problem.
 5094: 
 5095: =item * B<tries>:
 5096: 
 5097: Get the number of tries the student has used on the problem.
 5098: 
 5099: =item * B<maxtries>:
 5100: 
 5101: Get the number of max tries allowed.
 5102: 
 5103: =item * B<opendate>:
 5104: 
 5105: Get the open date for the problem.
 5106: 
 5107: =item * B<sig>:
 5108: 
 5109: Get the significant figures setting.
 5110: 
 5111: =item * B<tol>:
 5112: 
 5113: Get the tolerance for the problem.
 5114: 
 5115: =item * B<tries>:
 5116: 
 5117: Get the number of tries the user has already used on the problem.
 5118: 
 5119: =item * B<type>:
 5120: 
 5121: Get the question type for the problem.
 5122: 
 5123: =item * B<weight>:
 5124: 
 5125: Get the weight for the problem.
 5126: 
 5127: =back
 5128: 
 5129: =cut
 5130: 
 5131: 
 5132: 
 5133: 
 5134: sub printable {
 5135: 
 5136:     my ($self, $part) = @_;
 5137: 
 5138:     #  The following cases apply:
 5139:     #  - If a start date is not set, it is replaced by the open date.
 5140:     #  - Ditto for start/open replaced by content open.
 5141:     #  - If neither start nor printdates are set the part is printable.
 5142:     #  - Start date set but no end date: Printable if now >= start date.
 5143:     #  - End date set but no start date: Printable if now <= end date.
 5144:     #  - both defined: printable if start <= now <= end
 5145:     #
 5146: 
 5147:     # Get the print open/close dates for the resource.
 5148: 
 5149:     my $start = $self->parmval("printstartdate", $part);
 5150:     my $end   = $self->parmval("printenddate", $part);
 5151: 
 5152:     if (!$start) {
 5153: 	$start = $self->parmval("opendate", $part);
 5154:     }
 5155:     if (!$start) {
 5156: 	$start = $self->parmval("contentopen", $part);
 5157:     }
 5158: 
 5159: 
 5160:     my $now  = time();
 5161: 
 5162: 
 5163:     my $startok = 1;
 5164:     my $endok   = 1;
 5165: 
 5166:     if ((defined $start) && ($start ne '')) {
 5167: 	$startok = $start <= $now;
 5168:     }
 5169:     if ((defined $end) && ($end != '')) {
 5170: 	$endok = $end >= $now;
 5171:     }
 5172:     return $startok && $endok;
 5173: }
 5174: 
 5175: sub resprintable {
 5176:     my $self = shift;
 5177: 
 5178:     # get parts...or realize there are no parts.
 5179: 
 5180:     my $partsref = $self->parts();
 5181:     my @parts    = @$partsref;
 5182: 
 5183:     if (!@parts) {
 5184: 	return $self->printable(0);
 5185:     } else {
 5186: 	foreach my $part  (@parts) {
 5187: 	    if (!$self->printable($part)) { 
 5188: 		return 0; 
 5189: 	    }
 5190: 	}
 5191: 	return 1;
 5192:     }
 5193: }
 5194: 
 5195: sub acc {
 5196:     (my $self, my $part) = @_;
 5197:     my $acc = $self->parmval("acc", $part);
 5198:     return $acc;
 5199: }
 5200: sub answerdate {
 5201:     (my $self, my $part) = @_;
 5202:     # Handle intervals
 5203:     my $answerdatetype = $self->parmval("answerdate.type", $part);
 5204:     my $answerdate = $self->parmval("answerdate", $part);
 5205:     my $duedate = $self->parmval("duedate", $part);
 5206:     if ($answerdatetype eq 'date_interval') {
 5207:         $answerdate = $duedate + $answerdate; 
 5208:     }
 5209:     return $answerdate;
 5210: }
 5211: sub awarded { 
 5212:     my $self = shift; my $part = shift;
 5213:     $self->{NAV_MAP}->get_user_data();
 5214:     if (!defined($part)) { $part = '0'; }
 5215:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.awarded'};
 5216: }
 5217: sub latefrac {
 5218:     my $self = shift; my $part = shift;
 5219:     $self->{NAV_MAP}->get_user_data();
 5220:     if (!defined($part)) { $part = '0'; }
 5221:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.latefrac'};
 5222: }
 5223: sub taskversion {
 5224:     my $self = shift; my $part = shift;
 5225:     $self->{NAV_MAP}->get_user_data();
 5226:     if (!defined($part)) { $part = '0'; }
 5227:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.version'};
 5228: }
 5229: sub taskstatus {
 5230:     my $self = shift; my $part = shift;
 5231:     $self->{NAV_MAP}->get_user_data();
 5232:     if (!defined($part)) { $part = '0'; }
 5233:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$self->taskversion($part).'.'.$part.'.status'};
 5234: }
 5235: sub solved {
 5236:     my $self = shift; my $part = shift;
 5237:     $self->{NAV_MAP}->get_user_data();
 5238:     if (!defined($part)) { $part = '0'; }
 5239:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.solved'};
 5240: }
 5241: sub checkedin {
 5242:     my $self = shift; my $part = shift;
 5243:     $self->{NAV_MAP}->get_user_data();
 5244:     if (!defined($part)) { $part = '0'; }
 5245:     if ($self->is_task()) {
 5246:         my $version = $self->taskversion($part);
 5247:         return ($self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$version .'.'.$part.'.checkedin'},$self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$version .'.'.$part.'.checkedin.slot'});
 5248:     } else {
 5249:         return ($self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.checkedin'},$self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.checkedin.slot'});
 5250:     }
 5251: }
 5252: # this should work exactly like the copy in lonhomework.pm
 5253: # Why is there a copy in lonhomework?  Why not centralized?
 5254: #
 5255: #  TODO: Centralize duedate.
 5256: #
 5257: 
 5258: sub duedate {
 5259:     (my $self, my $part) = @_;
 5260:     if (defined ($self->{DUEDATE_CACHE}->{$part})) {
 5261:         return $self->{DUEDATE_CACHE}->{$part};
 5262:     }
 5263:     my $date;
 5264:     my @interval=$self->parmval("interval", $part);
 5265:     my $due_date=$self->parmval("duedate", $part);
 5266:     if ($interval[0] =~ /^(\d+)/) {
 5267:         my $timelimit = $1;
 5268:         my $first_access=&Apache::lonnet::get_first_access($interval[1],
 5269:                                                            $self->{SYMB});
 5270: 	if (defined($first_access)) {
 5271:             my $interval = $first_access+$timelimit;
 5272: 	    $date = (!$due_date || $interval < $due_date) ? $interval 
 5273:                                                           : $due_date;
 5274: 	} else {
 5275: 	    $date = $due_date;
 5276: 	}
 5277:     } else {
 5278: 	$date = $due_date;
 5279:     }
 5280:     $self->{DUEDATE_CACHE}->{$part} = $date;
 5281:     return $date;
 5282: }
 5283: sub handgrade {
 5284:     (my $self, my $part) = @_;
 5285:     my @response_ids = $self->responseIds($part);
 5286:     if (@response_ids) {
 5287: 	foreach my $response_id (@response_ids) {
 5288:             my $handgrade = $self->parmval("handgrade",$part.'_'.$response_id);
 5289: 	    if (lc($handgrade) eq 'yes') {
 5290: 		return 'yes';
 5291: 	    }
 5292: 	}
 5293:     }
 5294:     my $handgrade = $self->parmval("handgrade", $part);
 5295:     return $handgrade;
 5296: }
 5297: sub maxtries {
 5298:     (my $self, my $part) = @_;
 5299:     my $maxtries = $self->parmval("maxtries", $part);
 5300:     return $maxtries;
 5301: }
 5302: sub opendate {
 5303:     (my $self, my $part) = @_;
 5304:     my $opendatetype = $self->parmval("opendate.type", $part);
 5305:     my $opendate = $self->parmval("opendate", $part); 
 5306:     if ($opendatetype eq 'date_interval') {
 5307:         my $duedate = $self->duedate($part);
 5308:         $opendate = $duedate - $opendate; 
 5309:     }
 5310:     return $opendate;
 5311: }
 5312: sub overduedate {
 5313:     my ($self,$part) = @_;
 5314:     my $duedate = $self->parmval("duedate", $part);
 5315:     my $overduedate;
 5316:     if ($duedate) {
 5317:         my $grace = $self->parmval("grace", $part);
 5318:         if ($grace) {
 5319:             my $grace_end = (split(/,/,$grace))[-1];
 5320:             my ($offset) = split(/:/,$grace_end,2);
 5321:             if ($offset > 0) {
 5322:                 $overduedate = $offset + $duedate;
 5323:             }
 5324:         }
 5325:     }
 5326:     return $overduedate;
 5327: }
 5328: sub partial_credit_overdue {
 5329:     my ($self,$part) = @_;
 5330:     my $reduction;
 5331:     my $duedate = $self->parmval("duedate", $part);
 5332:     if ($duedate) {
 5333:         my $grace = $self->parmval("grace",$part);
 5334:         if ($grace) {
 5335:             my $lateness = time - $duedate;
 5336:             if ($lateness > 0) {
 5337:                 my ($start,$end,$startfrac,$endfrac,$usegrad);
 5338:                 $start = 0;
 5339:                 $startfrac = 1.0;
 5340:                 $usegrad = 0;
 5341:                 foreach my $item (split(/,/,$grace)) {
 5342:                     my ($offset,$frac,$grad) = split(/:/,$item);
 5343:                     if ($lateness > $offset) {
 5344:                         $start = $offset;
 5345:                         $startfrac = $frac;
 5346:                         next;
 5347:                     } elsif ($lateness <= $offset) {
 5348:                         $end = $offset;
 5349:                         $endfrac = $frac;
 5350:                         $usegrad = $grad;
 5351:                         last;
 5352:                     }
 5353:                 }
 5354:                 if ($end) {
 5355:                     if (($end == $start) || ($startfrac == $endfrac)) {
 5356:                         $reduction = $endfrac;
 5357:                     } elsif ($end - $start > 0) {
 5358:                         if (($endfrac <= 1.0) && ($endfrac >= 0)) {
 5359:                             $reduction = $endfrac;
 5360:                             if ($usegrad) {
 5361:                                 my $decline = $startfrac - $endfrac;
 5362:                                 my $fraction = ($lateness - $start)/($end - $start);
 5363:                                 if (($fraction <= 1) && ($fraction >= 0)) {
 5364:                                     my $value = $startfrac - ($decline*$fraction);
 5365:                                     $reduction = sprintf("%.2f", $value);
 5366:                                 }
 5367:                             }
 5368:                         }
 5369:                     }
 5370:                 }
 5371:             }
 5372:         }
 5373:     }
 5374:     return $reduction;
 5375: }
 5376: 
 5377: sub problemstatus {
 5378:     (my $self, my $part) = @_;
 5379:     my $problemstatus = $self->parmval("problemstatus", $part);
 5380:     return lc($problemstatus);
 5381: }
 5382: sub sig {
 5383:     (my $self, my $part) = @_;
 5384:     my $sig = $self->parmval("sig", $part);
 5385:     return $sig;
 5386: }
 5387: sub tol {
 5388:     (my $self, my $part) = @_;
 5389:     my $tol = $self->parmval("tol", $part);
 5390:     return $tol;
 5391: }
 5392: sub tries {
 5393:     my $self = shift; 
 5394:     my $tries = $self->queryRestoreHash('tries', shift);
 5395:     if (!defined($tries)) { return '0';}
 5396:     return $tries;
 5397: }
 5398: sub type {
 5399:     (my $self, my $part) = @_;
 5400:     my $type = $self->parmval("type", $part);
 5401:     return $type;
 5402: }
 5403: sub weight { 
 5404:     my $self = shift; my $part = shift;
 5405:     if (!defined($part)) { $part = '0'; }
 5406:     my $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 5407:                                 $self->{SYMB}, $self->{DOMAIN},
 5408:                                 $self->{USERNAME},
 5409:                                 $self->{SECTION});  
 5410:     return $weight;
 5411: }
 5412: sub part_display {
 5413:     my $self= shift(); my $partID = shift();
 5414:     if (! defined($partID)) { $partID = '0'; }
 5415:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',
 5416:                                      $self->{SYMB});
 5417:     if (! defined($display) || $display eq '') {
 5418:         $display = $partID;
 5419:     }
 5420:     return $display;
 5421: }
 5422: sub slot_control {
 5423:     my $self=shift(); my $part = shift();
 5424:     if (!defined($part)) { $part = '0'; }
 5425:     my $useslots = $self->parmval("useslots", $part);
 5426:     my $availablestudent = $self->parmval("availablestudent", $part);
 5427:     my $available = $self->parmval("available", $part); 
 5428:     return ($useslots,$availablestudent,$available);
 5429: }
 5430: sub deeplink {
 5431:     my ($self,$caller,$action) = @_;
 5432:     my $deeplink = $self->parmval("deeplink");
 5433:     if ($deeplink) {
 5434:         my ($state,$others,$listed,$scope) = split(/,/,$deeplink);
 5435:         if ($action eq 'getlisted') {
 5436:             return $listed;
 5437:         }
 5438:         if ($env{'request.deeplink.login'}) {
 5439:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5440:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5441:             my $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 5442:             if ($deeplink_symb) {
 5443:                 my ($loginmap,$mapname);
 5444:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 5445:                     $mapname = $self->enclosing_map_src();
 5446:                     $loginmap = &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 5447:                     return if ($mapname eq $loginmap);
 5448:                 } else {
 5449:                     return if ($deeplink_symb eq $self->symb());
 5450:                     if (($scope eq 'map') || ($scope eq 'rec')) {
 5451:                         $mapname = $self->enclosing_map_src();
 5452:                         $loginmap = &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($deeplink_symb))[0]);
 5453:                         return if ($mapname eq $loginmap);
 5454:                     }
 5455:                 }
 5456:                 if ($scope eq 'rec') {
 5457:                     my $map_pc = $self->navHash('map_pc_'.$mapname);
 5458:                     my @recurseup = split(/,/,$self->navHash('map_hierarchy_'.$map_pc));
 5459:                     my $login_pc = $self->navHash('map_pc_'.$loginmap);
 5460:                     return if (grep(/^\Q$login_pc\E$/,@recurseup));
 5461:                 }
 5462:             }
 5463:         }
 5464:         unless (($caller eq 'sequence') || ($state eq 'both')) {
 5465:             return $listed;
 5466:         }
 5467:     }
 5468:     return;
 5469: }
 5470: 
 5471: # Multiple things need this
 5472: sub getReturnHash {
 5473:     my $self = shift;
 5474:     
 5475:     if (!defined($self->{RETURN_HASH})) {
 5476:         #my %tmpHash  = &Apache::lonnet::restore($self->{SYMB},undef,$self->{DOMAIN},$self->{USERNAME});
 5477:         #$self->{RETURN_HASH} = \%tmpHash;
 5478:         # When info is retrieved for several resources (as when rendering a directory),
 5479:         # it is much faster to use the user profile dump and avoid repeated lonnet requests
 5480:         # (especially since lonnet::currentdump is using Lond directly whenever possible,
 5481:         # and lonnet::restore is not at this point).
 5482:         $self->{NAV_MAP}->get_user_data();
 5483:         $self->{RETURN_HASH} = $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}};
 5484:     }
 5485: }       
 5486: 
 5487: ######
 5488: # Status queries
 5489: ######
 5490: 
 5491: # These methods query the status of problems.
 5492: 
 5493: # If we need to count parts, this function determines the number of
 5494: # parts from the metadata. When called, it returns a reference to a list
 5495: # of strings corresponding to the parts. (Thus, using it in a scalar context
 5496: # tells you how many parts you have in the problem:
 5497: # $partcount = scalar($resource->countParts());
 5498: # Don't use $self->{PARTS} directly because you don't know if it's been
 5499: # computed yet.
 5500: 
 5501: =pod
 5502: 
 5503: =head2 Resource misc
 5504: 
 5505: Misc. functions for the resource.
 5506: 
 5507: =over 4
 5508: 
 5509: =item * B<hasDiscussion>:
 5510: 
 5511: Returns a false value if there has been discussion since the user last
 5512: logged in, true if there has. Always returns false if the discussion
 5513: data was not extracted when the nav map was constructed.
 5514: 
 5515: =item * B<last_post_time>:
 5516: 
 5517: Returns a false value if there hasn't been discussion otherwise returns
 5518: unix timestamp of last time a discussion posting (or edit) was made.
 5519: 
 5520: =item * B<discussion_info>:
 5521: 
 5522: optional argument is a filter (currently can be 'unread');
 5523: returns in scalar context the count of the number of discussion postings.
 5524: 
 5525: returns in list context both the count of postings and a hash ref
 5526: containing information about the postings (subject, id, timestamp) in a hash.
 5527: 
 5528: 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.
 5529: 
 5530: =item * B<getFeedback>:
 5531: 
 5532: Gets the feedback for the resource and returns the raw feedback string
 5533: for the resource, or the null string if there is no feedback or the
 5534: email data was not extracted when the nav map was constructed. Usually
 5535: used like this:
 5536: 
 5537:  for my $url (split(/\,/, $res->getFeedback())) {
 5538:     my $link = &escape($url);
 5539:     ...
 5540: 
 5541: and use the link as appropriate.
 5542: 
 5543: =cut
 5544: 
 5545: sub hasDiscussion {
 5546:     my $self = shift;
 5547:     return $self->{NAV_MAP}->hasDiscussion($self->{SYMB});
 5548: }
 5549: 
 5550: sub last_post_time {
 5551:     my $self = shift;
 5552:     return $self->{NAV_MAP}->last_post_time($self->{SYMB});
 5553: }
 5554: 
 5555: sub discussion_info {
 5556:     my ($self,$filter) = @_;
 5557:     return $self->{NAV_MAP}->discussion_info($self->{SYMB},$filter);
 5558: }
 5559: 
 5560: sub getFeedback {
 5561:     my $self = shift;
 5562:     my $source = $self->src();
 5563:     my $symb = $self->{SYMB};
 5564:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 5565:     return $self->{NAV_MAP}->getFeedback($symb,$source);
 5566: }
 5567: 
 5568: sub getErrors {
 5569:     my $self = shift;
 5570:     my $source = $self->src();
 5571:     my $symb = $self->{SYMB};
 5572:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 5573:     return $self->{NAV_MAP}->getErrors($symb,$source);
 5574: }
 5575: 
 5576: =pod
 5577: 
 5578: =item * B<parts>():
 5579: 
 5580: Returns a list reference containing sorted strings corresponding to
 5581: each part of the problem. Single part problems have only a part '0'.
 5582: Multipart problems do not return their part '0', since they typically
 5583: do not really matter. 
 5584: 
 5585: =item * B<countParts>():
 5586: 
 5587: Returns the number of parts of the problem a student can answer. Thus,
 5588: for single part problems, returns 1. For multipart, it returns the
 5589: number of parts in the problem, not including psuedo-part 0. 
 5590: 
 5591: =item * B<countResponses>():
 5592: 
 5593: Returns the total number of responses in the problem a student can answer.
 5594: 
 5595: =item * B<responseTypes>():
 5596: 
 5597: Returns a hash whose keys are the response types.  The values are the number 
 5598: of times each response type is used.  This is for the I<entire> problem, not 
 5599: just a single part.
 5600: 
 5601: =item * B<multipart>():
 5602: 
 5603: Returns true if the problem is multipart, false otherwise. Use this instead
 5604: of countParts if all you want is multipart/not multipart.
 5605: 
 5606: =item * B<responseType>($part):
 5607: 
 5608: Returns the response type of the part, without the word "response" on the
 5609: end. Example return values: 'string', 'essay', 'numeric', etc.
 5610: 
 5611: =item * B<responseIds>($part):
 5612: 
 5613: Retreives the response IDs for the given part as an array reference containing
 5614: strings naming the response IDs. This may be empty.
 5615: 
 5616: =back
 5617: 
 5618: =cut
 5619: 
 5620: sub parts {
 5621:     my $self = shift;
 5622: 
 5623:     if ($self->ext) { return []; }
 5624:     if (($self->is_tool()) &&
 5625:         ($self->is_gradable())) { return ['0']; }
 5626: 
 5627:     $self->extractParts();
 5628:     return $self->{PARTS};
 5629: }
 5630: 
 5631: sub countParts {
 5632:     my $self = shift;
 5633:     
 5634:     my $parts = $self->parts();
 5635: 
 5636:     # If I left this here, then it's not necessary.
 5637:     #my $delta = 0;
 5638:     #for my $part (@$parts) {
 5639:     #    if ($part eq '0') { $delta--; }
 5640:     #}
 5641: 
 5642:     if ($self->{RESOURCE_ERROR}) {
 5643:         return 0;
 5644:     }
 5645: 
 5646:     return scalar(@{$parts}); # + $delta;
 5647: }
 5648: 
 5649: sub countResponses {
 5650:     my $self = shift;
 5651:     my $count;
 5652:     foreach my $part (@{$self->parts()}) {
 5653:         $count+= scalar($self->responseIds($part));
 5654:     }
 5655:     return $count;
 5656: }
 5657: 
 5658: sub responseTypes {
 5659:     my $self = shift;
 5660:     my %responses;
 5661:     foreach my $part (@{$self->parts()}) {
 5662:         foreach my $responsetype ($self->responseType($part)) {
 5663:             $responses{$responsetype}++ if (defined($responsetype));
 5664:         }
 5665:     }
 5666:     return %responses;
 5667: }
 5668: 
 5669: sub multipart {
 5670:     my $self = shift;
 5671:     return $self->countParts() > 1;
 5672: }
 5673: 
 5674: sub singlepart {
 5675:     my $self = shift;
 5676:     return $self->countParts() == 1;
 5677: }
 5678: 
 5679: sub responseType {
 5680:     my $self = shift;
 5681:     my $part = shift;
 5682: 
 5683:     $self->extractParts();
 5684:     if (defined($self->{RESPONSE_TYPES}->{$part})) {
 5685: 	return @{$self->{RESPONSE_TYPES}->{$part}};
 5686:     } else {
 5687: 	return undef;
 5688:     }
 5689: }
 5690: 
 5691: sub responseIds {
 5692:     my $self = shift;
 5693:     my $part = shift;
 5694: 
 5695:     $self->extractParts();
 5696:     if (defined($self->{RESPONSE_IDS}->{$part})) {
 5697: 	return @{$self->{RESPONSE_IDS}->{$part}};
 5698:     } else {
 5699: 	return undef;
 5700:     }
 5701: }
 5702: 
 5703: # Private function: Extracts the parts information, both part names and
 5704: # part types, and saves it. 
 5705: sub extractParts { 
 5706:     my $self = shift;
 5707:     
 5708:     return if (defined($self->{PARTS}));
 5709:     return if ($self->ext);
 5710: 
 5711:     $self->{PARTS} = [];
 5712: 
 5713:     my %parts;
 5714: 
 5715:     # Retrieve part count, if this is a problem
 5716:     if ($self->is_raw_problem()) {
 5717: 	my $partorder = &Apache::lonnet::metadata($self->src(), 'partorder');
 5718:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
 5719: 
 5720: 	if ($partorder) {
 5721: 	    my @parts;
 5722: 	    for my $part (split (/,/,$partorder)) {
 5723: 		if (!Apache::loncommon::check_if_partid_hidden($part, $self->{SYMB})) {
 5724: 		    push @parts, $part;
 5725: 		    $parts{$part} = 1;
 5726: 		}
 5727: 	    }
 5728: 	    $self->{PARTS} = \@parts;
 5729: 	} else {
 5730: 	    if (!$metadata) {
 5731: 		$self->{RESOURCE_ERROR} = 1;
 5732: 		$self->{PARTS} = [];
 5733: 		$self->{PART_TYPE} = {};
 5734: 		return;
 5735: 	    }
 5736: 	    foreach my $entry (split(/\,/,$metadata)) {
 5737: 		if ($entry =~ /^(?:part|Task)_(.*)$/) {
 5738: 		    my $part = $1;
 5739: 		    # This floods the logs if it blows up
 5740: 		    if (defined($parts{$part})) {
 5741: 			&Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->{SYMB});
 5742: 		    }
 5743: 		    
 5744: 		    # check to see if part is turned off.
 5745: 		    
 5746: 		    if (!Apache::loncommon::check_if_partid_hidden($part, $self->{SYMB})) {
 5747: 			$parts{$part} = 1;
 5748: 		    }
 5749: 		}
 5750: 	    }
 5751: 	    my @sortedParts = sort(keys(%parts));
 5752: 	    $self->{PARTS} = \@sortedParts;
 5753:         }
 5754:         
 5755: 
 5756:         # These hashes probably do not need names that end with "Hash"....
 5757:         my %responseIdHash;
 5758:         my %responseTypeHash;
 5759: 
 5760: 
 5761:         # Init the responseIdHash
 5762:         foreach my $part (@{$self->{PARTS}}) {
 5763:             $responseIdHash{$part} = [];
 5764:         }
 5765: 
 5766:         # Now, the unfortunate thing about this is that parts, part name, and
 5767:         # response id are delimited by underscores, but both the part
 5768:         # name and response id can themselves have underscores in them.
 5769:         # So we have to use our knowlege of part names to figure out 
 5770:         # where the part names begin and end, and even then, it is possible
 5771:         # to construct ambiguous situations.
 5772:         foreach my $data (split(/,/, $metadata)) {
 5773:             if ($data =~ /^([a-zA-Z]+)response_(.*)/
 5774: 		|| $data =~ /^(Task)_(.*)/) {
 5775:                 my $responseType = $1;
 5776:                 my $partStuff = $2;
 5777:                 my $partIdSoFar = '';
 5778:                 my @partChunks = split(/_/, $partStuff);
 5779:                 my $i = 0;
 5780:                 for ($i = 0; $i < scalar(@partChunks); $i++) {
 5781:                     if ($partIdSoFar) { $partIdSoFar .= '_'; }
 5782:                     $partIdSoFar .= $partChunks[$i];
 5783:                     if ($parts{$partIdSoFar}) {
 5784:                         my @otherChunks = @partChunks[$i+1..$#partChunks];
 5785:                         my $responseId = join('_', @otherChunks);
 5786: 			if ($self->is_task()) {
 5787: 			    push(@{$responseIdHash{$partIdSoFar}},
 5788: 				 $partIdSoFar);
 5789: 			} else {
 5790: 			    push(@{$responseIdHash{$partIdSoFar}},
 5791: 				 $responseId);
 5792: 			}
 5793:                         push(@{$responseTypeHash{$partIdSoFar}},
 5794: 			     $responseType);
 5795:                     }
 5796:                 }
 5797:             }
 5798:         }
 5799: 	my $resorder = &Apache::lonnet::metadata($self->src(),'responseorder');
 5800:         #
 5801:         # Reorder the arrays in the %responseIdHash and %responseTypeHash
 5802: 	if ($resorder) {
 5803: 	    my @resorder=split(/,/,$resorder);
 5804: 	    foreach my $part (keys(%responseIdHash)) {
 5805: 		my $i=0;
 5806: 		my %resids = map { ($_,$i++) } @{ $responseIdHash{$part} };
 5807: 		my @neworder;
 5808: 		foreach my $possibleid (@resorder) {
 5809: 		    if (exists($resids{$possibleid})) {
 5810: 			push(@neworder,$resids{$possibleid});
 5811: 		    }
 5812: 		}
 5813: 		my @ids;
 5814: 		my @type;
 5815: 		foreach my $element (@neworder) {
 5816: 		    push (@ids,$responseIdHash{$part}->[$element]);
 5817: 		    push (@type,$responseTypeHash{$part}->[$element]);
 5818: 		}
 5819: 		$responseIdHash{$part}=\@ids;
 5820: 		$responseTypeHash{$part}=\@type;
 5821: 	    }
 5822: 	}
 5823:         $self->{RESPONSE_IDS} = \%responseIdHash;
 5824:         $self->{RESPONSE_TYPES} = \%responseTypeHash;
 5825:     }
 5826: 
 5827:     return;
 5828: }
 5829: 
 5830: =pod
 5831: 
 5832: =head2 Resource Status
 5833: 
 5834: Problem resources have status information, reflecting their various
 5835: dates and completion statuses.
 5836: 
 5837: There are two aspects to the status: the date-related information and
 5838: the completion information.
 5839: 
 5840: Idiomatic usage of these two methods would probably look something
 5841: like
 5842: 
 5843:  foreach my $part ($resource->parts()) {
 5844:     my $dateStatus = $resource->getDateStatus($part);
 5845:     my $completionStatus = $resource->getCompletionStatus($part);
 5846: 
 5847:     or
 5848: 
 5849:     my $status = $resource->status($part);
 5850: 
 5851:     ... use it here ...
 5852:  }
 5853: 
 5854: Which you use depends on exactly what you are looking for. The
 5855: status() function has been optimized for the nav maps display and may
 5856: not precisely match what you need elsewhere.
 5857: 
 5858: The symbolic constants shown below can be accessed through the
 5859: resource object: C<$res->OPEN>.
 5860: 
 5861: =over 4
 5862: 
 5863: =item * B<getDateStatus>($part):
 5864: 
 5865: ($part defaults to 0). A convenience function that returns a symbolic
 5866: constant telling you about the date status of the part. The possible
 5867: return values are:
 5868: 
 5869: =back
 5870: 
 5871: B<Date Codes>
 5872: 
 5873: =over 4
 5874: 
 5875: =item * B<OPEN_LATER>:
 5876: 
 5877: The problem will be opened later.
 5878: 
 5879: =item * B<OPEN>:
 5880: 
 5881: Open and not yet due.
 5882: 
 5883: =item * B<PAST_DUE_ANSWER_LATER>:
 5884: 
 5885: The due date has passed, but the answer date has not yet arrived.
 5886: 
 5887: =item * B<PAST_DUE_NO_ANSWER>:
 5888: 
 5889: The due date has passed and there is no answer opening date set.
 5890: 
 5891: =item * B<ANSWER_OPEN>:
 5892: 
 5893: The answer date is here.
 5894: 
 5895: =item * B<NOTHING_SET>:
 5896: 
 5897: No dates have been set for this problem at all.
 5898: 
 5899: =item * B<PAST_DUE_ATMPT_ANS>:
 5900: 
 5901: The due date has passed, feedback is suppressed, the problem was attempted, and the answer date has not yet arrived.
 5902: 
 5903: =item * B<PAST_DUE_ATMPT_NOANS>:
 5904: 
 5905: The due date has passed, feedback is suppressed, the problem was attempted, and there is no answer opening date set.
 5906: 
 5907: =item * B<PAST_DUE_NO_ATMT_ANS>:
 5908: 
 5909: The due date has passed, feedback is suppressed, the problem was not attempted, and the answer date has not yet arrived.
 5910: 
 5911: =item * B<PAST_DUE_NO_ATMT_NOANS>:
 5912: 
 5913: The due date has passed, feedback is suppressed, the problem was not attempted, and there is no answer opening date set.
 5914: 
 5915: =item * B<NETWORK_FAILURE>:
 5916: 
 5917: The information is unknown due to network failure.
 5918: 
 5919: =back
 5920: 
 5921: =cut
 5922: 
 5923: # Apparently the compiler optimizes these into constants automatically
 5924: sub OPEN_LATER             { return 0; }
 5925: sub OPEN                   { return 1; }
 5926: sub PAST_DUE_NO_ANSWER     { return 2; }
 5927: sub PAST_DUE_ANSWER_LATER  { return 3; }
 5928: sub ANSWER_OPEN            { return 4; }
 5929: sub NOTHING_SET            { return 5; }
 5930: sub PAST_DUE_ATMPT_ANS     { return 6; }
 5931: sub PAST_DUE_ATMPT_NOANS   { return 7; }
 5932: sub PAST_DUE_NO_ATMT_ANS   { return 8; }
 5933: sub PAST_DUE_NO_ATMT_NOANS { return 9; }
 5934: sub NETWORK_FAILURE        { return 100; }
 5935: 
 5936: # getDateStatus gets the date status for a given problem part. 
 5937: # Because answer date, due date, and open date are fully independent
 5938: # (i.e., it is perfectly possible to *only* have an answer date), 
 5939: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 5940: # (past, future, none given). This function handles this with a decision
 5941: # tree. Read the comments to follow the decision tree.
 5942: 
 5943: sub getDateStatus {
 5944:     my $self = shift;
 5945:     my $part = shift;
 5946:     $part = "0" if (!defined($part));
 5947: 
 5948:     # Always return network failure if there was one.
 5949:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 5950: 
 5951:     my $now = time();
 5952: 
 5953:     my $open = $self->opendate($part);
 5954:     my $due = $self->duedate($part);
 5955:     my $overdue = $self->overduedate($part);
 5956:     my $answer = $self->answerdate($part);
 5957: 
 5958:     if (!$open && !$due && !$answer) {
 5959:         # no data on the problem at all
 5960:         # should this be the same as "open later"? think multipart.
 5961:         return $self->NOTHING_SET;
 5962:     }
 5963:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 5964:     if (!$due || $now < $due) {return $self->OPEN}
 5965:     if ($overdue && $now < $overdue) {return $self->OPEN}
 5966:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 5967:     if ($answer) { return $self->ANSWER_OPEN; }
 5968:     return PAST_DUE_NO_ANSWER;
 5969: }
 5970: 
 5971: =pod
 5972: 
 5973: B<>
 5974: 
 5975: =over 4
 5976: 
 5977: =item * B<getCompletionStatus>($part):
 5978: 
 5979: ($part defaults to 0.) A convenience function that returns a symbolic
 5980: constant telling you about the completion status of the part, with the
 5981: following possible results:
 5982: 
 5983: =back
 5984: 
 5985: B<Completion Codes>
 5986: 
 5987: =over 4
 5988: 
 5989: =item * B<NOT_ATTEMPTED>:
 5990: 
 5991: Has not been attempted at all.
 5992: 
 5993: =item * B<INCORRECT>:
 5994: 
 5995: Attempted, but wrong by student.
 5996: 
 5997: =item * B<INCORRECT_BY_OVERRIDE>:
 5998: 
 5999: Attempted, but wrong by instructor override.
 6000: 
 6001: =item * B<CORRECT>:
 6002: 
 6003: Correct or correct by instructor.
 6004: 
 6005: =item * B<CORRECT_BY_OVERRIDE>:
 6006: 
 6007: Correct by instructor override.
 6008: 
 6009: =item * B<EXCUSED>:
 6010: 
 6011: Excused. Not yet implemented.
 6012: 
 6013: =item * B<NETWORK_FAILURE>:
 6014: 
 6015: Information not available due to network failure.
 6016: 
 6017: =item * B<ATTEMPTED>:
 6018: 
 6019: Attempted, and not yet graded.
 6020: 
 6021: =item * B<CREDIT_ATTEMPTED>:
 6022: 
 6023: Attempted, and credit received for attempt (survey and anonymous survey only).
 6024: 
 6025: =item * B<INCORRECT_BY_PASSBACK>:
 6026: 
 6027: Attempted, but wrong for LTI Tool Provider by passback of grade
 6028: 
 6029: =item * B<CORRECT_BY_PASSBACK>:
 6030: 
 6031: Correct for LTI Tool Provider by passback of grade
 6032: 
 6033: =back
 6034: 
 6035: =cut
 6036: 
 6037: sub NOT_ATTEMPTED         { return 10; }
 6038: sub INCORRECT             { return 11; }
 6039: sub INCORRECT_BY_OVERRIDE { return 12; }
 6040: sub CORRECT               { return 13; }
 6041: sub CORRECT_BY_OVERRIDE   { return 14; }
 6042: sub EXCUSED               { return 15; }
 6043: sub ATTEMPTED             { return 16; }
 6044: sub CREDIT_ATTEMPTED      { return 17; }
 6045: sub INCORRECT_BY_PASSBACK { return 18; }
 6046: sub CORRECT_BY_PASSBACK   { return 19; }
 6047: 
 6048: sub getCompletionStatus {
 6049:     my $self = shift;
 6050:     my $part = shift;
 6051:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 6052: 
 6053:     my $status = $self->queryRestoreHash('solved', $part);
 6054: 
 6055:     # Left as separate if statements in case we ever do more with this
 6056:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 6057:     if ($status eq 'correct_by_scantron') {return $self->CORRECT;}
 6058:     if ($status eq 'correct_by_override') {
 6059: 	return $self->CORRECT_BY_OVERRIDE;
 6060:     }
 6061:     if ($status eq 'correct_by_passback') {
 6062:         return $self->CORRECT_BY_PASSBACK;
 6063:     }
 6064:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 6065:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 6066:     if ($status eq 'incorrect_by_passback') {return $self->INCORRECT_BY_PASSBACK; }
 6067:     if ($status eq 'excused') {return $self->EXCUSED; }
 6068:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 6069:     if ($status eq 'credit_attempted') {
 6070:         if ($self->is_anonsurvey($part) || $self->is_survey($part)) {
 6071:             return $self->CREDIT_ATTEMPTED;
 6072:         } else {
 6073:             return $self->ATTEMPTED;
 6074:         }
 6075:     }
 6076:     return $self->NOT_ATTEMPTED;
 6077: }
 6078: 
 6079: sub queryRestoreHash {
 6080:     my $self = shift;
 6081:     my $hashentry = shift;
 6082:     my $part = shift;
 6083:     $part = "0" if (!defined($part) || $part eq '');
 6084:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 6085: 
 6086:     $self->getReturnHash();
 6087: 
 6088:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
 6089: }
 6090: 
 6091: =pod
 6092: 
 6093: B<Composite Status>
 6094: 
 6095: Along with directly returning the date or completion status, the
 6096: resource object includes a convenience function B<status>() that will
 6097: combine the two status tidbits into one composite status that can
 6098: represent the status of the resource as a whole. This method represents
 6099: the concept of the thing we want to display to the user on the nav maps
 6100: screen, which is a combination of completion and open status. The precise logic is
 6101: documented in the comments of the status method. The following results
 6102: may be returned, all available as methods on the resource object
 6103: ($res->NETWORK_FAILURE): In addition to the return values that match
 6104: the date or completion status, this function can return "ANSWER_SUBMITTED"
 6105: if that problemstatus parameter value is set to No, suppressing the
 6106: incorrect/correct feedback.
 6107: 
 6108: =over 4
 6109: 
 6110: =item * B<NETWORK_FAILURE>:
 6111: 
 6112: The network has failed and the information is not available.
 6113: 
 6114: =item * B<NOTHING_SET>:
 6115: 
 6116: No dates have been set for this problem (part) at all. (Because only
 6117: certain parts of a multi-part problem may be assigned, this can not be
 6118: collapsed into "open later", as we do not know a given part will EVER
 6119: be opened. For single part, this is the same as "OPEN_LATER".)
 6120: 
 6121: =item * B<CORRECT>:
 6122: 
 6123: For any reason at all, the part is considered correct.
 6124: 
 6125: =item * B<EXCUSED>:
 6126: 
 6127: For any reason at all, the problem is excused.
 6128: 
 6129: =item * B<PAST_DUE_NO_ANSWER>:
 6130: 
 6131: The problem is past due, not considered correct, and no answer date is
 6132: set.
 6133: 
 6134: =item * B<PAST_DUE_ANSWER_LATER>:
 6135: 
 6136: The problem is past due, not considered correct, and an answer date in
 6137: the future is set.
 6138: 
 6139: =item * B<PAST_DUE_ATMPT_ANS>:
 6140: 
 6141: The problem is past due, feedback is suppressed, the problem was
 6142: attempted and an answer date in the future is set.
 6143: 
 6144: =item * B<PAST_DUE_ATMPT_NOANS>:
 6145: 
 6146: The problem is past due, feedback is suppressed, the problem was
 6147: attempted and no answer date is set.
 6148: 
 6149: =item * B<PAST_DUE_NO_ATMT_ANS>:
 6150: 
 6151: The problem is past due, feedback is suppressed, the problem was
 6152: not attempted and an answer date in the future is set.
 6153: 
 6154: =item * B<PAST_DUE_NO_ATMT_NOANS>:
 6155: 
 6156: The problem is past due, feedback is suppressed, the problem was
 6157: not attempted and no answer date is set.
 6158: 
 6159: =item * B<ANSWER_OPEN>:
 6160: 
 6161: The problem is past due, not correct, and the answer is now available.
 6162: 
 6163: =item * B<OPEN_LATER>:
 6164: 
 6165: The problem is not yet open.
 6166: 
 6167: =item * B<TRIES_LEFT>:
 6168: 
 6169: The problem is open, has been tried, is not correct, but there are
 6170: tries left.
 6171: 
 6172: =item * B<INCORRECT>:
 6173: 
 6174: The problem is open, and all tries have been used without getting the
 6175: correct answer.
 6176: 
 6177: =item * B<OPEN>:
 6178: 
 6179: The item is open and not yet tried.
 6180: 
 6181: =item * B<ATTEMPTED>:
 6182: 
 6183: The problem has been attempted.
 6184: 
 6185: =item * B<CREDIT_ATTEMPTED>:
 6186: 
 6187: The problem has been attempted, and credit given for the attempt (survey and anonymous survey only).
 6188: 
 6189: =item * B<ANSWER_SUBMITTED>:
 6190: 
 6191: An answer has been submitted, but the student should not see it.
 6192: 
 6193: =back
 6194: 
 6195: =cut
 6196: 
 6197: sub TRIES_LEFT        { return 20; }
 6198: sub ANSWER_SUBMITTED  { return 21; }
 6199: sub PARTIALLY_CORRECT { return 22; }
 6200: 
 6201: sub RESERVED_LATER    { return 30; }
 6202: sub RESERVED          { return 31; }
 6203: sub RESERVED_LOCATION { return 32; }
 6204: sub RESERVABLE        { return 33; }
 6205: sub RESERVABLE_LATER  { return 34; }
 6206: sub NOTRESERVABLE     { return 35; }
 6207: sub NOT_IN_A_SLOT     { return 36; }
 6208: sub NEEDS_CHECKIN     { return 37; }
 6209: sub WAITING_FOR_GRADE { return 38; }
 6210: sub UNKNOWN           { return 39; }
 6211: 
 6212: sub status {
 6213:     my $self = shift;
 6214:     my $part = shift;
 6215:     if (!defined($part)) { $part = "0"; }
 6216:     my $completionStatus = $self->getCompletionStatus($part);
 6217:     my $dateStatus = $self->getDateStatus($part);
 6218: 
 6219:     # What we have is a two-dimensional matrix with 4 entries on one
 6220:     # dimension and 5 entries on the other, which we want to colorize,
 6221:     # plus network failure and "no date data at all".
 6222: 
 6223:     #if ($self->{RESOURCE_ERROR}) { return NETWORK_FAILURE; }
 6224:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 6225: 
 6226:     my $suppressFeedback = 0;
 6227:     if (($self->problemstatus($part) eq 'no') ||
 6228:         ($self->problemstatus($part) eq 'no_feedback_ever')) {
 6229:         $suppressFeedback = 1;
 6230:     }
 6231:     # If there's an answer date and we're past it, don't
 6232:     # suppress the feedback; student should know
 6233:     if ($self->duedate($part) && $self->duedate($part) < time() &&
 6234:         (!$self->overduedate($part) || $self->overduedate($part) < time()) &&
 6235: 	$self->answerdate($part) && $self->answerdate($part) < time()) {
 6236: 	$suppressFeedback = 0;
 6237:     }
 6238: 
 6239:     # There are a few whole rows we can dispose of:
 6240:     if ($completionStatus == CORRECT ||
 6241:         $completionStatus == CORRECT_BY_OVERRIDE ||
 6242:         $completionStatus == CORRECT_BY_PASSBACK ) {
 6243: 	if ( $suppressFeedback ) {
 6244:             if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 6245:                 $dateStatus == PAST_DUE_NO_ANSWER ) {
 6246:                 if ($dateStatus == PAST_DUE_ANSWER_LATER) {
 6247:                     return PAST_DUE_ATMPT_ANS;
 6248:                 } else {
 6249:                     return PAST_DUE_ATMPT_NOANS;
 6250:                 }
 6251:             } else {
 6252:                 return ANSWER_SUBMITTED;
 6253:             }
 6254:         }
 6255: 	my $awarded=$self->awarded($part);
 6256: 	if ($awarded < 1 && $awarded > 0) {
 6257:             return PARTIALLY_CORRECT;
 6258: 	} elsif ($awarded<1) {
 6259: 	    return INCORRECT;
 6260: 	}
 6261: 	return CORRECT; 
 6262:     }
 6263: 
 6264:     # If it's WRONG... and not open
 6265:     if ( ($completionStatus == INCORRECT || 
 6266: 	  $completionStatus == INCORRECT_BY_OVERRIDE ||
 6267: 	  $completionStatus == INCORRECT_BY_PASSBACK)
 6268: 	 && (!$self->opendate($part) ||  $self->opendate($part) > time()) ) {
 6269: 	return INCORRECT;
 6270:     }
 6271: 
 6272:     if ($completionStatus == ATTEMPTED) {
 6273:         return ATTEMPTED;
 6274:     }
 6275: 
 6276:     if ($completionStatus == CREDIT_ATTEMPTED) {
 6277:         return CREDIT_ATTEMPTED;
 6278:     }
 6279: 
 6280:     # If it's EXCUSED, then return that no matter what
 6281:     if ($completionStatus == EXCUSED) {
 6282:         return EXCUSED; 
 6283:     }
 6284: 
 6285:     if ($dateStatus == NOTHING_SET) {
 6286:         return NOTHING_SET;
 6287:     }
 6288: 
 6289:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 6290:     # by 4 matrix (date statuses).
 6291: 
 6292:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 6293:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 6294:         if ($suppressFeedback) {
 6295:             if ($completionStatus == NOT_ATTEMPTED) {
 6296:                 if ($dateStatus == PAST_DUE_ANSWER_LATER) {
 6297:                     return PAST_DUE_NO_ATMT_ANS;
 6298:                 } else {
 6299:                     return PAST_DUE_NO_ATMT_NOANS;
 6300:                 }
 6301:             } else {
 6302:                 if ($dateStatus == PAST_DUE_ANSWER_LATER) {
 6303:                     return PAST_DUE_ATMPT_ANS;
 6304:                 } else {
 6305:                     return PAST_DUE_ATMPT_NOANS;
 6306:                 }
 6307:             }
 6308:         } else {
 6309:             return $dateStatus;
 6310:         }
 6311:     }
 6312: 
 6313:     if ($dateStatus == ANSWER_OPEN) {
 6314:         return ANSWER_OPEN;
 6315:     }
 6316: 
 6317:     # Now: (incorrect, incorrect_override, not_attempted) x 
 6318:     # (open_later), (open)
 6319:     
 6320:     if ($dateStatus == OPEN_LATER) {
 6321:         return OPEN_LATER;
 6322:     }
 6323: 
 6324:     # If it's WRONG...
 6325:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE ||
 6326:         $completionStatus == INCORRECT_BY_PASSBACK) {
 6327:         # and there are TRIES LEFT:
 6328:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 6329:             return $suppressFeedback ? ANSWER_SUBMITTED : TRIES_LEFT;
 6330:         }
 6331:         return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
 6332:     }
 6333: 
 6334:     # Otherwise, it's untried and open
 6335:     return OPEN;
 6336: }
 6337: 
 6338: sub check_for_slot {
 6339:     my $self = shift;
 6340:     my $part = shift;
 6341:     my $symb = $self->{SYMB};
 6342:     my ($use_slots,$available,$availablestudent) = $self->slot_control($part);
 6343:     if (($use_slots ne '') && ($use_slots !~ /^\s*no\s*$/i)) {
 6344:         my @slots = (split(/:/,$availablestudent),split(/:/,$available));
 6345:         my $cid=$env{'request.course.id'};
 6346:         my $cdom=$env{'course.'.$cid.'.domain'};
 6347:         my $cnum=$env{'course.'.$cid.'.num'};
 6348:         my $now = time;
 6349:         my $num_usable_slots = 0;
 6350:         my ($checkedin,$checkedinslot,%consumed_uniq,%slots);
 6351:         if (@slots > 0) {
 6352:             %slots=&Apache::lonnet::get('slots',[@slots],$cdom,$cnum);
 6353:             if (&Apache::lonnet::error(%slots)) {
 6354:                 return (UNKNOWN);
 6355:             }
 6356:             my @sorted_slots = &Apache::loncommon::sorted_slots(\@slots,\%slots,'starttime');
 6357:             foreach my $slot_name (@sorted_slots) {
 6358:                 next if (!defined($slots{$slot_name}) || !ref($slots{$slot_name}));
 6359:                 my $end = $slots{$slot_name}->{'endtime'};
 6360:                 my $start = $slots{$slot_name}->{'starttime'};
 6361:                 my $ip = $slots{$slot_name}->{'ip'};
 6362:                 if ($self->simpleStatus() == OPEN) {
 6363:                     if ($end > $now) {
 6364:                         if ($start > $now) {
 6365:                             return (RESERVED_LATER,$start,$slot_name);
 6366:                         } else {
 6367:                             if ($ip ne '') {
 6368:                                 if (!&Apache::loncommon::check_ip_acc($ip)) {
 6369:                                     return (RESERVED_LOCATION,$end,$slot_name);
 6370:                                 }
 6371:                             }
 6372:                             my @proctors;
 6373:                             if ($slots{$slot_name}->{'proctor'} ne '') {
 6374:                                 @proctors = split(',',$slots{$slot_name}->{'proctor'});
 6375:                             }
 6376:                             if (@proctors > 0) {
 6377:                                 ($checkedin,$checkedinslot) = $self->checkedin();
 6378:                                 unless ((grep(/^\Q$checkedin\E/,@proctors)) &&
 6379:                                         ($checkedinslot eq $slot_name)) {
 6380:                                     return (NEEDS_CHECKIN,$end,$slot_name); 
 6381:                                 }
 6382:                             }
 6383:                             return (RESERVED,$end,$slot_name);
 6384:                         }
 6385:                     }
 6386:                 } elsif ($end > $now) {
 6387:                     $num_usable_slots ++;
 6388:                 }
 6389:             }
 6390:             my ($is_correct,$wait_for_grade);
 6391:             if ($self->is_task()) {
 6392:                 my $taskstatus = $self->taskstatus();
 6393:                 $is_correct = (($taskstatus eq 'pass') || 
 6394:                                ($self->solved() =~ /^correct_/));
 6395:                 unless ($taskstatus =~ /^(?:pass|fail)$/) {
 6396:                     $wait_for_grade = 1;
 6397:                 }
 6398:             } else {
 6399:                 unless ($self->completable()) {
 6400:                     $wait_for_grade = 1;
 6401:                 }
 6402:                 unless (($self->problemstatus($part) eq 'no') ||
 6403:                         ($self->problemstatus($part) eq 'no_feedback_ever')) {
 6404:                     $is_correct = ($self->solved($part) =~ /^correct_/);
 6405:                     $wait_for_grade = 0;
 6406:                 }
 6407:             }
 6408:             ($checkedin,$checkedinslot) = $self->checkedin();
 6409:             if ($checkedin) {
 6410:                 if (ref($slots{$checkedinslot}) eq 'HASH') {
 6411:                     $consumed_uniq{$checkedinslot} = $slots{$checkedinslot}{'uniqueperiod'};
 6412:                 }
 6413:                 if ($wait_for_grade) {
 6414:                     return (WAITING_FOR_GRADE);
 6415:                 } elsif ($is_correct) {
 6416:                     return (CORRECT); 
 6417:                 }
 6418:             }
 6419:             if ($num_usable_slots) {
 6420:                 return(NOT_IN_A_SLOT);
 6421:             }
 6422:         }
 6423:         my $reservable = &Apache::lonnet::get_reservable_slots($cnum,$cdom,$env{'user.name'},
 6424:                                                                $env{'user.domain'});
 6425:         if (ref($reservable) eq 'HASH') {
 6426:             my ($map) = &Apache::lonnet::decode_symb($symb);
 6427:             if ((ref($reservable->{'now_order'}) eq 'ARRAY') && (ref($reservable->{'now'}) eq 'HASH')) {
 6428:                 foreach my $slot (reverse (@{$reservable->{'now_order'}})) {
 6429:                     my $canuse;
 6430:                     if ($reservable->{'now'}{$slot}{'symb'} eq '') {
 6431:                         $canuse = 1;
 6432:                     } else {
 6433:                         my %oksymbs;
 6434:                         my @slotsymbs = split(/\s*,\s*/,$reservable->{'now'}{$slot}{'symb'});
 6435:                         map { $oksymbs{$_} = 1; } @slotsymbs;
 6436:                         if ($oksymbs{$symb}) {
 6437:                             $canuse = 1;
 6438:                         } else {
 6439:                             foreach my $item (@slotsymbs) {
 6440:                                 if ($item =~ /\.(page|sequence)$/) {
 6441:                                     (undef,undef, my $sloturl) = &Apache::lonnet::decode_symb($item);
 6442:                                     if (($map ne '') && ($map eq $sloturl)) {
 6443:                                         $canuse = 1;
 6444:                                         last;
 6445:                                     }
 6446:                                 }
 6447:                             }
 6448:                         }
 6449:                     }
 6450:                     if ($canuse) {
 6451:                         if ($checkedin) {
 6452:                             if (ref($consumed_uniq{$checkedinslot}) eq 'ARRAY') {
 6453:                                 my ($uniqstart,$uniqend)=@{$consumed_uniq{$checkedinslot}};
 6454:                                 if ($reservable->{'now'}{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
 6455:                                     my ($new_uniq_start,$new_uniq_end) = ($1,$2);
 6456:                                     next if (!
 6457:                                         ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
 6458:                                         ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
 6459:                                 }
 6460:                             }
 6461:                         }
 6462:                         return(RESERVABLE,$reservable->{'now'}{$slot}{'endreserve'});
 6463:                     }
 6464:                 }
 6465:             }
 6466:             if ((ref($reservable->{'future_order'}) eq 'ARRAY') && (ref($reservable->{'future'}) eq 'HASH')) {
 6467:                 foreach my $slot (@{$reservable->{'future_order'}}) {
 6468:                     my $canuse;
 6469:                     if ($reservable->{'future'}{$slot}{'symb'} eq '') {
 6470:                         $canuse = 1;
 6471:                     } elsif ($reservable->{'future'}{$slot}{'symb'} =~ /,/) {
 6472:                         my %oksymbs;
 6473:                         my @slotsymbs = split(/\s*,\s*/,$reservable->{'future'}{$slot}{'symb'});
 6474:                         map { $oksymbs{$_} = 1; } @slotsymbs;
 6475:                         if ($oksymbs{$symb}) {
 6476:                             $canuse = 1;
 6477:                         } else {
 6478:                             foreach my $item (@slotsymbs) {
 6479:                                 if ($item =~ /\.(page|sequence)$/) {
 6480:                                     (undef,undef, my $sloturl) = &Apache::lonnet::decode_symb($item);
 6481:                                     if (($map ne '') && ($map eq $sloturl)) {
 6482:                                         $canuse = 1;
 6483:                                         last;
 6484:                                     }
 6485:                                 }
 6486:                             }
 6487:                         }
 6488:                     } elsif ($reservable->{'future'}{$slot}{'symb'} eq $symb) {
 6489:                         $canuse = 1;
 6490:                     }
 6491:                     if ($canuse) {
 6492:                         if ($checkedin) {
 6493:                             if (ref($consumed_uniq{$checkedinslot}) eq 'ARRAY') {
 6494:                                 my ($uniqstart,$uniqend)=@{$consumed_uniq{$checkedinslot}};
 6495:                                 if ($reservable->{'future'}{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
 6496:                                     my ($new_uniq_start,$new_uniq_end) = ($1,$2);
 6497:                                     next if (!
 6498:                                         ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
 6499:                                         ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
 6500:                                 }
 6501:                             }
 6502:                         }
 6503:                         return(RESERVABLE_LATER,$reservable->{'future'}{$slot}{'startreserve'});
 6504:                     }
 6505:                 }
 6506:             }
 6507:         }
 6508:         return(NOTRESERVABLE);
 6509:     }
 6510:     return;
 6511: }
 6512: 
 6513: sub CLOSED { return 23; }
 6514: sub ERROR { return 24; }
 6515: 
 6516: =pod
 6517: 
 6518: B<Simple Status>
 6519: 
 6520: Convenience method B<simpleStatus> provides a "simple status" for the resource.
 6521: "Simple status" corresponds to "which icon is shown on the
 6522: Navmaps". There are six "simple" statuses:
 6523: 
 6524: =over 4
 6525: 
 6526: =item * B<CLOSED>: The problem is currently closed. (No icon shown.)
 6527: 
 6528: =item * B<OPEN>: The problem is open and unattempted.
 6529: 
 6530: =item * B<CORRECT>: The problem is correct for any reason.
 6531: 
 6532: =item * B<INCORRECT>: The problem is incorrect and can still be
 6533: completed successfully.
 6534: 
 6535: =item * B<ATTEMPTED>: The problem has been attempted, but the student
 6536: does not know if they are correct. (The ellipsis icon.)
 6537: 
 6538: =item * B<ERROR>: There is an error retrieving information about this
 6539: problem.
 6540: 
 6541: =back
 6542: 
 6543: =cut
 6544: 
 6545: # This hash maps the composite status to this simple status, and
 6546: # can be used directly, if you like
 6547: my %compositeToSimple = 
 6548:     (
 6549:       NETWORK_FAILURE()       => ERROR,
 6550:       NOTHING_SET()           => CLOSED,
 6551:       CORRECT()               => CORRECT,
 6552:       PARTIALLY_CORRECT()     => PARTIALLY_CORRECT,
 6553:       EXCUSED()               => CORRECT,
 6554:       PAST_DUE_NO_ANSWER()    => INCORRECT,
 6555:       PAST_DUE_ANSWER_LATER() => INCORRECT,
 6556:       PAST_DUE_ATMPT_ANS()    => ATTEMPTED,
 6557:       PAST_DUE_ATMPT_NOANS()  => ATTEMPTED,
 6558:       PAST_DUE_NO_ATMT_ANS()  => CLOSED,
 6559:       PAST_DUE_NO_ATMT_NOANS() => CLOSED,
 6560:       ANSWER_OPEN()           => INCORRECT,
 6561:       OPEN_LATER()            => CLOSED,
 6562:       TRIES_LEFT()            => OPEN,
 6563:       INCORRECT()             => INCORRECT,
 6564:       OPEN()                  => OPEN,
 6565:       ATTEMPTED()             => ATTEMPTED,
 6566:       CREDIT_ATTEMPTED()      => CORRECT,
 6567:       ANSWER_SUBMITTED()      => ATTEMPTED
 6568:      );
 6569: 
 6570: sub simpleStatus {
 6571:     my $self = shift;
 6572:     my $part = shift;
 6573:     my $status = $self->status($part);
 6574:     return $compositeToSimple{$status};
 6575: }
 6576: 
 6577: =pod
 6578: 
 6579: B<simpleStatusCount> will return an array reference containing, in
 6580: this order, the number of OPEN, CLOSED, CORRECT, INCORRECT, ATTEMPTED,
 6581: and ERROR parts the given problem has.
 6582: 
 6583: =cut
 6584:     
 6585: # This maps the status to the slot we want to increment
 6586: my %statusToSlotMap = 
 6587:     (
 6588:      OPEN()      => 0,
 6589:      CLOSED()    => 1,
 6590:      CORRECT()   => 2,
 6591:      INCORRECT() => 3,
 6592:      ATTEMPTED() => 4,
 6593:      ERROR()     => 5
 6594:      );
 6595: 
 6596: sub statusToSlot { return $statusToSlotMap{shift()}; }
 6597: 
 6598: sub simpleStatusCount {
 6599:     my $self = shift;
 6600: 
 6601:     my @counts = (0, 0, 0, 0, 0, 0, 0);
 6602:     foreach my $part (@{$self->parts()}) {
 6603: 	$counts[$statusToSlotMap{$self->simpleStatus($part)}]++;
 6604:     }
 6605: 
 6606:     return \@counts;
 6607: }
 6608: 
 6609: =pod
 6610: 
 6611: B<Completable>
 6612: 
 6613: The completable method represents the concept of I<whether the student can
 6614: currently do the problem>. If the student can do the problem, which means
 6615: that it is open, there are tries left, and if the problem is manually graded
 6616: or the grade is suppressed via problemstatus, the student has not tried it
 6617: yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
 6618: either the student has tried it and there is no feedback, or that for
 6619: some reason it is no longer completable (not open yet, successfully completed,
 6620: out of tries, etc.). As an example, this is used as the filter for the
 6621: "Uncompleted Homework" option for the nav maps.
 6622: 
 6623: If this does not quite meet your needs, do not fiddle with it (unless you are
 6624: fixing it to better match the student's conception of "completable" because
 6625: it's broken somehow)... make a new method.
 6626: 
 6627: =cut
 6628: 
 6629: sub completable {
 6630:     my $self = shift;
 6631:     if (!$self->is_problem()) { return 0; }
 6632:     my $partCount = $self->countParts();
 6633: 
 6634:     foreach my $part (@{$self->parts()}) {
 6635:         if ($part eq '0' && $partCount != 1) { next; }
 6636:         my $status = $self->status($part);
 6637:         # "If any of the parts are open, or have tries left (implies open),
 6638:         # and it is not "attempted" (manually graded problem), it is
 6639:         # not "complete"
 6640: 	if ($self->getCompletionStatus($part) == ATTEMPTED() ||
 6641:             $self->getCompletionStatus($part) == CREDIT_ATTEMPTED() ||
 6642: 	    $status == ANSWER_SUBMITTED() ) {
 6643: 	    # did this part already, as well as we can
 6644: 	    next;
 6645: 	}
 6646: 	if ($status == OPEN() || $status == TRIES_LEFT()) {
 6647: 	    return 1;
 6648: 	}
 6649:     }
 6650:         
 6651:     # If all the parts were complete, so was this problem.
 6652:     return 0;
 6653: }
 6654: 
 6655: =pod
 6656: 
 6657: B<Answerable>
 6658: 
 6659: The answerable method differs from the completable method in its handling of problem parts
 6660: for which feedback on correctness is suppressed, but the student still has tries left, and
 6661: the problem part is not past due, (i.e., the student could submit a different answer if
 6662: he/she so chose). For that case completable will return 0, whereas answerable will return 1.
 6663: 
 6664: =cut
 6665: 
 6666: sub answerable {
 6667:     my $self = shift;
 6668:     if (!$self->is_problem()) { return 0; }
 6669:     my $partCount = $self->countParts();
 6670:     foreach my $part (@{$self->parts()}) {
 6671:         if ($part eq '0' && $partCount != 1) { next; }
 6672:         my $status = $self->status($part);
 6673:         if ($self->getCompletionStatus($part) == ATTEMPTED() ||
 6674:             $self->getCompletionStatus($part) == CREDIT_ATTEMPTED() ||
 6675:             $status == ANSWER_SUBMITTED() ) {
 6676:             if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 6677:                 return 1;
 6678:             }
 6679:         }
 6680:         if ($status == OPEN() || $status == TRIES_LEFT() || $status == NETWORK_FAILURE()) {
 6681:             return 1;
 6682:         }
 6683:     }
 6684:     # None of the parts were answerable, so neither is this problem.
 6685:     return 0;
 6686: }
 6687: 
 6688: =pod
 6689: 
 6690: =head2 Resource/Nav Map Navigation
 6691: 
 6692: =over 4
 6693: 
 6694: =item * B<getNext>():
 6695: 
 6696: Retreive an array of the possible next resources after this
 6697: one. Always returns an array, even in the one- or zero-element case.
 6698: 
 6699: =item * B<getPrevious>():
 6700: 
 6701: Retreive an array of the possible previous resources from this
 6702: one. Always returns an array, even in the one- or zero-element case.
 6703: 
 6704: =cut
 6705: 
 6706: sub getNext {
 6707:     my $self = shift;
 6708:     my @branches;
 6709:     my $to = $self->to();
 6710:     foreach my $branch ( split(/,/, $to) ) {
 6711:         my $choice = $self->{NAV_MAP}->getById($branch);
 6712:         #if (!$choice->condition()) { next; }
 6713:         my $next = $choice->goesto();
 6714:         $next = $self->{NAV_MAP}->getById($next);
 6715: 
 6716:         push @branches, $next;
 6717:     }
 6718:     return \@branches;
 6719: }
 6720: 
 6721: sub getPrevious {
 6722:     my $self = shift;
 6723:     my @branches;
 6724:     my $from = $self->from();
 6725:     foreach my $branch ( split(/,/, $from)) {
 6726:         my $choice = $self->{NAV_MAP}->getById($branch);
 6727:         my $prev = $choice->comesfrom();
 6728:         $prev = $self->{NAV_MAP}->getById($prev);
 6729: 
 6730:         push @branches, $prev;
 6731:     }
 6732:     return \@branches;
 6733: }
 6734: 
 6735: sub browsePriv {
 6736:     my $self = shift;
 6737:     my $noblockcheck = shift;
 6738:     my $deeplinklisted = shift;
 6739:     if (defined($self->{BROWSE_PRIV})) {
 6740:         return $self->{BROWSE_PRIV};
 6741:     }
 6742:     my ($nodeeplinkcheck,$nodeeplinkout);
 6743:     if ($deeplinklisted) {
 6744:         my $deeplink = $self->deeplink(undef,'getlisted');
 6745:         if (($deeplink) && ($deeplink ne 'absent')) {
 6746:             $nodeeplinkcheck = 1;
 6747:         }
 6748:         $nodeeplinkout = 1;
 6749:     }
 6750:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre',$self->src(),
 6751: 						    $self->{SYMB},undef,
 6752:                                                     undef,$noblockcheck,
 6753:                                                     undef,$nodeeplinkcheck,
 6754:                                                     $nodeeplinkout);
 6755: }
 6756: 
 6757: =pod
 6758: 
 6759: =back
 6760: 
 6761: =cut
 6762: 
 6763: 1;
 6764: 
 6765: __END__
 6766: 
 6767: 

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