File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.14.2.4: download - view: text, annotated - select for diffs
Thu Oct 6 16:32:04 2022 UTC (19 months, 2 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.561, 1.562

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

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