File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509: download - view: text, annotated - select for diffs
Fri Sep 25 17:39:36 2015 UTC (8 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_X, HEAD
- Show both due date and reservation status for non-task items with access
  controlled by slots, if there is a due date, and status is open.

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

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