File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.423.2.3: download - view: text, annotated - select for diffs
Wed Feb 10 16:45:31 2010 UTC (14 years, 3 months ago) by raeburn
Branches: version_2_9_X
CVS tags: version_2_9_1, version_2_9_0, version_2_8_99_1
Diff to branchpoint 1.423: preferred, unified
- Backport 1.436, 1.437, 1.441.

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

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