File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.17: download - view: text, annotated - select for diffs
Wed Jul 3 03:07:58 2024 UTC (2 weeks, 1 day ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_5
- For 2.11
  Backport 1.561, 1.562

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

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