File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.14.2.5: download - view: text, annotated - select for diffs
Wed Jan 18 00:53:39 2023 UTC (16 months, 3 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.509.2.14: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.558

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

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