File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.445: download - view: text, annotated - select for diffs
Tue Mar 16 19:55:49 2010 UTC (14 years, 2 months ago) by droeschl
Branches: MAIN
CVS tags: HEAD
In process of removing remote control, remote navmap and different icon modes code
- mostly remote navmap related code and files removed
- some minor refactoring
- some translations added/removed

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

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