File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.522: download - view: text, annotated - select for diffs
Mon Jul 18 19:28:57 2016 UTC (7 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- For resources already checked into a slot (now past its end time),
  check for use of unique time periods in used slot, when checking for other
  reservable (future) slots.

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

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