File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.512: download - view: text, annotated - select for diffs
Mon Feb 22 03:37:02 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6806. Support anchor in URL set for an external resource.

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

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