File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.443: download - view: text, annotated - select for diffs
Tue Jan 26 11:33:48 2010 UTC (14 years, 4 months ago) by foxr
Branches: MAIN
CVS tags: version_2_9_99_0, bz6209-base, bz6209, HEAD
Add is_incomplete predicate

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

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