File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.5.4.2: download - view: text, annotated - select for diffs
Fri Sep 15 23:17:24 2017 UTC (6 years, 8 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.509.2.5: preferred, unified
- For 2.11.2 (modified)
  Backport 1.533, 1.534, 1.535, 1.536

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

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