File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.14.2.3: download - view: text, annotated - select for diffs
Fri Jul 8 16:10:35 2022 UTC (23 months, 2 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.509.2.14: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.559

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

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