File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.3: download - view: text, annotated - select for diffs
Wed Aug 10 21:29:52 2016 UTC (7 years, 9 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.518

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

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