File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.14.2.9: download - view: text, annotated - select for diffs
Thu Jul 6 20:32:17 2023 UTC (10 months, 3 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.509.2.14: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.531, 1.537, 1.539, 1.542

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

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