File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.509.2.14.2.2: download - view: text, annotated - select for diffs
Wed Jan 5 00:41:13 2022 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.509.2.14: preferred, unified
- For 2.11.4 (modified)
  Typo in rev. 1.509.2.14.2.1 backport of 1.520

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

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