File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.538: download - view: text, annotated - select for diffs
Thu Dec 21 03:50:57 2017 UTC (6 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Course contents includes information for resource with reservation, if
  past the start time, and proctor check-in of the user stilll needed.

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

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