File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.541: download - view: text, annotated - select for diffs
Wed Jan 31 14:05:12 2018 UTC (6 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Typos in documentation.

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

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