File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.496: download - view: text, annotated - select for diffs
Thu May 30 05:04:22 2013 UTC (10 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC1, HEAD
- When users with pav and vgr priv (e.g., Course Coordinators)  print a
  folder of resources for anonymous CODE(s) or for named student(s), e.g.,
  for a bubblesheet exam, parameter in map for hiddenresource will be
  ignored when retrieving resources for folder in random order.
- Supports use case where CC sets hidden for exam folder while printing
  bubblesheet exam, and also while grading exam.

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

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