File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.554: download - view: text, annotated - select for diffs
Wed Aug 4 19:59:10 2021 UTC (2 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907 Content in a course can be set to be deep-link only.
  - deeplink parameter has 5 components:
    state, others, listing, scope, protect and menus.
  - deeplink protection for launch from non-LON-CAPA LTI-enabled systems
    uses /adm/launch/tiny/$dom/$uniqueID, and key and secret used by launcher
    can be set in a course (by CC), or for domain (by DC).

# The LearningOnline Network with CAPA
# Navigate Maps Handler
#
# $Id: lonnavmaps.pm,v 1.554 2021/08/04 19:59:10 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
###

=pod

=head1 NAME

Apache::lonnavmaps - Subroutines to handle and render the navigation

=head1 SYNOPSIS

Handles navigational maps.

The main handler generates the navigational listing for the course,
the other objects export this information in a usable fashion for
other modules.


This is part of the LearningOnline Network with CAPA project
described at http://www.lon-capa.org.


=head1 OVERVIEW

X<lonnavmaps, overview> When a user enters a course, LON-CAPA examines the
course structure and caches it in what is often referred to as the
"big hash" X<big hash>. You can see it if you are logged into
LON-CAPA, in a course, by going to /adm/test. The content of 
the hash will be under the heading "Big Hash".

Access to /adm/test is controlled by a domain configuration, 
which a Domain Coordinator will set for a server's default domain
via: Main Menu > Set domain configuration > Display (Access to 
server status pages checked), and entering a username:domain
or IP address in the "Show user environment" row. Users with
an unexpired domain coordinator role in the server's domain
automatically receive access to /adm/test.

Big Hash contains, among other things, how resources are related
to each other (next/previous), what resources are maps, which 
resources are being chosen to not show to the student (for random
selection), and a lot of other things that can take a lot of time
to compute due to the amount of data that needs to be collected and
processed.

Apache::lonnavmaps provides an object model for manipulating this
information in a higher-level fashion than directly manipulating 
the hash. It also provides access to several auxiliary functions 
that aren't necessarily stored in the Big Hash, but are a per-
resource sort of value, like whether there is any feedback on 
a given resource.

Apache::lonnavmaps also abstracts away branching, and someday, 
conditions, for the times where you don't really care about those
things.

Apache::lonnavmaps also provides fairly powerful routines for
rendering navmaps, and last but not least, provides the navmaps
view for when the user clicks the NAV button.

B<Note>: Apache::lonnavmaps by default will show information 
for the "currently logged in user".  However, if information
about resources is needed for a different user, e.g., a bubblesheet
exam which uses randomorder, or randompick needs to be printed or 
graded for named user(s) or specific CODEs, then the username,
domain, or CODE can be passed as arguments when creating a new 
navmap object.

Note if you want things like "due dates for another student",
you would use the EXT function instead of lonnavmaps.
That said, the lonnavmaps module can still help, because many
things, such as the course structure, are usually constant
between users, and Apache::lonnavmaps can help by providing
symbs for the EXT call.

The rest of this file will cover the provided rendering routines, 
which can often be used without fiddling with the navmap object at
all, then documents the Apache::lonnavmaps::navmap object, which
is the key to accessing the Big Hash information, covers the use
of the Iterator (which provides the logic for traversing the 
somewhat-complicated Big Hash data structure), documents the
Apache::lonnavmaps::Resource objects that are returned singularly
by: getBySymb(), getById(), getByMapPc(), and getResourceByUrl()
(can also be as an array), or in an array by retrieveResources().

=head1 Subroutine: render

The navmap renderer package provides a sophisticated rendering of the
standard navigation maps interface into HTML. The provided nav map
handler is actually just a glorified call to this.

Because of the large number of parameters this function accepts,
instead of passing it arguments as is normal, pass it in an anonymous
hash with the desired options.

The package provides a function called 'render', called as
Apache::lonnavmaps::render({}).

=head2 Overview of Columns

The renderer will build an HTML table for the navmap and return
it. The table consists of several columns, and a row for each
resource (or possibly each part). You tell the renderer how many
columns to create and what to place in each column, optionally using
one or more of the prepared columns, and the renderer will assemble
the table.

Any additional generally useful column types should be placed in the
renderer code here, so anybody can use it anywhere else. Any code
specific to the current application (such as the addition of <input>
elements in a column) should be placed in the code of the thing using
the renderer.

At the core of the renderer is the array reference COLS (see Example
section below for how to pass this correctly). The COLS array will
consist of entries of one of two types of things: Either an integer
representing one of the pre-packaged column types, or a sub reference
that takes a resource reference, a part number, and a reference to the
argument hash passed to the renderer, and returns a string that will
be inserted into the HTML representation as it.

All other parameters are ways of either changing how the columns
are printing, or which rows are shown.

The pre-packaged column names are refered to by constants in the
Apache::lonnavmaps namespace. The following currently exist:

=over 4

=item * B<Apache::lonnavmaps::resource>:

The general info about the resource: Link, icon for the type, etc. The
first column in the standard nav map display. This column provides the
indentation effect seen in the B<NAV> screen. This column also accepts
the following parameters in the renderer hash:

=over 4

=item * B<resource_nolink>: default false

If true, the resource will not be linked. By default, all non-folder
resources are linked.

=item * B<resource_part_count>: default true

If true, the resource will show a part count B<if> the full
part list is not displayed. (See "condense_parts" later.) If false,
the resource will never show a part count.

=item * B<resource_no_folder_link>:

If true, the resource's folder will not be clickable to open or close
it. Default is false. True implies printCloseAll is false, since you
can't close or open folders when this is on anyhow.

=item * B<map_no_edit_link>:

If true, the title of the folder or page will not be followed by an
icon/link to direct editing of a folder or composite page, originally
added via the Course Editor.

=back

=item * B<Apache::lonnavmaps::communication_status>:

Whether there is discussion on the resource, email for the user, or
(lumped in here) perl errors in the execution of the problem. This is
the second column in the main nav map.

=item * B<Apache::lonnavmaps::quick_status>:

An icon for the status of a problem, with five possible states:
Correct, incorrect, open, awaiting grading (for a problem where the
computer's grade is suppressed, or the computer can't grade, like
essay problem), or none (not open yet, not a problem). The
third column of the standard navmap.

=item * B<Apache::lonnavmaps::long_status>:

A text readout of the details of the current status of the problem,
such as "Due in 22 hours". The fourth column of the standard navmap.

=item * B<Apache::lonnavmaps::part_status_summary>:

A text readout summarizing the status of the problem. If it is a
single part problem, will display "Correct", "Incorrect", 
"Not yet open", "Open", "Attempted", or "Error". If there are
multiple parts, this will output a string that in HTML will show a
status of how many parts are in each status, in color coding, trying
to match the colors of the icons within reason.

Note this only makes sense if you are I<not> showing parts. If 
C<showParts> is true (see below), this column will not output
anything. 

=back

If you add any others please be sure to document them here.

An example of a column renderer that will show the ID number of a
resource, along with the part name if any:

 sub { 
  my ($resource, $part, $params) = @_;   
  if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
  return '<td>' . $resource->{ID} . '</td>';
 }

Note these functions are responsible for the TD tags, which allow them
to override vertical and horizontal alignment, etc.

=head2 Parameters

Minimally, you should be
able to get away with just using 'cols' (to specify the columns
shown), 'url' (necessary for the folders to link to the current screen
correctly), and possibly 'queryString' if your app calls for it. In
that case, maintaining the state of the folders will be done
automatically.

=over 4

=item * B<iterator>: default: constructs one from %env

A reference to a fresh ::iterator to use from the navmaps. The
rendering will reflect the options passed to the iterator, so you can
use that to just render a certain part of the course, if you like. If
one is not passed, the renderer will attempt to construct one from
env{'form.filter'} and env{'form.condition'} information, plus the
'iterator_map' parameter if any.

=item * B<iterator_map>: default: not used

If you are letting the renderer do the iterator handling, you can
instruct the renderer to render only a particular map by passing it
the source of the map you want to process, like
'/res/103/jerf/navmap.course.sequence'.

=item * B<include_top_level_map>: default: false

If you need to include the top level map (meaning the course) in the
rendered output set this to true

=item * B<navmap>: default: constructs one from %env

A reference to a navmap, used only if an iterator is not passed in. If
this is necessary to make an iterator but it is not passed in, a new
one will be constructed based on env info. This is useful to do basic
error checking before passing it off to render.

=item * B<r>: default: must be passed in

The standard Apache response object. This must be passed to the
renderer or the course hash will be locked.

=item * B<cols>: default: empty (useless)

An array reference

=item * B<showParts>:default true

A flag. If true, a line for the resource itself, and a line
for each part will be displayed. If not, only one line for each
resource will be displayed.

=item * B<condenseParts>: default true

A flag. If true, if all parts of the problem have the same
status and that status is Nothing Set, Correct, or Network Failure,
then only one line will be displayed for that resource anyhow. If no,
all parts will always be displayed. If showParts is 0, this is
ignored.

=item * B<jumpCount>: default: determined from %env

A string identifying the URL to place the anchor 'curloc' at.
It is the responsibility of the renderer user to
ensure that the #curloc is in the URL. By default, determined through
the use of the env{} 'jump' information, and should normally "just
work" correctly.

=item * B<here>: default: empty string

A Symb identifying where to place the 'here' marker. The empty
string means no marker.

=item * B<indentString>: default: 25 pixel whitespace image

A string identifying the indentation string to use. 

=item * B<queryString>: default: empty

A string which will be prepended to the query string used when the
folders are opened or closed. You can use this to pass
application-specific values.

=item * B<url>: default: none

The url the folders will link to, which should be the current
page. Required if the resource info column is shown, and you 
are allowing the user to open and close folders.

=item * B<currentJumpIndex>: default: no jumping

Describes the currently-open row number to cause the browser to jump
to, because the user just opened that folder. By default, pulled from
the Jump information in the env{'form.*'}.

=item * B<printKey>: default: false

If true, print the key that appears on the top of the standard
navmaps.

=item * B<printCloseAll>: default: true

If true, print the "Close all folders" or "open all folders"
links.

=item * B<filterFunc>: default: sub {return 1;} (accept everything)

A function that takes the resource object as its only parameter and
returns a true or false value. If true, the resource is displayed. If
false, it is simply skipped in the display.

=item * B<suppressEmptySequences>: default: false

If you're using a filter function, and displaying sequences to orient
the user, then frequently some sequences will be empty. Setting this to
true will cause those sequences not to display, so as not to confuse the
user into thinking that if the sequence is there there should be things
under it; for example, see the "Show Uncompleted Homework" view on the
B<NAV> screen.

=item * B<suppressNavmaps>: default: false

If true, will not display Navigate Content resources. 

=back

=head2 Additional Info

In addition to the parameters you can pass to the renderer, which will
be passed through unchange to the column renderers, the renderer will
generate the following information which your renderer may find
useful:

=over 4

=item * B<counter>: 

Contains the number of rows printed. Useful after calling the render 
function, as you can detect whether anything was printed at all.

=item * B<isNewBranch>:

Useful for renderers: If this resource is currently the first resource
of a new branch, this will be true. The Resource column (leftmost in the
navmaps screen) uses this to display the "new branch" icon 

=back

=cut


=head1 SUBROUTINES

=over

=item update()

=item addToFilter()

Convenience functions: Returns a string that adds or subtracts
the second argument from the first hash, appropriate for the 
query string that determines which folders to recurse on

=item removeFromFilter()

=item getLinkForResource()

Convenience function: Given a stack returned from getStack on the iterator,
return the correct src() value.

=item getDescription()

Convenience function: This separates the logic of how to create
the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
etc.) into a separate function. It takes a resource object as the
first parameter, and the part number of the resource as the second.
It's basically a big switch statement on the status of the resource.

=item dueInLessThan24Hours()

Convenience function, so others can use it: Is the problem due in less than 24 hours, and still can be done?

=item lastTry()

Convenience function, so others can use it: Is there only one try remaining for the
part, with more than one try to begin with, not due yet and still can be done?

=item advancedUser()

This puts a human-readable name on the env variable.

=item timeToHumanString()

timeToHumanString takes a time number and converts it to a
human-readable representation, meant to be used in the following
manner:

=over 4

=item * print "Due $timestring"

=item * print "Open $timestring"

=item * print "Answer available $timestring"

=back

Very, very, very, VERY English-only... goodness help a localizer on
this func...

=item resource()

returns 0

=item communication_status()

returns 1

=item quick_status()

returns 2

=item long_status()

returns 3

=item part_status_summary()

returns 4

=item render_resource()

=item render_communication_status()

=item render_quick_status()

=item render_long_status()

=item render_parts_summary_status()

=item setDefault()

=item cmp_title()

=item render()

=item add_linkitem()

=item show_linkitems_toolbar()

=back

=cut

package Apache::lonnavmaps;

use strict;
use GDBM_File;
use Apache::loncommon();
use Apache::lonenc();
use Apache::lonlocal;
use Apache::lonnet;
use Apache::lonmap;

use POSIX qw (ceil floor strftime);
use Time::HiRes qw( gettimeofday tv_interval );
use LONCAPA;
use DateTime();
use HTML::Entities;

# For debugging

#use Data::Dumper;


# symbolic constants
sub SYMB { return 1; }
sub URL { return 2; }
sub NOTHING { return 3; }

# Some data

my $resObj = "Apache::lonnavmaps::resource";

# Keep these mappings in sync with lonquickgrades, which usesthe colors
# instead of the icons.
my %statusIconMap = 
    (
     $resObj->CLOSED       => '',
     $resObj->OPEN         => 'navmap.open.gif',
     $resObj->CORRECT      => 'navmap.correct.gif',
     $resObj->PARTIALLY_CORRECT      => 'navmap.partial.gif',
     $resObj->INCORRECT    => 'navmap.wrong.gif',
     $resObj->ATTEMPTED    => 'navmap.ellipsis.gif',
     $resObj->ERROR        => ''
     );

my %iconAltTags =   #texthash does not work here
    ( 'navmap.correct.gif'  => 'Correct',
      'navmap.wrong.gif'    => 'Incorrect',
      'navmap.open.gif'     => 'Is Open',
      'navmap.partial.gif'  => 'Partially Correct',
      'navmap.ellipsis.gif' => 'Attempted',
     );

# Defines a status->color mapping, null string means don't color
my %colormap = 
    ( $resObj->NETWORK_FAILURE        => '',
      $resObj->CORRECT                => '',
      $resObj->EXCUSED                => '#3333FF',
      $resObj->PAST_DUE_ANSWER_LATER  => '',
      $resObj->PAST_DUE_NO_ANSWER     => '',
      $resObj->ANSWER_OPEN            => '#006600',
      $resObj->OPEN_LATER             => '',
      $resObj->TRIES_LEFT             => '',
      $resObj->INCORRECT              => '',
      $resObj->OPEN                   => '',
      $resObj->NOTHING_SET            => '',
      $resObj->ATTEMPTED              => '',
      $resObj->CREDIT_ATTEMPTED       => '',
      $resObj->ANSWER_SUBMITTED       => '',
      $resObj->PARTIALLY_CORRECT      => '#006600'
      );
# And a special case in the nav map; what to do when the assignment
# is not yet done and due in less than 24 hours
my $hurryUpColor = "#FF0000";

sub addToFilter {
    my $hashIn = shift;
    my $addition = shift;
    my %hash = %$hashIn;
    $hash{$addition} = 1;

    return join (",", keys(%hash));
}

sub removeFromFilter {
    my $hashIn = shift;
    my $subtraction = shift;
    my %hash = %$hashIn;

    delete $hash{$subtraction};
    return join(",", keys(%hash));
}

sub getLinkForResource {
    my $stack = shift;
    my $res;

    # Check to see if there are any pages in the stack
    foreach $res (@$stack) {
        if (defined($res)) {
	    my $anchor;
	    if ($res->is_page()) {
		foreach my $item (@$stack) { if (defined($item)) { $anchor = $item; }  }
		if ($anchor->encrypted() && !&advancedUser()) {
		    $anchor='LC_'.$anchor->id();
		} else {
		    $anchor=&escape($anchor->shown_symb());
		}
		return ($res->link(),$res->shown_symb(),$anchor);
	    }
            # in case folder was skipped over as "only sequence"
	    my ($map,$id,$src)=&Apache::lonnet::decode_symb($res->symb());
	    if ($map=~/\.page$/) {
		my $url=&Apache::lonnet::clutter($map);
		$anchor=&escape($res->shown_symb());
		return ($url,$res->shown_symb(),$anchor);
	    }
        }
    }

    # Failing that, return the src of the last resource that is defined
    # (when we first recurse on a map, it puts an undefined resource
    # on the bottom because $self->{HERE} isn't defined yet, and we
    # want the src for the map anyhow)
    foreach my $item (@$stack) {
        if (defined($item)) { $res = $item; }
    }

    if ($res) {
	return ($res->link(),$res->shown_symb());
    }
    return;
}



sub getDescription {
    my $res = shift;
    my $part = shift;
    my $status = $res->status($part);

    my $open = $res->opendate($part);
    my $due = $res->duedate($part);
    my $answer = $res->answerdate($part);

    if ($status == $res->NETWORK_FAILURE) { 
        return &mt("Having technical difficulties; please check status later"); 
    }
    if ($status == $res->NOTHING_SET) {
        return &Apache::lonhtmlcommon::direct_parm_link(&mt('Not currently assigned'),$res->symb(),'opendate',$part);
    }
    if ($status == $res->OPEN_LATER) {
        return &mt("Open [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($open,'start'),$res->symb(),'opendate',$part));
    }
    my $slotinfo;
    if ($res->simpleStatus($part) == $res->OPEN) {
        unless (&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) {
            my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
            my $slotmsg;
            if ($slot_status == $res->UNKNOWN) {
                $slotmsg = &mt('Reservation status unknown');
            } elsif ($slot_status == $res->RESERVED) {
                $slotmsg = &mt('Reserved - ends [_1]',
                           timeToHumanString($slot_time,'end'));
            } elsif ($slot_status == $res->RESERVED_LOCATION) {
                $slotmsg = &mt('Reserved - specific location(s) - ends [_1]',
                           timeToHumanString($slot_time,'end'));
            } elsif ($slot_status == $res->RESERVED_LATER) {
                $slotmsg = &mt('Reserved - next open [_1]',
                           timeToHumanString($slot_time,'start'));
            } elsif ($slot_status == $res->RESERVABLE) {
                $slotmsg = &mt('Reservable, reservations close [_1]',
                           timeToHumanString($slot_time,'end'));
            } elsif ($slot_status == $res->NEEDS_CHECKIN) {
                $slotmsg = &mt('Reserved, check-in needed - ends [_1]',
                           timeToHumanString($slot_time,'end'));
            } elsif ($slot_status == $res->RESERVABLE_LATER) {
                $slotmsg = &mt('Reservable, reservations open [_1]',
                           timeToHumanString($slot_time,'start'));
            } elsif ($slot_status == $res->NOT_IN_A_SLOT) {
                $slotmsg = &mt('Reserve a time/place to work');
            } elsif ($slot_status == $res->NOTRESERVABLE) {
                $slotmsg = &mt('Reservation not available');
            } elsif ($slot_status == $res->WAITING_FOR_GRADE) {
                $slotmsg = &mt('Submission in grading queue');
            }
            if ($slotmsg) {
                if ($res->is_task() || !$due) {
                     return $slotmsg;
                }
                $slotinfo = ('&nbsp;' x 2).'('.$slotmsg.')';
            }
        }
    }
    if ($status == $res->OPEN) {
        if ($due) {
	    if ($res->is_practice()) {
		return &mt("Closes [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'start'),$res->symb(),'duedate',$part)).$slotinfo;
	    } else {
		return &mt("Due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'duedate',$part)).$slotinfo;
	    }
        } else {
            return &Apache::lonhtmlcommon::direct_parm_link(&mt("Open, no due date"),$res->symb(),'duedate',$part).$slotinfo;
        }
    }
    if ($status == $res->PAST_DUE_ANSWER_LATER) {
        return &mt("Answer open [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($answer,'start'),$res->symb(),'answerdate',$part));
    }
    if ($status == $res->PAST_DUE_NO_ANSWER) {
	if ($res->is_practice()) {
	    return &mt("Closed [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'start'),$res->symb(),'answerdate,duedate',$part));
	} else {
	    return &mt("Was due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'answerdate,duedate',$part));
	}
    }
    if (($status == $res->ANSWER_OPEN || $status == $res->PARTIALLY_CORRECT)
	&& $res->handgrade($part) ne 'yes') {
        my $msg = &mt('Answer available');
        my $parmlist = 'answerdate,duedate';
        if (($res->is_tool) && ($res->is_gradable())) {
            if (($status == $res->PARTIALLY_CORRECT) && ($res->parmval('retrypartial',$part))) {
                $msg = &mt('Grade received');
                $parmlist = 'retrypartial';
            } else {
                $msg = &mt('Grade available');
            }
        }
        return &Apache::lonhtmlcommon::direct_parm_link($msg,$res->symb(),$parmlist,$part);
    }
    if ($status == $res->EXCUSED) {
        return &mt("Excused by instructor");
    }
    if ($status == $res->ATTEMPTED) {
        if ($res->is_anonsurvey($part) || $res->is_survey($part)) {
            return &mt("Survey submission recorded");
        } else {
            return &mt("Answer submitted, not yet graded");
        }
    }
    if ($status == $res->CREDIT_ATTEMPTED) {
        if ($res->is_anonsurvey($part) || $res->is_survey($part)) {
            return &mt("Credit for survey submission");
        }
    }
    if ($status == $res->TRIES_LEFT) {
        my $tries = $res->tries($part);
        my $maxtries = $res->maxtries($part);
        my $triesString = "";
        if ($tries && $maxtries) {
            $triesString = '<span class="LC_fontsize_medium"><i>('.&mt('[_1] of [quant,_2,try,tries] used',$tries,$maxtries).')</i></span>';
            if ($maxtries > 1 && $maxtries - $tries == 1) {
                $triesString = "<b>$triesString</b>";
            }
        }
        if ($due) {
            return &mt("Due [_1]",&Apache::lonhtmlcommon::direct_parm_link(&timeToHumanString($due,'end'),$res->symb(),'duedate',$part)) .
                " $triesString";
        } else {
            return &Apache::lonhtmlcommon::direct_parm_link(&mt("No due date"),$res->symb(),'duedate',$part)." $triesString";
        }
    }
    if ($status == $res->ANSWER_SUBMITTED) {
        return &mt('Answer submitted');
    }
}


sub dueInLessThan24Hours {
    my $res = shift;
    my $part = shift;
    my $status = $res->status($part);

    return ($status == $res->OPEN() ||
            $status == $res->TRIES_LEFT()) &&
	    $res->duedate($part) && $res->duedate($part) < time()+(24*60*60) &&
	    $res->duedate($part) > time();
}


sub lastTry {
    my $res = shift;
    my $part = shift;

    my $tries = $res->tries($part);
    my $maxtries = $res->maxtries($part);
    return $tries && $maxtries && $maxtries > 1 &&
        $maxtries - $tries == 1 && $res->duedate($part) &&
        $res->duedate($part) > time();
}


sub advancedUser {
    return $env{'request.role.adv'};
}

sub timeToHumanString {
    my ($time,$type,$format) = @_;

    # zero, '0' and blank are bad times
    if (!$time) {
        return &mt('never');
    }
    unless (&Apache::lonlocal::current_language()=~/^en/) {
	return &Apache::lonlocal::locallocaltime($time);
    } 
    my $now = time();

    # Positive = future
    my $delta = $time - $now;

    my $minute = 60;
    my $hour = 60 * $minute;
    my $day = 24 * $hour;
    my $week = 7 * $day;
    my $inPast = 0;

    # Logic in comments:
    # Is it now? (extremely unlikely)
    if ( $delta == 0 ) {
        return "this instant";
    }

    if ($delta < 0) {
        $inPast = 1;
        $delta = -$delta;
    }

    if ( $delta > 0 ) {

        my $tense = $inPast ? " ago" : "";
        my $prefix = $inPast ? "" : "in ";
        
        # Less than a minute
        if ( $delta < $minute ) {
            if ($delta == 1) { return "${prefix}1 second$tense"; }
            return "$prefix$delta seconds$tense";
        }

        # Less than an hour
        if ( $delta < $hour ) {
            # If so, use minutes; or minutes, seconds (if format requires)
            my $minutes = floor($delta / 60);
            if (($format ne '') && ($format =~ /\%(T|S)/)) {
                my $display;
                if ($minutes == 1) {
                    $display = "${prefix}1 minute";
                } else {
                    $display = "$prefix$minutes minutes";
                }
                my $seconds = $delta % $minute;
                if ($seconds == 0) {
                    $display .= $tense;
                } elsif ($seconds == 1) {
                    $display .= ", 1 second$tense";
                } else {
                    $display .= ", $seconds seconds$tense";
                }
                return $display;
            }
            if ($minutes == 1) { return "${prefix}1 minute$tense"; }
            return "$prefix$minutes minutes$tense";
        }
        
        # Is it less than 24 hours away? If so,
        # display hours + minutes, (and + seconds, if format specified it)  
        if ( $delta < $hour * 24) {
            my $hours = floor($delta / $hour);
            my $minutes = floor(($delta % $hour) / $minute);
            my $hourString = "$hours hours";
            my $minuteString = ", $minutes minutes";
            if ($hours == 1) {
                $hourString = "1 hour";
            }
            if ($minutes == 1) {
                $minuteString = ", 1 minute";
            }
            if ($minutes == 0) {
                $minuteString = "";
            }
            if (($format ne '') && ($format =~ /\%(T|S)/)) {
                my $display = "$prefix$hourString$minuteString";
                my $seconds = $delta-(($hours * $hour)+($minutes * $minute));
                if ($seconds == 0) {
                    $display .= $tense;
                } elsif ($seconds == 1) {
                    $display .= ", 1 second$tense";
                } else {
                    $display .= ", $seconds seconds$tense";
                }
                return $display;
            }
            return "$prefix$hourString$minuteString$tense";
        }

        # Date/time is more than 24 hours away

	my $dt = DateTime->from_epoch(epoch => $time)
	                 ->set_time_zone(&Apache::lonlocal::gettimezone());

	# If there's a caller supplied format, use it, unless it only displays
        # H:M:S or H:M.

	if (($format ne '') && ($format ne '%T') && ($format ne '%R')) {
	    my $timeStr = $dt->strftime($format);
	    return $timeStr.' ('.$dt->time_zone_short_name().')';
	}

        # Less than 5 days away, display day of the week and
        # HH:MM

        if ( $delta < $day * 5 ) {
            my $timeStr = $dt->strftime("%A, %b %e at %I:%M %P (%Z)");
            $timeStr =~ s/12:00 am/00:00/;
            $timeStr =~ s/12:00 pm/noon/;
            return ($inPast ? "last " : "this ") .
                $timeStr;
        }
        
	my $conjunction='on';
	if ($type eq 'start') {
	    $conjunction='at';
	} elsif ($type eq 'end') {
	    $conjunction='by';
	}
        # Is it this year?
	my $dt_now = DateTime->from_epoch(epoch => $now)
	                     ->set_time_zone(&Apache::lonlocal::gettimezone());
        if ( $dt->year() == $dt_now->year()) {
            # Return on Month Day, HH:MM meridian
            my $timeStr = $dt->strftime("$conjunction %A, %b %e at %I:%M %P (%Z)");
            $timeStr =~ s/12:00 am/00:00/;
            $timeStr =~ s/12:00 pm/noon/;
            return $timeStr;
        }

        # Not this year, so show the year
        my $timeStr = 
	    $dt->strftime("$conjunction %A, %b %e %Y at %I:%M %P (%Z)");
        $timeStr =~ s/12:00 am/00:00/;
        $timeStr =~ s/12:00 pm/noon/;
        return $timeStr;
    }
}


sub resource { return 0; }
sub communication_status { return 1; }
sub quick_status { return 2; }
sub long_status { return 3; }
sub part_status_summary { return 4; }

sub render_resource {
    my ($resource, $part, $params) = @_;

    my $editmapLink;
    my $nonLinkedText = ''; # stuff after resource title not in link

    my $link = $params->{"resourceLink"};
    if ($resource->ext()) {
        $link =~ s/\#.+(\?)/$1/g;
    }

    #  The URL part is not escaped at this point, but the symb is... 

    my $src = $resource->src();
    my $it = $params->{"iterator"};
    my $filter = $it->{FILTER};

    my $title = $resource->compTitle();

    my $partLabel = "";
    my $newBranchText = "";
    my $location=&Apache::loncommon::lonhttpdurl("/adm/lonIcons");
    # If this is a new branch, label it so
    if ($params->{'isNewBranch'}) {
        $newBranchText = "<img src='$location/branch.gif' alt=".mt('Branch')." />";
    }

    my $whitespace = $location.'/whitespace_21.gif';
    my ($nomodal,$linkopen,$linkclose);
    unless ($resource->is_map() || $params->{'resource_nolink'}) {
        $linkopen = "<img src='$whitespace' alt='' />";
        $linkclose = "</a>";
        if (($params->{'modalLink'}) && (!$resource->is_sequence())) {
            if ($link =~m{^(?:|/adm/wrapper)/ext/([^#]+)}) {
                my $exturl = $1;
                if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
                    $nomodal = 1;
                }
            } elsif (($link eq "/public/$LONCAPA::match_domain/$LONCAPA::match_courseid/syllabus") &&
                     ($env{'request.course.id'}) && ($ENV{'SERVER_PORT'} == 443) &&
                     ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
                $nomodal = 1;
            }
            my $esclink = &js_escape($link);
            if ($nomodal) {
                $linkopen .= "<a href=\"#\" onclick=\"javascript:window.open('$esclink','resourcepreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1'); return false;\" />";
            } else {
                $linkopen .= "<a href=\"$link\" onclick=\"javascript:openMyModal('$esclink',600,500,'yes','true'); return false;\">";
            }
        } else {
            $linkopen .= "<a href=\"$link\">";
        }
    }

    # Default icon: unknown page
    my $icon = "<img class=\"LC_contentImage\" src='$location/unknown.gif' alt='' />";
    
    if ($resource->is_problem()) {
        if ($part eq '0' || $params->{'condensed'}) {
	    $icon = '<img class="LC_contentImage" src="'.$location.'/';
	    if ($resource->is_task()) {
		$icon .= 'task.gif" alt="'.&mt('Task');
	    } else {
		$icon .= 'problem.gif" alt="'.&mt('Problem');
	    }
	    $icon .='" />';
        } else {
            $icon = $params->{'indentString'};
        }
    } else {
	$icon = "<img class=\"LC_contentImage\" src='".&Apache::loncommon::icon($resource->src)."' alt='' />";
    }

    # Display the correct map icon to open or shut map
    if ($resource->is_map()) {
        my $mapId = $resource->map_pc();
        my $nowOpen = !defined($filter->{$mapId});
        if ($it->{CONDITION}) {
            $nowOpen = !$nowOpen;
        }
	
	my $folderType = $resource->is_sequence() ? 'folder' : 'page';
        my $title=$resource->title;
		$title=~s/\"/\&qout;/g;
        if (!$params->{'resource_no_folder_link'}) {
            $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
            $icon = "<img src='$location/arrow." . ($nowOpen ? 'closed' : 'open') . ".gif' alt='' />"
                    ."<img class=\"LC_contentImage\" src='$location/$icon' alt=\""
                    .($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" />";			
            $linkopen = "<a href=\"" . $params->{'url'} . '?' . 
                $params->{'queryString'} . '&amp;filter=';
            $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
                addToFilter($filter, $mapId) :
                removeFromFilter($filter, $mapId);
            $linkopen .= "&amp;condition=" . $it->{CONDITION} . '&amp;hereType='
                . $params->{'hereType'} . '&amp;here=' .
                &escape($params->{'here'}) . 
                '&amp;jump=' .
                &escape($resource->symb()) . 
                "&amp;folderManip=1\">";
            $linkclose = '</a>';
        } else {
            # Don't allow users to manipulate folder
            $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
            $icon = "<img class=\"LC_space\" src='$whitespace' alt='' />"."<img class=\"LC_contentImage\" src='$location/$icon' alt=\"".($nowOpen ? &mt('Open Folder') : &mt('Close Folder')).' '.$title."\" />";
            if ($params->{'caller'} eq 'sequence') {
                $linkopen = "<a href=\"$link\">";
                $linkclose = '</a>';
            } else {
                $linkopen = "";
                $linkclose = "";
            }
        }
        if (((&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) ||
              (&Apache::lonnet::allowed('cev',$env{'request.course.id'}))) &&
            ($resource->symb=~/\_\_\_[^\_]+\_\_\_uploaded/)) {
            if (!$params->{'map_no_edit_link'}) {
                my $icon = &Apache::loncommon::lonhttpdurl('/res/adm/pages').'/editmap.png';
                $editmapLink='&nbsp;'.
                         '<a href="/adm/coursedocs?command=directnav&amp;symb='.&escape($resource->symb()).'">'.
                         '<img src="'.$icon.'" alt="'.&mt('Edit Content').'" title="'.&mt('Edit Content').'" />'.
                         '</a>';
            }
        }
        if ($params->{'mapHidden'} || $resource->randomout()) {
            $nonLinkedText .= ' <span class="LC_warning">('.&mt('hidden').')</span> ';
        } elsif ($params->{'mapUnlisted'}) {
            $nonLinkedText .= ' <span class="LC_warning">('.&mt('unlisted').')</span> ';
        } elsif ($params->{'mapHiddenDeepLink'} || $resource->deeplinkout()) {
            $nonLinkedText .= ' <span class="LC_warning">('.&mt('not shown').')</span> ';
        }
    } else {
        if ($resource->randomout()) {
            $nonLinkedText .= ' <span class="LC_warning">('.&mt('hidden').')</span> ';
        } elsif ($resource->deeplinkout()) {
            $nonLinkedText .= ' <span class="LC_warning">('.&mt('not shown').')</span> ';
        } else {
            my $deeplink = $resource->deeplink($params->{caller});
            if ((($deeplink eq 'absent') || ($deeplink eq 'grades')) &&
                  &advancedUser()) {
                $nonLinkedText .= ' <span class="LC_warning">('.&mt('unlisted').')</span> ';
            } elsif (($deeplink) && ($deeplink) ne 'full') {
                if (&advancedUser()) {
                    $nonLinkedText .= ' <span class="LC_warning">('.&mt('deep-link access').
                                      ')</span> ';
                } else {
                    $nonLinkedText .= ' <span class="LC_warning">('.&mt('access via external site').
                                      ')</span> ';
                }
            }
        }
    }
    if (!$resource->condval()) {
        $nonLinkedText .= ' <span class="LC_info">('.&mt('conditionally hidden').')</span> ';
    }
    if (($resource->is_practice()) && ($resource->is_raw_problem())) {
        $nonLinkedText .=' <span class="LC_info"><b>'.&mt('not graded').'</b></span>';
    }

    # We're done preparing and finally ready to start the rendering
    my $result = '<td class="LC_middle">';
    my $newfolderType = $resource->is_sequence() ? 'folder' : 'page';
	
    my $indentLevel = $params->{'indentLevel'};
    if ($newBranchText) { $indentLevel--; }

    # print indentation
    for (my $i = 0; $i < $indentLevel; $i++) {
        $result .= $params->{'indentString'};
    }

    # Decide what to display
    $result .= "$newBranchText$linkopen$icon$linkclose";
    
    my $curMarkerBegin = '';
    my $curMarkerEnd = '';

    # Is this the current resource?
    if (!$params->{'displayedHereMarker'} && 
        $resource->symb() eq $params->{'here'} ) {
        unless ($resource->is_map()) {
            $curMarkerBegin = '<span class="LC_current_nav_location">';
            $curMarkerEnd = '</span>';
        }
	$params->{'displayedHereMarker'} = 1;
    }

    if ($resource->is_problem() && $part ne '0' && 
        !$params->{'condensed'}) {
	my $displaypart=$resource->part_display($part);
        $partLabel = " (".&mt('Part: [_1]', $displaypart).")";
	if ($link!~/\#/) { $link.='#'.&escape($part); }
        $title = "";
    }

    if ($params->{'condensed'} && $resource->countParts() > 1) {
        $nonLinkedText .= ' ('.&mt('[_1] parts', $resource->countParts()).')';
    }

    if (!$params->{'resource_nolink'} && !$resource->is_sequence() && !$resource->is_empty_sequence) {
        $linkclose = '</a>';
        if ($params->{'modalLink'}) {
            my $esclink = &js_escape($link);
            if ($nomodal) {
                $linkopen = "<a href=\"#\" onclick=\"javascript:window.open('$esclink','resourcepreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1'); return false;\" />";
            } else {
                $linkopen = "<a href=\"$link\" onclick=\"javascript:openMyModal('$esclink',600,500,'yes','true'); return false;\">";
            }
        } else {
            $linkopen = "<a href=\"$link\">";
        }
    }
    $result .= "$curMarkerBegin$linkopen$title$partLabel$linkclose$curMarkerEnd$editmapLink$nonLinkedText</td>";

    return $result;
}

sub render_communication_status {
    my ($resource, $part, $params) = @_;
    my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";

    my $link = $params->{"resourceLink"};
    my $linkopen = "<a href=\"$link\">";
    my $linkclose = "</a>";
    my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc");

    if ($resource->hasDiscussion()) {
        $discussionHTML = $linkopen .
            '<img alt="'.&mt('New Discussion').'" src="'.$location.'/chat.gif" title="'.&mt('New Discussion').'"/>' .
            $linkclose;
    }
    
    if ($resource->getFeedback()) {
        my $feedback = $resource->getFeedback();
        foreach my $msgid (split(/\,/, $feedback)) {
            if ($msgid) {
                $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
                    . &escape($msgid) . '">'
                    . '<img alt="'.&mt('New E-mail').'" src="'.$location.'/feedback.gif" title="'.&mt('New E-mail').'"/></a>';
            }
        }
    }
    
    if ($resource->getErrors()) {
        my $errors = $resource->getErrors();
        my $errorcount = 0;
        foreach my $msgid (split(/,/, $errors)) {
            last if ($errorcount>=10); # Only output 10 bombs maximum
            if ($msgid) {
                $errorcount++;
                $errorHTML .= '&nbsp;<a href="/adm/email?display='
                    . &escape($msgid) . '">'
                    . '<img alt="'.&mt('New Error').'" src="'.$location.'/bomb.gif" title="'.&mt('New Error').'"/></a>';
            }
        }
    }

    if ($params->{'multipart'} && $part != '0') {
	$discussionHTML = $feedbackHTML = $errorHTML = '';
    }
    return "<td class=\"LC_middle\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";

}
sub render_quick_status {
    my ($resource, $part, $params) = @_;
    my $result = "";
    my $firstDisplayed = !$params->{'condensed'} && 
        $params->{'multipart'} && $part eq "0";

    my $link = $params->{"resourceLink"};
    my $linkopen = "<a href=\"$link\">";
    my $linkclose = "</a>";
	
	$result .= '<td class="LC_middle">';
    if ($resource->is_gradable() &&
        !$firstDisplayed) {
        my $icon = $statusIconMap{$resource->simpleStatus($part)};
        my $alt = $iconAltTags{$icon};
        if ($icon) {
	    my $location=
		&Apache::loncommon::lonhttpdurl("/adm/lonIcons/$icon");
		$result .= $linkopen.'<img src="'.$location.'" alt="'.&mt($alt).'" title="'.&mt($alt).'" />'.$linkclose;            
        } else {
            $result .= "&nbsp;";
        }
    } else { # not problem, no icon
        $result .= "&nbsp;";
    }
	$result .= "</td>\n";
    return $result;
}
sub render_long_status {
    my ($resource, $part, $params) = @_;
    my $result = '<td class="LC_middle LC_right">';
    my $firstDisplayed = !$params->{'condensed'} && 
        $params->{'multipart'} && $part eq "0";
                
    my $color;
    my $info = '';
    if ($resource->is_gradable() || $resource->is_practice()) {
        $color = $colormap{$resource->status};

        if (dueInLessThan24Hours($resource, $part)) {
            $color = $hurryUpColor;
            $info = ' title="'.&mt('Due in less than 24 hours!').'"';
        } elsif (lastTry($resource, $part)) {
            unless (($resource->problemstatus($part) eq 'no') ||
                    ($resource->problemstatus($part) eq 'no_feedback_ever')) {
                $color = $hurryUpColor;
                $info = ' title="'.&mt('One try remaining!').'"';
            }
         }
    }

    if (($resource->kind() eq "res") &&
        ($resource->is_raw_problem() || $resource->is_gradable()) &&
        !$firstDisplayed) {
        if ($color) {$result .= '<span style="color:'.$color.'"'.$info.'><b>'; }
        $result .= getDescription($resource, $part);
        if ($color) {$result .= "</b></span>"; }
    }
    if ($resource->is_map() && &advancedUser() && $resource->randompick()) {
        $result .= &mt('(randomly select [_1])', $resource->randompick());
    }
    if ($resource->is_map() && &advancedUser() && $resource->randomorder()) {
        $result .= &mt('(randomly ordered)');
    }

    # Debugging code
    #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) .
    #	' - Part: ' . $part;

    $result .= "</td>\n";
    
    return $result;
}

# Colors obtained by taking the icons, matching the colors, and
# possibly reducing the Value (HSV) of the color, if it's too bright
# for text, generally by one third or so.
my %statusColors = 
    (
     $resObj->CLOSED => '#000000',
     $resObj->OPEN   => '#998b13',
     $resObj->CORRECT => '#26933f',
     $resObj->INCORRECT => '#c48207',
     $resObj->ATTEMPTED => '#a87510',
     $resObj->ERROR => '#000000'
     );
my %statusStrings = 
    (
     $resObj->CLOSED => 'Not yet open',
     $resObj->OPEN   => 'Open',
     $resObj->CORRECT => 'Correct',
     $resObj->INCORRECT => 'Incorrect',
     $resObj->ATTEMPTED => 'Attempted',
     $resObj->ERROR => 'Network Error'
     );
my @statuses = ($resObj->CORRECT, $resObj->ATTEMPTED, $resObj->INCORRECT, $resObj->OPEN, $resObj->CLOSED, $resObj->ERROR);

sub render_parts_summary_status {
    my ($resource, $part, $params) = @_;
    if (!$resource->is_gradable() && !$resource->contains_problem) { return '<td></td>'; }
    if ($params->{showParts}) { 
	return '<td></td>';
    }

    my $td = "<td align='right'>\n";
    my $endtd = "</td>\n";
    my @probs;

    if ($resource->contains_problem) {
	@probs=$resource->retrieveResources($resource,sub { $_[0]->is_problem() },1,0);
    } else {
	@probs=($resource);
    }
    my $return;
    my %overallstatus;
    my $totalParts;
    foreach my $resource (@probs) {
	# If there is a single part, just show the simple status
	if ($resource->singlepart()) {
	    my $status = $resource->simpleStatus(${$resource->parts}[0]);
	    $overallstatus{$status}++;
	    $totalParts++;
	    next;
	}
	# Now we can be sure the $part doesn't really matter.
	my $statusCount = $resource->simpleStatusCount();
	my @counts;
	foreach my $status (@statuses) {
	    # decouple display order from the simpleStatusCount order
	    my $slot = Apache::lonnavmaps::resource::statusToSlot($status);
	    if ($statusCount->[$slot]) {
		$overallstatus{$status}+=$statusCount->[$slot];
		$totalParts+=$statusCount->[$slot];
	    }
	}
    }
    $return.= $td . $totalParts . ' parts: ';
    foreach my $status (@statuses) {
        if ($overallstatus{$status}) {
            $return.='<span style="color:' . $statusColors{$status}
                   . '">' . $overallstatus{$status} . ' '
                   . $statusStrings{$status} . '</span>';
        }
    }
    $return.= $endtd;
    return $return;
}

my @preparedColumns = (\&render_resource, \&render_communication_status,
                       \&render_quick_status, \&render_long_status,
		       \&render_parts_summary_status);

sub setDefault {
    my ($val, $default) = @_;
    if (!defined($val)) { return $default; }
    return $val;
}

sub cmp_title {
    my ($atitle,$btitle) = (lc($_[0]->compTitle),lc($_[1]->compTitle));
    $atitle=~s/^\s*//;
    $btitle=~s/^\s*//;
    return $atitle cmp $btitle;
}

sub render {
    my $args = shift;
    &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
    my $result = '';
    # Configure the renderer.
    my $cols = $args->{'cols'};
    if (!defined($cols)) {
        # no columns, no nav maps.
        return '';
    }
    my $navmap;
    if (defined($args->{'navmap'})) {
        $navmap = $args->{'navmap'};
    }

    my $r = $args->{'r'};
    my $queryString = $args->{'queryString'};
    my $jump = $args->{'jump'};
    my $here = $args->{'here'};
    my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
    my $closeAllPages = setDefault($args->{'closeAllPages'}, 0);
    my $currentJumpDelta = 2; # change this to change how many resources are displayed
                             # before the current resource when using #current

    # If we were passed 'here' information, we are not rendering
    # after a folder manipulation, and we were not passed an
    # iterator, make sure we open the folders to show the "here"
    # marker
    my $filterHash = {};
    # Figure out what we're not displaying
    foreach my $item (split(/\,/, $env{"form.filter"})) {
        if ($item) {
            $filterHash->{$item} = "1";
        }
    }

    # Filter: Remember filter function and add our own filter: Refuse
    # to show hidden resources unless the user can see them.
    my $userCanSeeHidden = advancedUser();
    my $filterFunc = setDefault($args->{'filterFunc'},
                                sub {return 1;});
    if (!$userCanSeeHidden) {
        # Without renaming the filterfunc, the server seems to go into
        # an infinite loop
        my $oldFilterFunc = $filterFunc;
        $filterFunc = sub { my $res = shift; return !$res->randomout() &&
                                ($res->deeplink($args->{'caller'}) ne 'absent') &&
                                ($res->deeplink($args->{'caller'}) ne 'grades') &&
                                !$res->deeplinkout() &&
                                &$oldFilterFunc($res);};
    }

    my $condition = 0;
    if ($env{'form.condition'}) {
        $condition = 1;
    }

    if (!$env{'form.folderManip'} && !defined($args->{'iterator'})) {
        # Step 1: Check to see if we have a navmap
        if (!defined($navmap)) {
            $navmap = Apache::lonnavmaps::navmap->new();
	    if (!defined($navmap)) {
		# no longer in course
		return '<span class="LC_error">'.&mt('No course selected').'</span><br />
                        <a href="/adm/roles">'.&mt('Select a course').'</a><br />';
	    }
	}

        # Step two: Locate what kind of here marker is necessary
        # Determine where the "here" marker is and where the screen jumps to.

        if ($env{'form.postsymb'} ne '') {
            $here = $jump = &Apache::lonnet::symbclean($env{'form.postsymb'});
        } elsif ($env{'form.postdata'} ne '') {
            # couldn't find a symb, is there a URL?
            my $currenturl = $env{'form.postdata'};
            #$currenturl=~s/^http\:\/\///;
            #$currenturl=~s/^[^\/]+//;
            unless ($args->{'caller'} eq 'sequence') {
                $here = $jump = &Apache::lonnet::symbread($currenturl);
            }
	}
	if (($here eq '') && ($args->{'caller'} ne 'sequence')) {
	    my $last;
	    if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                    &GDBM_READER(),0640)) {
		$last=$hash{'last_known'};
		untie(%hash);
	    }
	    if ($last) { $here = $jump = $last; }
	}

        # Step three: Ensure the folders are open
        my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
        my $curRes;
        my $found = 0;
        
        # We only need to do this if we need to open the maps to show the
        # current position. This will change the counter so we can't count
        # for the jump marker with this loop.
        while ($here && ($curRes = $mapIterator->next()) && !$found) {
            if (ref($curRes) && $curRes->symb() eq $here) {
                my $mapStack = $mapIterator->getStack();
                
                # Ensure the parent maps are open
                for my $map (@{$mapStack}) {
                    if ($condition) {
                        undef $filterHash->{$map->map_pc()};
                    } else {
                        $filterHash->{$map->map_pc()} = 1;
                    }
                }
                $found = 1;
            }
        }            
    }        

    if ( !defined($args->{'iterator'}) && $env{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
        # If this is a click on a folder or something, we want to preserve the "here"
        # from the querystring, and get the new "jump" marker
        $here = $env{'form.here'};
        $jump = $env{'form.jump'};
    } 
    
    my $it = $args->{'iterator'};
    if (!defined($it)) {
        # Construct a default iterator based on $env{'form.'} information
        
        # Step 1: Check to see if we have a navmap
        if (!defined($navmap)) {
            $navmap = Apache::lonnavmaps::navmap->new();
            if (!defined($navmap)) {
                # no longer in course
                return '<span class="LC_error">'.&mt('No course selected').'</span><br />
                        <a href="/adm/roles">'.&mt('Select a course').'</a><br />';
            }
        }

        # See if we're being passed a specific map
        if ($args->{'iterator_map'}) {
            my $map = $args->{'iterator_map'};
            $map = $navmap->getResourceByUrl($map);
            if (ref($map)) {
                my $firstResource = $map->map_start();
                my $finishResource = $map->map_finish();
                $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
            } else {
                return;
            }
        } else {
            $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition,undef,$args->{'include_top_level_map'});
        }
    }

    # (re-)Locate the jump point, if any
    # Note this does not take filtering or hidden into account... need
    # to be fixed?
    my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
    my $curRes;
    my $foundJump = 0;
    my $counter = 0;
    
    while (($curRes = $mapIterator->next()) && !$foundJump) {
        if (ref($curRes)) { $counter++; }
        
        if (ref($curRes) && $jump eq $curRes->symb()) {
            
            # This is why we have to use the main iterator instead of the
            # potentially faster DFS: The count has to be the same, so
            # the order has to be the same, which DFS won't give us.
            $args->{'currentJumpIndex'} = $counter;
            $foundJump = 1;
        }
    }

    my $showParts = setDefault($args->{'showParts'}, 1);
    my $condenseParts = setDefault($args->{'condenseParts'}, 1);
    # keeps track of when the current resource is found,
    # so we can back up a few and put the anchor above the
    # current resource
    my $printKey = $args->{'printKey'};
    my $printCloseAll = $args->{'printCloseAll'};
    if (!defined($printCloseAll)) { $printCloseAll = 1; }
   
    # Print key?
    if ($printKey) {
        $result .= '<table border="0" cellpadding="2" cellspacing="0">';
        $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
	my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc");
        if ($navmap->{LAST_CHECK}) {
            $result .= 
                '<img src="'.$location.'/chat.gif" alt="" /> '.&mt('New discussion since').' '.
                strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
                '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
                '<img src="'.$location.'/feedback.gif" alt="" /> '.&mt('New message (click to open)').'<p>'.
                '</td>'; 
        } else {
            $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
                '<img src="'.$location.'/chat.gif" alt="" /> '.&mt('Discussions').'</td><td align="center" valign="bottom">'.
                '&nbsp;&nbsp;<img src="'.$location.'/feedback.gif" alt="" /> '.&mt('New message (click to open)').
                '</td>'; 
        }

        $result .= '</tr></table>';
    }

    if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
	my ($link,$text);
        if ($condition) {
	    $link='navmaps?condition=0&amp;filter=&amp;'.$queryString.
		'&amp;here='.&escape($here);
	    $text='Close all folders';
        } else {
	    $link='navmaps?condition=1&amp;filter=&amp;'.$queryString.
		'&amp;here='.&escape($here);
	    $text='Open all folders';
        }
        if ($env{'form.register'}) {
            $link .= '&amp;register='.$env{'form.register'};
        }
	if ($args->{'caller'} eq 'navmapsdisplay') {
            unless ($args->{'notools'}) {
                &add_linkitem($args->{'linkitems'},'changefolder',
                              "location.href='$link'",$text);
            }
	} else {
	    $result.= '<a href="'.$link.'">'.&mt($text).'</a>';
	}
        $result .= "\n";
    }

    # Check for any unread discussions in all resources.
    if (($args->{'caller'} eq 'navmapsdisplay') && (!$args->{'notools'})) {
	&add_linkitem($args->{'linkitems'},'clearbubbles',
		      'document.clearbubbles.submit()',
		      'Mark all posts read');
	my $time=time;
        my $querystr = &HTML::Entities::encode($ENV{'QUERY_STRING'},'<>&"');
	$result .= (<<END);
    <form name="clearbubbles" method="post" action="/adm/feedback">
	<input type="hidden" name="navurl" value="$querystr" />
	<input type="hidden" name="navtime" value="$time" />
END
        if ($env{'form.register'}) {
            $result .= '<input type="hidden" name="register" value="'.$env{'form.register'}.'" />';
        }
        if ($args->{'sort'} eq 'discussion') { 
	    my $totdisc = 0;
	    my $haveDisc = '';
	    my @allres=$navmap->retrieveResources();
	    foreach my $resource (@allres) {
		if ($resource->hasDiscussion()) {
		    $haveDisc .= $resource->wrap_symb().':';
		    $totdisc ++;
		}
	    }
	    if ($totdisc > 0) {
		$haveDisc =~ s/:$//;
		$result .= (<<END);
	<input type="hidden" name="navmaps" value="$haveDisc" />
    </form>
END
            }
	}
	$result.='</form>';
    }
    if (($args->{'caller'} eq 'navmapsdisplay') &&
        ((&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) ||
         (&Apache::lonnet::allowed('cev',$env{'request.course.id'})))) {
        my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        if ($env{'course.'.$env{'request.course.id'}.'.url'} eq 
            "uploaded/$cdom/$cnum/default.sequence") {
            &add_linkitem($args->{'linkitems'},'edittoplevel',
                          "javascript:gocmd('/adm/coursedocs','editdocs');",
                          'Content Editor');
        }
    }

    if ($args->{'caller'} eq 'navmapsdisplay') {
        $result .= &show_linkitems_toolbar($args,$condition);
    } elsif ($args->{'sort_html'}) { 
        $result.=$args->{'sort_html'}; 
    }

    #$result .= "<br />\n";
    if ($r) {
        $r->print($result);
        $r->rflush();
        $result = "";
    }
    # End parameter setting
    
    $result .= "<br />\n";

    # Data
    $result.=&Apache::loncommon::start_data_table("LC_tableOfContent");    

    my $res = "Apache::lonnavmaps::resource";
    my %condenseStatuses =
        ( $res->NETWORK_FAILURE    => 1,
          $res->NOTHING_SET        => 1,
          $res->CORRECT            => 1 );

    # Shared variables
    $args->{'counter'} = 0; # counts the rows
    $args->{'indentLevel'} = 0;
    $args->{'isNewBranch'} = 0;
    $args->{'condensed'} = 0;   

    my $location = &Apache::loncommon::lonhttpdurl("/adm/lonIcons/whitespace_21.gif");
    $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='$location' alt='' />");
    $args->{'displayedHereMarker'} = 0;

    # If we're suppressing empty sequences, look for them here.
    # We also do this even if $args->{'suppressEmptySequences'}
    # is not true, so we can hide empty sequences for which the
    # hiddenresource parameter is set to yes (at map level), or
    # mark as hidden for users who have $userCanSeeHidden.  
    # Use DFS for speed, since structure actually doesn't matter,
    # except what map has what resources.

    my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
                                                     $it->{FIRST_RESOURCE},
                                                     $it->{FINISH_RESOURCE},
                                                     {}, undef, 1);
    my $depth = 0;
    $dfsit->next();
    my $curRes = $dfsit->next();
    while ($depth > -1) {
        if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
        if ($curRes == $dfsit->END_MAP()) { $depth--; }

        if (ref($curRes)) { 
            # Parallel pre-processing: Do sequences have non-filtered-out children?
            if ($curRes->is_map()) {
                $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
                # Sequences themselves do not count as visible children,
                # unless those sequences also have visible children.
                # This means if a sequence appears, there's a "promise"
                # that there's something under it if you open it, somewhere.
            } elsif ($curRes->src()) {
                # Not a sequence: if it's filtered, ignore it, otherwise
                # rise up the stack and mark the sequences as having children
                if (&$filterFunc($curRes)) {
                    for my $sequence (@{$dfsit->getStack()}) {
                        $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
                    }
                }
            }
        }
    } continue {
        $curRes = $dfsit->next();
    }

    my $displayedJumpMarker = 0;
    # Set up iteration.
    my $now = time();
    my $in24Hours = $now + 24 * 60 * 60;
    my $rownum = 0;

    # export "here" marker information
    $args->{'here'} = $here;

    $args->{'indentLevel'} = -1; # first BEGIN_MAP takes this to 0
    my @resources;
    my $code='';# sub { !(shift->is_map();) };
    if ($args->{'sort'} eq 'title') {
        my $oldFilterFunc = $filterFunc;
	my $filterFunc= 
	    sub {
		my ($res)=@_;
		if ($res->is_map()) { return 0;}
		return &$oldFilterFunc($res);
	    };
	@resources=$navmap->retrieveResources(undef,$filterFunc);
	@resources= sort { &cmp_title($a,$b) } @resources;
    } elsif ($args->{'sort'} eq 'duedate') {
	my $oldFilterFunc = $filterFunc;
	my $filterFunc= 
	    sub {
		my ($res)=@_;
		if (!$res->is_problem()) { return 0;}
		return &$oldFilterFunc($res);
	    };
	@resources=$navmap->retrieveResources(undef,$filterFunc);
	@resources= sort {
	    if ($a->duedate ne $b->duedate) {
	        return $a->duedate cmp $b->duedate;
	    }
	    my $value=&cmp_title($a,$b);
	    return $value;
	} @resources;
    } elsif ($args->{'sort'} eq 'discussion') {
	my $oldFilterFunc = $filterFunc;
	my $filterFunc= 
	    sub {
		my ($res)=@_;
		if (!$res->hasDiscussion() &&
		    !$res->getFeedback() &&
		    !$res->getErrors()) { return 0;}
		return &$oldFilterFunc($res);
	    };
	@resources=$navmap->retrieveResources(undef,$filterFunc);
	@resources= sort { &cmp_title($a,$b) } @resources;
    } else {
	#unknow sort mechanism or default
	undef($args->{'sort'});
    }

    # Determine if page will be served with https in case
    # it contains a syllabus which uses an external URL
    # which points at an http site.

    my ($is_ssl,$cdom,$cnum,$hostname);
    if ($ENV{'SERVER_PORT'} == 443) {
        $is_ssl = 1;
        if ($r) {
            $hostname = $r->hostname();
        } else {
            $hostname = $ENV{'SERVER_NAME'};
        }
    }
    if ($env{'request.course.id'}) {
        $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    }

    my $inhibitmenu;
    if ($args->{'modalLink'}) {
        $inhibitmenu = '&amp;inhibitmenu=yes';
    }

    while (1) {
	if ($args->{'sort'}) {
	    $curRes = shift(@resources);
	} else {
	    $curRes = $it->next($closeAllPages);
	}
	if (!$curRes) { last; }

        # Maintain indentation level.
        if ($curRes == $it->BEGIN_MAP() ||
            $curRes == $it->BEGIN_BRANCH() ) {
            $args->{'indentLevel'}++;
        }
        if ($curRes == $it->END_MAP() ||
            $curRes == $it->END_BRANCH() ) {
            $args->{'indentLevel'}--;
        }
        # Notice new branches
        if ($curRes == $it->BEGIN_BRANCH()) {
            $args->{'isNewBranch'} = 1;
        }

        # If this isn't an actual resource, continue on
        if (!ref($curRes)) {
            next;
        }

        # If this has been filtered out, continue on
        if (!(&$filterFunc($curRes))) {
            $args->{'isNewBranch'} = 0; # Don't falsely remember this
            next;
        } 

        # If this is an empty sequence and we're filtering them, continue on
        $args->{'mapHidden'} = 0;
        $args->{'mapUnlisted'} = 0;
        $args->{'mapHiddenDeepLink'} = 0;
        if (($curRes->is_map()) && (!$curRes->{DATA}->{HAS_VISIBLE_CHILDREN})) {
            if ($args->{'suppressEmptySequences'}) {
                next;
            } else {
                my $mapname = &Apache::lonnet::declutter($curRes->src());
                $mapname = &Apache::lonnet::deversion($mapname); 
                if (lc($navmap->get_mapparam(undef,$mapname,"0.hiddenresource")) eq 'yes') {
                    if ($userCanSeeHidden) {
                        $args->{'mapHidden'} = 1;
                    } else {
                        next;
                    }
                } elsif ($curRes->deeplinkout) {
                    if ($userCanSeeHidden) {
                        $args->{'mapHiddenDeepLink'} = 1;
                    } else {
                        next;
                    }
                } else {
                    my $deeplink = $navmap->get_mapparam(undef,$mapname,"0.deeplink");
                    my ($state,$others,$listed) = split(/,/,$deeplink);
                    if (($listed eq 'absent') || ($listed eq 'grades')) {
                        if ($userCanSeeHidden) {
                            $args->{'mapUnlisted'} = 1;
                        } else {
                            next;
                        }
                    }
                }
            }
        }

        # If we're suppressing navmaps and this is a navmap, continue on
        if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
            next;
        }

        $args->{'counter'}++;

        # Does it have multiple parts?
        $args->{'multipart'} = 0;
        $args->{'condensed'} = 0;
        my @parts;
            
        # Decide what parts to show.
        if ($curRes->is_problem() && $showParts) {
            @parts = @{$curRes->parts()};
            $args->{'multipart'} = $curRes->multipart();
            
            if ($condenseParts) { # do the condensation
                if (!$args->{'condensed'}) {
                    # Decide whether to condense based on similarity
                    my $status = $curRes->status($parts[0]);
                    my $due = $curRes->duedate($parts[0]);
                    my $open = $curRes->opendate($parts[0]);
                    my $statusAllSame = 1;
                    my $dueAllSame = 1;
                    my $openAllSame = 1;
                    for (my $i = 1; $i < scalar(@parts); $i++) {
                        if ($curRes->status($parts[$i]) != $status){
                            $statusAllSame = 0;
                        }
                        if ($curRes->duedate($parts[$i]) != $due ) {
                            $dueAllSame = 0;
                        }
                        if ($curRes->opendate($parts[$i]) != $open) {
                            $openAllSame = 0;
                        }
                    }
                    # $*allSame is true if all the statuses were
                    # the same. Now, if they are all the same and
                    # match one of the statuses to condense, or they
                    # are all open with the same due date, or they are
                    # all OPEN_LATER with the same open date, display the
                    # status of the first non-zero part (to get the 'correct'
                    # status right, since 0 is never 'correct' or 'open').
                    if (($statusAllSame && defined($condenseStatuses{$status})) ||
                        ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
                        ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
                        @parts = ($parts[0]);
                        $args->{'condensed'} = 1;
                    }
                }
		# Multipart problem with one part: always "condense" (happens
		#  to match the desirable behavior)
		if ($curRes->countParts() == 1) {
		    @parts = ($parts[0]);
		    $args->{'condensed'} = 1;
		}
            }
        }
        # If deep-link parameter is set (and is not set to full) suppress link
        # unless privileged user, tinyurl used for login resolved to a map, and
        # the resource is within the map.
        if ((!$curRes->deeplink($args->{'caller'})) ||
            ($curRes->deeplink($args->{'caller'}) eq 'full') || &advancedUser()) {
            $args->{'resource_nolink'} = 0;
        } else {
            $args->{'resource_nolink'} = 1;
        }

        # If the multipart problem was condensed, "forget" it was multipart
        if (scalar(@parts) == 1) {
            $args->{'multipart'} = 0;
        } else {
            # Add part 0 so we display it correctly.
            unshift @parts, '0';
        }
	
	{
	    my ($src,$symb,$anchor,$stack);
	    if ($args->{'sort'}) {
		my $it = $navmap->getIterator(undef, undef, undef, 1);
		while ( my $res=$it->next()) {
		    if (ref($res) &&
			$res->symb() eq  $curRes->symb()) { last; }
		}
		$stack=$it->getStack();
	    } else {
		$stack=$it->getStack();
	    }
	    ($src,$symb,$anchor)=getLinkForResource($stack);
            my $srcHasQuestion = $src =~ /\?/;
            if ($env{'request.course.id'}) {
                if (($is_ssl) && ($src =~ m{^\Q/public/$cdom/$cnum/syllabus\E($|\?)}) &&
                    ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
                    unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
                        if ($hostname ne '') {
                            $src = 'http://'.$hostname.$src;
                        }
                        $src .= ($srcHasQuestion? '&amp;' : '?') . 'usehttp=1';
                        $srcHasQuestion = 1;
                    }
                } elsif (($is_ssl) && ($src =~ m{^\Q/adm/wrapper/ext/\E(?!https:)})) {
                    unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
                        if ($hostname ne '') {
                            $src = 'http://'.$hostname.$src;
                        }
                        $src .= ($srcHasQuestion? '&amp;' : '?') . 'usehttp=1';
                        $srcHasQuestion = 1;
                    }
                }
            }
	    if (defined($anchor)) { $anchor='#'.$anchor; }
	    if (($args->{'caller'} eq 'sequence') && ($curRes->is_map())) {
	        $args->{"resourceLink"} = $src.($srcHasQuestion?'&amp;':'?') .'navmap=1';
	    } else {
	        $args->{"resourceLink"} = $src.
		    ($srcHasQuestion?'&amp;':'?') .
		    'symb=' . &escape($symb).$inhibitmenu.$anchor;
	    }
	}
        # Now, we've decided what parts to show. Loop through them and
        # show them.
        foreach my $part (@parts) {
            $rownum ++;
            
            $result .= &Apache::loncommon::start_data_table_row();

            # Set up some data about the parts that the cols might want
            my $filter = $it->{FILTER};

            # Now, display each column.
            foreach my $col (@$cols) {
                my $colHTML = '';
                if (ref($col)) {
                    $colHTML .= &$col($curRes, $part, $args);
                } else {
                    $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
                }

                # If this is the first column and it's time to print
                # the anchor, do so
                if ($col == $cols->[0] && 
                    $args->{'counter'} == $args->{'currentJumpIndex'} - 
                    $currentJumpDelta) {
                    # Jam the anchor after the <td> tag;
                    # necessary for valid HTML (which Mozilla requires)
                    $colHTML =~ s/\>/\>\<a name="curloc" \>\<\/a\>/;
                    $displayedJumpMarker = 1;
                }
                $result .= $colHTML . "\n";
            }
            $result .= &Apache::loncommon::end_data_table_row();
            $args->{'isNewBranch'} = 0;
        }

        if ($r && $rownum % 20 == 0) {
            $r->print($result);
            $result = "";
            $r->rflush();
        }
    } continue {
	if ($r) {
	    # If we have the connection, make sure the user is still connected
	    my $c = $r->connection;
	    if ($c->aborted()) {
		# Who cares what we do, nobody will see it anyhow.
		return '';
	    }
	}
    }

    $result.=&Apache::loncommon::end_data_table();
    
    # Print out the part that jumps to #curloc if it exists
    # delay needed because the browser is processing the jump before
    # it finishes rendering, so it goes to the wrong place!
    # onload might be better, but this routine has no access to that.
    # On mozilla, the 0-millisecond timeout seems to prevent this;
    # it's quite likely this might fix other browsers, too, and 
    # certainly won't hurt anything.
    if ($displayedJumpMarker) {
        $result .= &Apache::lonhtmlcommon::scripttag("
if (location.href.indexOf('#curloc')==-1) {
    setTimeout(\"location += '#curloc';\", 0)
}
");
    }

    if ($r) {
        $r->print($result);
        $result = "";
        $r->rflush();
    }
        
    return $result;
}

sub add_linkitem {
    my ($linkitems,$name,$cmd,$text)=@_;
    $$linkitems{$name}{'cmd'}=$cmd;
    $$linkitems{$name}{'text'}=&mt($text);
}

sub show_linkitems_toolbar {
    my ($args,$condition) = @_;
    my $result;
    if (ref($args) eq 'HASH') {
        if (ref($args->{'linkitems'}) eq 'HASH') {
            my $numlinks = scalar(keys(%{$args->{'linkitems'}}));
            if ($numlinks > 1) {
                $result = '<td>'.
                          &Apache::loncommon::help_open_menu('Navigation Screen','Navigation_Screen',
                                                             undef,'RAT').
                          '</td>'.
                          '<td>&nbsp;</td>'.
                          '<td class="LC_middle">'.&mt('Tools:').'</td>';
            }
            $result .= '<td align="left">'."\n".
                       '<ul id="LC_toolbar">';
            my @linkorder = ('firsthomework','everything','uncompleted',
                             'changefolder','clearbubbles','edittoplevel');
            foreach my $link (@linkorder) {
                if (ref($args->{'linkitems'}{$link}) eq 'HASH') {
                    if ($args->{'linkitems'}{$link}{'text'} ne '') {
                        $args->{'linkitems'}{$link}{'cmd'}=~s/"/'/g;
                        if ($args->{'linkitems'}{$link}{'cmd'}) {
                            my $link_id = 'LC_content_toolbar_'.$link;
                            if ($link eq 'changefolder') {
                                if ($condition) {
                                    $link_id='LC_content_toolbar_changefolder_toggled';
                                } else {
                                    $link_id='LC_content_toolbar_changefolder';
                                }
                            }
                            $result .= '<li><a href="#" '.
                                       'onclick="'.$args->{'linkitems'}{$link}{'cmd'}.'" '.
                                       'id="'.$link_id.'" '.
                                       'class="LC_toolbarItem" '.
                                       'title="'.$args->{'linkitems'}{$link}{'text'}.'">'.
                                       '</a></li>'."\n";
                        }
                    }
                }
            }
            $result .= '</ul>'.
                       '</td>';
            if (($numlinks==1) && (exists($args->{'linkitems'}{'edittoplevel'}))) {
                $result .= '<td><a href="'.$args->{'linkitems'}{'edittoplevel'}{'cmd'}.'">'.
                           &mt('Content Editor').'</a></td>';
            }
        }
        if ($args->{'sort_html'}) {
            $result .= '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
                       '<td align="right">'.$args->{'sort_html'}.'</td>';
        }
    }
    if ($result) {
        $result = "<table><tr>$result</tr></table>";
    }
    return $result;
}

1;









package Apache::lonnavmaps::navmap;

=pod

=head1 Object: Apache::lonnavmaps::navmap

=head2 Overview

The navmap object's job is to provide access to the resources
in the course as Apache::lonnavmaps::resource objects, and to
query and manage the relationship between those resource objects.

Generally, you'll use the navmap object in one of three basic ways.
In order of increasing complexity and power:

=over 4

=item * C<$navmap-E<gt>getByX>, where X is B<Id>, B<Symb> or B<MapPc> and getResourceByUrl. This provides
    various ways to obtain resource objects, based on various identifiers.
    Use this when you want to request information about one object or 
    a handful of resources you already know the identities of, from some
    other source. For more about Ids, Symbs, and MapPcs, see the
    Resource documentation. Note that Url should be a B<last resort>,
    not your first choice; it only really works when there is only one
    instance of the resource in the course, which only applies to
    maps, and even that may change in the future (see the B<getResourceByUrl>
    documentation for more details.)

=item * C<my @resources = $navmap-E<gt>retrieveResources(args)>. This
    retrieves resources matching some criterion and returns them
    in a flat array, with no structure information. Use this when
    you are manipulating a series of resources, based on what map
    the are in, but do not care about branching, or exactly how
    the maps and resources are related. This is the most common case.

=item * C<$it = $navmap-E<gt>getIterator(args)>. This allows you traverse
    the course's navmap in various ways without writing the traversal
    code yourself. See iterator documentation below. Use this when
    you need to know absolutely everything about the course, including
    branches and the precise relationship between maps and resources.

=back

=head2 Creation And Destruction

To create a navmap object, use the following function:

=over 4

=item * B<Apache::lonnavmaps::navmap-E<gt>new>():

Creates a new navmap object. Returns the navmap object if this is
successful, or B<undef> if not.

=back

=head2 Methods

=over 4

=item * B<getIterator>(first, finish, filter, condition):

See iterator documentation below.

=cut

use strict;
use GDBM_File;
use Apache::lonnet;
use LONCAPA;

sub new {
    # magic invocation to create a class instance
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};
    bless($self);		# So we can call change_user if necessary

    $self->{USERNAME} = shift || $env{'user.name'};
    $self->{DOMAIN}   = shift || $env{'user.domain'};
    $self->{CODE}     = shift;
    $self->{NOHIDE} = shift;



    # Resource cache stores navmap resources as we reference them. We generate
    # them on-demand so we don't pay for creating resources unless we use them.
    $self->{RESOURCE_CACHE} = {};

    # Network failure flag, if we accessed the course or user opt and
    # failed
    $self->{NETWORK_FAILURE} = 0;

    # We can only tie the nav hash as done below if the username/domain
    # match the env one. Otherwise change_user does everything we need...since we can't
    # assume there are course hashes for the specific requested user:domain
    # Note: change_user is also called if we need the nav hash when printing CODEd 
    # assignments or printing an exam, in which the enclosing folder for the items in
    # the exam has hidden set.
    #

    if (($self->{USERNAME} eq $env{'user.name'}) && ($self->{DOMAIN} eq $env{'user.domain'}) &&
         !$self->{CODE} && !$self->{NOHIDE}) {
	
	# tie the nav hash
	
	my %navmaphash;
	my %parmhash;
	my $courseFn = $env{"request.course.fn"};
	if (!(tie(%navmaphash, 'GDBM_File', "${courseFn}.db",
		  &GDBM_READER(), 0640))) {
	    return undef;
	}
	
	if (!(tie(%parmhash, 'GDBM_File', "${courseFn}_parms.db",
		  &GDBM_READER(), 0640)))
	{
	    untie %{$self->{PARM_HASH}};
	    return undef;
	}
	
	$self->{NAV_HASH} = \%navmaphash;
	$self->{PARM_HASH} = \%parmhash;
	$self->{PARM_CACHE} = {};
    } else {
	$self->change_user($self->{USERNAME}, $self->{DOMAIN},  $self->{CODE}, $self->{NOHIDE});
    }

    return $self;
}

#
#  In some instances it is useful to be able to dynamically change the
# username/domain associated with a navmap (e.g. to navigate for someone
# else besides the current user...if sufficiently privileged.
# Parameters:
#    user  - New user.
#    domain- Domain the user belongs to.
#    code  - Anonymous CODE in use.
# Implicit inputs:
#   
sub change_user {
    my $self = shift;
    $self->{USERNAME} = shift;
    $self->{DOMAIN}   = shift;
    $self->{CODE}     = shift;
    $self->{NOHIDE}   = shift;

    # If the hashes are already tied make sure to break that bond:

    untie %{$self->{NAV_HASH}}; 
    untie %{$self->{PARM_HASH}};

    # The assumption is that we have to
    # use lonmap here to re-read the hash and from it reconstruct
    # new big and parameter hashes.  An implicit assumption at this time
    # is that the course file is probably not created locally yet
    # an that we will therefore just read without tying.

    my ($cdom, $cnum) = split(/\_/, $env{'request.course.id'});

    my %big_hash;
    &Apache::lonmap::loadmap($cnum, $cdom, $self->{USERNAME}, $self->{DOMAIN}, $self->{CODE}, $self->{NOHIDE}, \%big_hash);
    $self->{NAV_HASH} = \%big_hash;



    # Now clear the parm cache and reconstruct the parm hash from the big_hash
    # param.xxxx keys.

    $self->{PARM_CACHE} = {};
    
    my %parm_hash = {};
    foreach my $key (keys(%big_hash)) {
	if ($key =~ /^param\./) {
	    my $param_key = $key;
	    $param_key =~ s/^param\.//;
	    $parm_hash{$param_key} = $big_hash{$key};
	}
    }

    $self->{PARM_HASH} = \%parm_hash;

}

sub generate_course_user_opt {
    my $self = shift;
    if ($self->{COURSE_USER_OPT_GENERATED}) { return; }

    my $uname=$self->{USERNAME};
    my $udom=$self->{DOMAIN};

    my $cid=$env{'request.course.id'};
    my $cdom=$env{'course.'.$cid.'.domain'};
    my $cnum=$env{'course.'.$cid.'.num'};
    
# ------------------------------------------------- Get coursedata (if present)
    my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
    # Check for network failure
    if (!ref($courseopt)) {
	if ( $courseopt =~ /no.such.host/i || $courseopt =~ /con_lost/i) {
	    $self->{NETWORK_FAILURE} = 1;
	}
	undef($courseopt);
    }

# --------------------------------------------------- Get userdata (if present)
	
    my $useropt=&Apache::lonnet::get_userresdata($uname,$udom);
    # Check for network failure
    if (!ref($useropt)) {
	if ( $useropt =~ /no.such.host/i || $useropt =~ /con_lost/i) {
	    $self->{NETWORK_FAILURE} = 1;
	}
	undef($useropt);
    }

    $self->{COURSE_OPT} = $courseopt;
    $self->{USER_OPT} = $useropt;

    $self->{COURSE_USER_OPT_GENERATED} = 1;
    
    return;
}



sub generate_email_discuss_status {
    my $self = shift;
    my $symb = shift;
    if ($self->{EMAIL_DISCUSS_GENERATED}) { return; }

    my $cid=$env{'request.course.id'};
    my $cdom=$env{'course.'.$cid.'.domain'};
    my $cnum=$env{'course.'.$cid.'.num'};
    
    my %emailstatus = &Apache::lonnet::dump('email_status',$self->{DOMAIN},$self->{USERNAME});
    my $logoutTime = $emailstatus{'logout'};
    my $courseLeaveTime = $emailstatus{'logout_'.$env{'request.course.id'}};
    $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
			   $courseLeaveTime : $logoutTime);
    my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
					       $cdom, $cnum);
    my %lastread = &Apache::lonnet::dump('nohist_'.$cid.'_discuss',
                                        $self->{DOMAIN},$self->{USERNAME},'lastread');
    my %lastreadtime = ();
    foreach my $key (keys(%lastread)) {
        my $shortkey = $key;
        $shortkey =~ s/_lastread$//;
        $lastreadtime{$shortkey} = $lastread{$key};
    }

    my %feedback=();
    my %error=();
    my @keys = &Apache::lonnet::getkeys('nohist_email',$self->{DOMAIN},
					$self->{USERNAME});
    
    foreach my $msgid (@keys) {
	if ((!$emailstatus{$msgid}) || ($emailstatus{$msgid} eq 'new')) {
            my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
                $symb,$error) = &Apache::lonmsg::unpackmsgid(&LONCAPA::escape($msgid));
            &Apache::lonenc::check_decrypt(\$symb); 
            if (($fromcid ne '') && ($fromcid ne $cid)) {
                next;
            }
            if (defined($symb)) {
                if (defined($error) && $error == 1) {
                    $error{$symb}.=','.$msgid;
                } else {
                    $feedback{$symb}.=','.$msgid;
                }
            } else {
                my $plain=
                    &LONCAPA::unescape(&LONCAPA::unescape($msgid));
                if ($plain=~/ \[([^\]]+)\]\:/) {
                    my $url=$1;
                    if ($plain=~/\:Error \[/) {
                        $error{$url}.=','.$msgid;
                    } else {
                        $feedback{$url}.=','.$msgid;
                    }
                }
            }
	}
    }
    
    #symbs of resources that have feedbacks (will be urls pre-2.3)
    $self->{FEEDBACK} = \%feedback;
    #or errors (will be urls pre 2.3)
    $self->{ERROR_MSG} = \%error;
    $self->{DISCUSSION_TIME} = \%discussiontime;
    $self->{EMAIL_STATUS} = \%emailstatus;
    $self->{LAST_READ} = \%lastreadtime;
    
    $self->{EMAIL_DISCUSS_GENERATED} = 1;
}

sub get_user_data {
    my $self = shift;
    if ($self->{RETRIEVED_USER_DATA}) { return; }

    # Retrieve performance data on problems
    my %student_data = Apache::lonnet::currentdump($env{'request.course.id'},
						   $self->{DOMAIN},
						   $self->{USERNAME});
    $self->{STUDENT_DATA} = \%student_data;

    $self->{RETRIEVED_USER_DATA} = 1;
}

sub get_discussion_data {
    my $self = shift;
    if ($self->{RETRIEVED_DISCUSSION_DATA}) {
	return $self->{DISCUSSION_DATA};
    }

    $self->generate_email_discuss_status();    

    my $cid=$env{'request.course.id'};
    my $cdom=$env{'course.'.$cid.'.domain'};
    my $cnum=$env{'course.'.$cid.'.num'};
    # Retrieve discussion data for resources in course
    my %discussion_data = &Apache::lonnet::dumpstore($cid,$cdom,$cnum);


    $self->{DISCUSSION_DATA} = \%discussion_data;
    $self->{RETRIEVED_DISCUSSION_DATA} = 1;
    return $self->{DISCUSSION_DATA};
}


# Internal function: Takes a key to look up in the nav hash and implements internal
# memory caching of that key.
sub navhash {
    my $self = shift; my $key = shift;
    return $self->{NAV_HASH}->{$key};
}

=pod

=item * B<courseMapDefined>(): Returns true if the course map is defined, 
    false otherwise. Undefined course maps indicate an error somewhere in
    LON-CAPA, and you will not be able to proceed with using the navmap.
    See the B<NAV> screen for an example of using this.

=cut

# Checks to see if coursemap is defined, matching test in old lonnavmaps
sub courseMapDefined {
    my $self = shift;
    my $uri = &Apache::lonnet::clutter($env{'request.course.uri'});

    my $firstres = $self->navhash("map_start_$uri");
    my $lastres = $self->navhash("map_finish_$uri");
    return $firstres && $lastres;
}

sub getIterator {
    my $self = shift;
    my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
                                                     shift, undef, shift,
						     shift, shift, shift);
    return $iterator;
}

# Private method: Does the given resource (as a symb string) have
# current discussion? Returns 0 if chat/mail data not extracted.
sub hasDiscussion {
    my $self = shift;
    my $symb = shift;
    $self->generate_email_discuss_status();

    if (!defined($self->{DISCUSSION_TIME})) { return 0; }

    #return defined($self->{DISCUSSION_TIME}->{$symb});

    # backward compatibility (bulletin boards used to be 'wrapped')
    my $ressymb = $self->wrap_symb($symb);
    if ( defined ( $self->{LAST_READ}->{$ressymb} ) ) {
        return $self->{DISCUSSION_TIME}->{$ressymb} > $self->{LAST_READ}->{$ressymb};
    } else {
#        return $self->{DISCUSSION_TIME}->{$ressymb} >  $self->{LAST_CHECK}; # v.1.1 behavior 
        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).
    }
}

sub last_post_time {
    my $self = shift;
    my $symb = shift;
    my $ressymb = $self->wrap_symb($symb);
    return $self->{DISCUSSION_TIME}->{$ressymb};
}

sub discussion_info {
    my $self = shift;
    my $symb = shift;
    my $filter = shift;

    $self->get_discussion_data();

    my $ressymb = $self->wrap_symb($symb);
    # keys used to store bulletinboard postings use 'unwrapped' symb. 
    my $discsymb = &escape($self->unwrap_symb($ressymb));
    my $version = $self->{DISCUSSION_DATA}{'version:'.$discsymb};
    if (!$version) { return; }

    my $prevread = $self->{LAST_READ}{$ressymb};

    my $count = 0;
    my $hiddenflag = 0;
    my $deletedflag = 0;
    my ($hidden,$deleted,%info);

    for (my $id=$version; $id>0; $id--) {
	my $vkeys=$self->{DISCUSSION_DATA}{$id.':keys:'.$discsymb};
	my @keys=split(/:/,$vkeys);
	if (grep(/^hidden$/ ,@keys)) {
	    if (!$hiddenflag) {
		$hidden = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':hidden'};
		$hiddenflag = 1;
	    }
	} elsif (grep(/^deleted$/,@keys)) {
	    if (!$deletedflag) {
		$deleted = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':deleted'};
		$deletedflag = 1;
	    }
	} else {
	    if (($hidden !~/\.$id\./) && ($deleted !~/\.$id\./)) {
                if ($filter eq 'unread') {
		    if ($prevread >= $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'}) {
                        next;
                    }
                }
		$count++;
		$info{$count}{'subject'} =
		    $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':subject'};
                $info{$count}{'id'} = $id;
                $info{$count}{'timestamp'} = $self->{DISCUSSION_DATA}{$id.':'.$discsymb.':timestamp'};
            }
	}
    }
    if (wantarray) {
	return ($count,%info);
    }
    return $count;
}

sub wrap_symb {
    my $self = shift;
    my $symb = shift;
    if ($symb =~ m-___(adm/[^/]+/[^/]+/)(\d+)(/bulletinboard)$-) {
        unless ($symb =~ m|adm/wrapper/adm|) {
            $symb = 'bulletin___'.$2.'___adm/wrapper/'.$1.$2.$3;
        }
    }
    return $symb;
}

sub unwrap_symb {
    my $self = shift;
    my $ressymb = shift;
    my $discsymb = $ressymb;
    if ($ressymb =~ m-^(bulletin___\d+___)adm/wrapper/(adm/[^/]+/[^/]+/\d+/bulletinboard)$-) {
         $discsymb = $1.$2;
    }
    return $discsymb;
}

# Private method: Does the given resource (as a symb string) have
# current feedback? Returns the string in the feedback hash, which
# will be false if it does not exist.

sub getFeedback { 
    my $self = shift;
    my $symb = shift;
    my $source = shift;

    $self->generate_email_discuss_status();

    if (!defined($self->{FEEDBACK})) { return ""; }
    
    my $feedback;
    if ($self->{FEEDBACK}->{$symb}) {
        $feedback = $self->{FEEDBACK}->{$symb};
        if ($self->{FEEDBACK}->{$source}) {
            $feedback .= ','.$self->{FEEDBACK}->{$source};
        }
    } else {
        if ($self->{FEEDBACK}->{$source}) {
            $feedback = $self->{FEEDBACK}->{$source};
        }
    }
    return $feedback;
}

# Private method: Get the errors for that resource (by source).
sub getErrors { 
    my $self = shift;
    my $symb = shift;
    my $src = shift;

    $self->generate_email_discuss_status();

    if (!defined($self->{ERROR_MSG})) { return ""; }

    my $errors;
    if ($self->{ERROR_MSG}->{$symb}) {
        $errors = $self->{ERROR_MSG}->{$symb};
        if ($self->{ERROR_MSG}->{$src}) {
            $errors .= ','.$self->{ERROR_MSG}->{$src};
        }
    } else {
        if ($self->{ERROR_MSG}->{$src}) {
            $errors = $self->{ERROR_MSG}->{$src};
        }
    }
    return $errors;
}

=pod

=item * B<getById>(id):

Based on the ID of the resource (1.1, 3.2, etc.), get a resource
object for that resource. This method, or other methods that use it
(as in the resource object) is the only proper way to obtain a
resource object.

=item * B<getBySymb>(symb):

Based on the symb of the resource, get a resource object for that
resource. This is one of the proper ways to get a resource object.

=item * B<getByMapPc>(map_pc):

Based on the map_pc of the resource, get a resource object for
the given map. This is one of the proper ways to get a resource object.

=cut

# The strategy here is to cache the resource objects, and only construct them
# as we use them. The real point is to prevent reading any more from the tied
# hash than we have to, which should hopefully alleviate speed problems.

sub getById {
    my $self = shift;
    my $id = shift;

    if (defined ($self->{RESOURCE_CACHE}->{$id}))
    {
        return $self->{RESOURCE_CACHE}->{$id};
    }

    # resource handles inserting itself into cache.
    # Not clear why the quotes are necessary, but as of this
    # writing it doesn't work without them.
    return "Apache::lonnavmaps::resource"->new($self, $id);
}

sub getBySymb {
    my $self = shift;
    my $symb = shift;

    my ($mapUrl, $id, $filename) = &Apache::lonnet::decode_symb($symb);
    my $map = $self->getResourceByUrl($mapUrl);
    my $returnvalue = undef;
    if (ref($map)) {
        $returnvalue = $self->getById($map->map_pc() .'.'.$id);
    }
    return $returnvalue;
}

sub getByMapPc {
    my $self = shift;
    my $map_pc = shift;
    my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
    $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
    return $self->getById($map_id);
}

=pod

=item * B<firstResource>():

Returns a resource object reference corresponding to the first
resource in the navmap.

=cut

sub firstResource {
    my $self = shift;
    my $firstResource = $self->navhash('map_start_' .
                     &Apache::lonnet::clutter($env{'request.course.uri'}));
    return $self->getById($firstResource);
}

=pod

=item * B<finishResource>():

Returns a resource object reference corresponding to the last resource
in the navmap.

=cut

sub finishResource {
    my $self = shift;
    my $firstResource = $self->navhash('map_finish_' .
                     &Apache::lonnet::clutter($env{'request.course.uri'}));
    return $self->getById($firstResource);
}

# Parmval reads the parm hash and cascades the lookups. parmval_real does
# the actual lookup; parmval caches the results.
sub parmval {
    my $self = shift;
    my ($what,$symb,$recurse)=@_;
    my $hashkey = $what."|||".$symb;
    my $cache = $self->{PARM_CACHE};
    if (defined($self->{PARM_CACHE}->{$hashkey})) {
        if (ref($self->{PARM_CACHE}->{$hashkey}) eq 'ARRAY') { 
            if (defined($self->{PARM_CACHE}->{$hashkey}->[0])) {
                if (wantarray) {
                    return @{$self->{PARM_CACHE}->{$hashkey}};
                } else {
                    return $self->{PARM_CACHE}->{$hashkey}->[0];
                }
            }
        } else {
            return $self->{PARM_CACHE}->{$hashkey};
        }
    }

    my $result = $self->parmval_real($what, $symb, $recurse);
    $self->{PARM_CACHE}->{$hashkey} = $result;
    if (wantarray) {
        return @{$result};
    }
    return $result->[0];
}


sub parmval_real {
    my $self = shift;
    my ($what,$symb,$recurse) = @_;


    # Make sure the {USER_OPT} and {COURSE_OPT} hashes are populated
    $self->generate_course_user_opt();

    my $cid=$env{'request.course.id'};
    my $csec=$env{'request.course.sec'};
    my $cgroup='';
    my @cgrps=split(/:/,$env{'request.course.groups'});
    if (@cgrps > 0) {
        @cgrps = sort(@cgrps);
        $cgroup = $cgrps[0];
    } 
    my $uname=$self->{USERNAME};
    my $udom=$self->{DOMAIN};

    unless ($symb) { return ['']; }
    my $result='';

    my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
    $mapname = &Apache::lonnet::deversion($mapname);
    my $toolsymb = '';
    if ($fn =~ /ext\.tool$/) {
        $toolsymb = $symb;
    }
    my ($recursed,@recurseup); 
    
# ----------------------------------------------------- Cascading lookup scheme
    my $rwhat=$what;
    $what=~s/^parameter\_//;
    $what=~s/\_/\./;

    my $symbparm=$symb.'.'.$what;
    my $recurseparm=$mapname.'___(rec).'.$what;
    my $mapparm=$mapname.'___(all).'.$what;
    my $usercourseprefix=$cid;
    


    my $grplevel=$usercourseprefix.'.['.$cgroup.'].'.$what;
    my $grplevelr=$usercourseprefix.'.['.$cgroup.'].'.$symbparm;
    my $grpleveli=$usercourseprefix.'.['.$cgroup.'].'.$recurseparm;
    my $grplevelm=$usercourseprefix.'.['.$cgroup.'].'.$mapparm;


    my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
    my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
    my $secleveli=$usercourseprefix.'.['.$csec.'].'.$recurseparm;
    my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;


    my $courselevel= $usercourseprefix.'.'.$what;
    my $courselevelr=$usercourseprefix.'.'.$symbparm;
    my $courseleveli=$usercourseprefix.'.'.$recurseparm;
    my $courselevelm=$usercourseprefix.'.'.$mapparm;


    my $useropt = $self->{USER_OPT};
    my $courseopt = $self->{COURSE_OPT};
    my $parmhash = $self->{PARM_HASH};

# ---------------------------------------------------------- first, check user
    if ($uname and defined($useropt)) {
        if (defined($$useropt{$courselevelr})) { return [$$useropt{$courselevelr},'resource']; }
        if (defined($$useropt{$courselevelm})) { return [$$useropt{$courselevelm},'map']; }
        if (defined($$useropt{$courseleveli})) { return [$$useropt{$courseleveli},'map']; }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
            if (defined($$useropt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return [$$useropt{$norecursechk},'map'];
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
            if (defined($$useropt{$recursechk})) { return [$$useropt{$recursechk},'map']; } 
        }
        if (defined($$useropt{$courselevel})) { return [$$useropt{$courselevel},'course']; }
    }

# ------------------------------------------------------- second, check course
    if ($cgroup ne '' and defined($courseopt)) {
        if (defined($$courseopt{$grplevelr})) { return [$$courseopt{$grplevelr},'resource']; }
        if (defined($$courseopt{$grplevelm})) { return [$$courseopt{$grplevelm},'map']; }
        if (defined($$courseopt{$grpleveli})) { return [$$courseopt{$grpleveli},'map']; } 
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(all).'.$what;
            if (defined($$courseopt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return [$$courseopt{$norecursechk},'map'];
                } else {
                   last;
                }
            }
            my $recursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(rec).'.$what;
            if (defined($$courseopt{$recursechk})) { return [$$courseopt{$recursechk},'map']; }      
        }
        if (defined($$courseopt{$grplevel})) { return [$$courseopt{$grplevel},'course']; }
    }

    if ($csec ne '' and defined($courseopt)) {
        if (defined($$courseopt{$seclevelr})) { return [$$courseopt{$seclevelr},'resource']; }
        if (defined($$courseopt{$seclevelm})) { return [$$courseopt{$seclevelm},'map']; }
        if (defined($$courseopt{$secleveli})) { return [$$courseopt{$secleveli},'map']; } 
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(all).'.$what;
            if (defined($$courseopt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return [$$courseopt{$norecursechk},'map'];
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(rec).'.$what;
            if (defined($$courseopt{$recursechk})) { return [$$courseopt{$recursechk},'map']; }
        }
        if (defined($$courseopt{$seclevel})) { return [$$courseopt{$seclevel},'course']; }
    }

    if (defined($courseopt)) {
        if (defined($$courseopt{$courselevelr})) { return [$$courseopt{$courselevelr},'resource']; }
    }

# ----------------------------------------------------- third, check map parms

    my $thisparm=$$parmhash{$symbparm};
    if (defined($thisparm)) { return [$thisparm,'map']; }

# ----------------------------------------------------- fourth , check default

    my $meta_rwhat=$rwhat;
    $meta_rwhat=~s/\./_/g;
    my $default=&Apache::lonnet::metadata($fn,$meta_rwhat,$toolsymb);
    if (defined($default)) { return [$default,'resource']}
    $default=&Apache::lonnet::metadata($fn,'parameter_'.$meta_rwhat,$toolsymb);
    if (defined($default)) { return [$default,'resource']}
# --------------------------------------------------- fifth, check more course
    if (defined($courseopt)) {
        if (defined($$courseopt{$courselevelm})) { return [$$courseopt{$courselevelm},'map']; }
        if (defined($$courseopt{$courseleveli})) { return [$$courseopt{$courseleveli},'map']; }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
            if (defined($$courseopt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return [$$courseopt{$norecursechk},'map'];
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
            if (defined($$courseopt{$recursechk})) {
                return [$$courseopt{$recursechk},'map'];
            }
        }
        if (defined($$courseopt{$courselevel})) {
           my $ret = [$$courseopt{$courselevel},'course'];
           return $ret;
       }
    }
# --------------------------------------------------- sixth , cascade up parts

    my ($space,@qualifier)=split(/\./,$rwhat);
    my $qualifier=join('.',@qualifier);
    unless ($space eq '0') {
	my @parts=split(/_/,$space);
	my $id=pop(@parts);
	my $part=join('_',@parts);
	if ($part eq '') { $part='0'; }
       my @partgeneral=$self->parmval($part.".$qualifier",$symb,1);
       if (defined($partgeneral[0])) { return \@partgeneral; }
    }
    if ($recurse) { return []; }
    my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$rwhat,$toolsymb);
    if (defined($pack_def)) { return [$pack_def,'resource']; }
    return [''];
}

sub recurseup_maps {
    my ($self,$mapname) = @_;
    my @recurseup;
    if ($mapname) {
        my $res = $self->getResourceByUrl($mapname);
        if (ref($res)) {
            my @pcs = split(/,/,$res->map_hierarchy());
            shift(@pcs);
            if (@pcs) {
                @recurseup = map { &Apache::lonnet::declutter($self->getByMapPc($_)->src()); } reverse(@pcs);
            }
        }
    }
    return @recurseup;
}

sub recursed_crumbs {
    my ($self,$mapurl,$restitle) = @_;
    my (@revmapinfo,@revmapres);
    my $mapres = $self->getResourceByUrl($mapurl);
    if (ref($mapres)) {
        @revmapres = map { $self->getByMapPc($_); } split(/,/,$mapres->map_breadcrumbs());
        shift(@revmapres);
    }
    my $allowedlength = 60;
    my $minlength = 5;
    my $allowedtitle = 30;
    if (($env{'environment.icons'} eq 'iconsonly') && (!$env{'browser.mobile'})) {
        $allowedlength = 100;
        $allowedtitle = 70;
    }
    if (length($restitle) > $allowedtitle) {
        $restitle = &truncate_crumb_text($restitle,$allowedtitle);
    }
    my $totallength = length($restitle);
    my @links;

    foreach my $map (@revmapres) {
        my $pc = $map->map_pc();
        next if ((!$pc) || ($pc == 1));
        push(@links,$map);
        push(@revmapinfo,{'href' => $env{'request.use_absolute'}.$map->link().'?navmap=1','text' => $map->title(),'no_mt' => 1,});
        $totallength += length($map->title());
    }
    my $numlinks = scalar(@links);
    if ($numlinks) {
        if ($totallength - $allowedlength > 0) {
            my $available = $allowedlength - length($restitle);
            my $avg = POSIX::ceil($available/$numlinks);
            if ($avg < $minlength) {
                $avg = $minlength;
            }
            @revmapinfo = ();
            foreach my $map (@links) {
                my $showntitle = &truncate_crumb_text($map->title(),$avg);
                if ($showntitle ne '') {
                    push(@revmapinfo,{'href' => $env{'request.use_absolute'}.$map->link().'?navmap=1','text' => $showntitle,'no_mt' => 1,});
                }
            }
        }
    }
    if ($restitle ne '') {
        push(@revmapinfo,{'text' => $restitle, 'no_mt' => 1});
    }
    return @revmapinfo;
}

sub truncate_crumb_text {
    my ($title,$limit) = @_;
    my $showntitle = '';
    if (length($title) > $limit) {
        my @words = split(/\b\s*/,$title);
        if (@words == 1) {
            $showntitle = substr($title,0,$limit).' ...';
        } else {
            my $linklength = 0;
            my $num = 0;
            foreach my $word (@words) {
                $linklength += 1+length($word);
                if ($word eq '-') {
                    $showntitle =~ s/ $//;
                    $showntitle .= $word;
                } elsif ($linklength > $limit) {
                    if ($num < @words) {
                        $showntitle .= $word.' ...';
                        last;
                    } else {
                        $showntitle .= $word;
                    }
                } else {
                    $showntitle .= $word.' ';
                }
            }
            $showntitle =~ s/ $//;
        }
        return $showntitle;
    } else {
        return $title;
    }
}

#
#  Determines the open/close dates for printing a map that
#  encloses a resource.
#
sub map_printdates {
    my ($self, $res, $part) = @_;





    my $opendate = $self->get_mapparam($res->symb(),'',"$part.printstartdate");
    my $closedate= $self->get_mapparam($res->symb(),'',"$part.printenddate");


    return ($opendate, $closedate);
}

sub get_mapparam {
    my ($self, $symb, $mapname, $what) = @_;

    # Ensure the course option hash is populated:

    $self->generate_course_user_opt();

    # Get the course id and section if there is one.

    my $cid=$env{'request.course.id'};
    my $csec=$env{'request.course.sec'};
    my $cgroup='';
    my @cgrps=split(/:/,$env{'request.course.groups'});
    if (@cgrps > 0) {
        @cgrps = sort(@cgrps);
        $cgroup = $cgrps[0];
    } 
    my $uname=$self->{USERNAME};
    my $udom=$self->{DOMAIN};

    unless ($symb || $mapname) { return; }
    my $result='';
    my ($recursed,@recurseup);


    # Figure out which map we are in.

    if ($symb && !$mapname) {
        my ($id,$fn);
        ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
        $mapname = &Apache::lonnet::deversion($mapname);
    }


    my $rwhat=$what;
    $what=~s/^parameter\_//;
    $what=~s/\_/\./;

    # Build the hash keys for the lookup:

    my $mapparm=$mapname.'___(all).'.$what;
    my $recurseparm=$mapname.'___(rec).'.$what; 
    my $usercourseprefix=$cid;


    my $grplevelm    = "$usercourseprefix.[$cgroup].$mapparm";
    my $seclevelm    = "$usercourseprefix.[$csec].$mapparm";
    my $courselevelm = "$usercourseprefix.$mapparm";

    my $grpleveli    = "$usercourseprefix.[$cgroup].$recurseparm";
    my $secleveli    = "$usercourseprefix.[$csec].$recurseparm";
    my $courseleveli = "$usercourseprefix.$recurseparm";

    # Get handy references to the hashes we need in $self:

    my $useropt = $self->{USER_OPT};
    my $courseopt = $self->{COURSE_OPT};
    my $parmhash = $self->{PARM_HASH};

    # Check per user 



    if ($uname and defined($useropt)) {
	if (defined($$useropt{$courselevelm})) {
	    return $$useropt{$courselevelm};
	}
        if (defined($$useropt{$courseleveli})) {
            return $$useropt{$courseleveli};
        }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
            if (defined($$useropt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return $$useropt{$norecursechk};
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
            if (defined($$useropt{$recursechk})) {
                return $$useropt{$recursechk};
            }
        }
    }

    # Check course -- group



    if ($cgroup ne '' and defined ($courseopt)) {
	if (defined($$courseopt{$grplevelm})) {
	    return $$courseopt{$grplevelm};
	}
        if (defined($$courseopt{$grpleveli})) {
            return $$courseopt{$grpleveli};
        }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(all).'.$what;
            if (defined($$courseopt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return $$courseopt{$norecursechk};
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.['.$cgroup.'].'.$item.'___(rec).'.$what;
            if (defined($$courseopt{$recursechk})) {
                return $$courseopt{$recursechk};
            }
        }
    }

    # Check course -- section


    if ($csec ne '' and defined($courseopt)) {
	if (defined($$courseopt{$seclevelm})) {
	    return $$courseopt{$seclevelm};
	}
        if (defined($$courseopt{$secleveli})) {
            return $$courseopt{$secleveli};
        }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        foreach my $item (@recurseup) {
            my $norecursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(all).'.$what;
            if (defined($$courseopt{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    return $$courseopt{$norecursechk};
                } else {
                    last;
                }
            }
            my $recursechk=$usercourseprefix.'.['.$csec.'].'.$item.'___(rec).'.$what;
            if (defined($$courseopt{$recursechk})) {
                return $$courseopt{$recursechk};
            }
        }
    }
    # Check the map parameters themselves:

    if ($symb) {
        my $symbparm=$symb.'.'.$what;
        my $thisparm = $$parmhash{$symbparm};
        if (defined($thisparm)) {
	    return $thisparm;
        }
    }


    # Additional course parameters:

    if (defined($courseopt)) {
	if (defined($$courseopt{$courselevelm})) {
	    return $$courseopt{$courselevelm};
	}
        if (defined($$courseopt{$courseleveli})) {
            return $$courseopt{$courseleveli};
        }
        unless ($recursed) {
            @recurseup = $self->recurseup_maps($mapname);
            $recursed = 1;
        }
        if (@recurseup) {
            foreach my $item (@recurseup) {
                my $norecursechk=$usercourseprefix.'.'.$item.'___(all).'.$what;
                if (defined($$courseopt{$norecursechk})) {
                    if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                        return $$courseopt{$norecursechk};
                    } else {
                        last;
                    }
                }
                my $recursechk=$usercourseprefix.'.'.$item.'___(rec).'.$what;
                if (defined($$courseopt{$recursechk})) {
                    return $$courseopt{$recursechk};
                }
            }
        }
    }
    return undef;		# Undefined if we got here.
}

sub course_printdates {
    my ($self, $symb,  $part) = @_;


    my $opendate  = $self->getcourseparam($symb, $part . '.printstartdate');
    my $closedate = $self->getcourseparam($symb, $part . '.printenddate');
    return ($opendate, $closedate);

}

sub getcourseparam {
    my ($self, $symb, $what) = @_;

    $self->generate_course_user_opt(); # If necessary populate the hashes.

    my $uname = $self->{USERNAME};
    my $udom  = $self->{DOMAIN};
    
    # Course, section, group ids come from the env:

    my $cid   = $env{'request.course.id'};
    my $csec  = $env{'request.course.sec'};
    my $cgroup = '';		# Assume no group

    my @cgroups = split(/:/, $env{'request.course.groups'});
    if(@cgroups > 0) {
	@cgroups = sort(@cgroups);
	$cgroup  = $cgroups[0];	# There is a course group. 
   }
    my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
    $mapname = &Apache::lonnet::deversion($mapname);

    #
    # Make the various lookup keys:
    #

    $what=~s/^parameter\_//;
    $what=~s/\_/\./;

    # Local refs to the hashes we're going to look at:

    my $useropt   = $self->{USER_OPT};
    my $courseopt = $self->{COURSE_OPT};

    # 
    # We want the course level stuff from the way
    # parmval_real operates 
    # TODO: Factor some of this stuff out of
    # both parmval_real and here
    #
    my $courselevel = $cid . '.' .  $what;
    my $grplevel    = $cid . '.[' . $cgroup   . ']' . $what;
    my $seclevel    = $cid . '.[' . $csec     . ']' . $what;


    # Try for the user's course level option:

    if ($uname and defined($useropt)) {
	if (defined($$useropt{$courselevel})) {
	    return $$useropt{$courselevel};
	}
    }
    # Try for the group's course level option:

    if ($cgroup ne '' and defined($courseopt)) {
	if (defined($$courseopt{$grplevel})) {
	    return $$courseopt{$grplevel};
	}
    }

    #  Try for section level parameters:

    if ($csec ne '' and defined($courseopt)) {
	if (defined($$courseopt{$seclevel})) {
	    return $$courseopt{$seclevel};
	}
    }
    # Try for 'additional' course parameters:

    if (defined($courseopt)) {
	if (defined($$courseopt{$courselevel})) {
	    return $$courseopt{$courselevel};
	}
    }
    return undef;

}


=pod

=item * B<getResourceByUrl>(url,multiple):

Retrieves a resource object by URL of the resource, unless the optional
multiple parameter is included in which case an array of resource 
objects is returned. If passed a resource object, it will simply return  
it, so it is safe to use this method in code like
"$res = $navmap->getResourceByUrl($res)"
if you're not sure if $res is already an object, or just a URL. If the
resource appears multiple times in the course, only the first instance 
will be returned (useful for maps), unless the multiple parameter has
been included, in which case all instances are returned in an array.

=item * B<retrieveResources>(map, filterFunc, recursive, bailout, showall, noblockcheck):

The map is a specification of a map to retreive the resources from,
either as a url or as an object. The filterFunc is a reference to a
function that takes a resource object as its one argument and returns
true if the resource should be included, or false if it should not
be. If recursive is true, the map will be recursively examined,
otherwise it will not be. If bailout is true, the function will return
as soon as it finds a resource, if false it will finish. If showall is
true it will not hide maps that contain nothing but one other map. The 
noblockcheck arg is propagated to become the sixth arg in the call to
lonnet::allowed when checking a resource's availability during collection
of resources using the iterator. noblockcheck needs to be true if 
retrieveResources() was called by a routine that itself was called by 
lonnet::allowed, in order to avoid recursion.  By default the map  
is the top-level map of the course, filterFunc is a function that 
always returns 1, recursive is true, bailout is false, showall is
false. The resources will be returned in a list containing the
resource objects for the corresponding resources, with B<no structure 
information> in the list; regardless of branching, recursion, etc.,
it will be a flat list.

Thus, this is suitable for cases where you don't want the structure,
just a list of all resources. It is also suitable for finding out how
many resources match a given description; for this use, if all you
want to know is if I<any> resources match the description, the bailout
parameter will allow you to avoid potentially expensive enumeration of
all matching resources.

=item * B<hasResource>(map, filterFunc, recursive, showall):

Convenience method for

 scalar(retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0

which will tell whether the map has resources matching the description
in the filter function.

=item * B<usedVersion>(url):

Retrieves version infomation for a url. Returns the version (a number, or 
the string "mostrecent") for resources which have version information in  
the big hash.

=cut


sub getResourceByUrl {
    my $self = shift;
    my $resUrl = shift;
    my $multiple = shift;

    if (ref($resUrl)) { return $resUrl; }

    $resUrl = &Apache::lonnet::clutter($resUrl);
    my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
    if (!$resId) { return ''; }
    if ($multiple) {
        my @resources = ();
        my @resIds = split (/,/, $resId);
        foreach my $id (@resIds) {
            my $resourceId = $self->getById($id);
            if ($resourceId) { 
                push(@resources,$resourceId);
            }
        }
        return @resources;
    } else {
        if ($resId =~ /,/) {
            $resId = (split (/,/, $resId))[0];
        }
        return $self->getById($resId);
    }
}

sub retrieveResources {
    my $self = shift;
    my $map = shift;
    my $filterFunc = shift;
    if (!defined ($filterFunc)) {
        $filterFunc = sub {return 1;};
    }
    my $recursive = shift;
    if (!defined($recursive)) { $recursive = 1; }
    my $bailout = shift;
    if (!defined($bailout)) { $bailout = 0; }
    my $showall = shift;
    my $noblockcheck = shift;
    # Create the necessary iterator.
    if (!ref($map)) { # assume it's a url of a map.
        $map = $self->getResourceByUrl($map);
    }

    # If nothing was passed, assume top-level map
    if (!$map) {
	$map = $self->getById('0.0');
    }

    # Check the map's validity.
    if (!$map->is_map()) {
        # Oh, to throw an exception.... how I'd love that!
        return ();
    }

    # Get an iterator.
    my $it = $self->getIterator($map->map_start(), $map->map_finish(),
                                undef, $recursive, $showall);

    my @resources = ();

    if (&$filterFunc($map)) {
	push(@resources, $map);
    }

    # Run down the iterator and collect the resources.
    my $curRes;

    while ($curRes = $it->next(undef,$noblockcheck)) {
        if (ref($curRes)) {
            if (!&$filterFunc($curRes)) {
                next;
            }

            push(@resources, $curRes);

            if ($bailout) {
                return @resources;
            }
        }

    }

    return @resources;
}

sub hasResource {
    my $self = shift;
    my $map = shift;
    my $filterFunc = shift;
    my $recursive = shift;
    my $showall = shift;
    
    return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1, $showall)) > 0;
}

sub usedVersion {
    my $self = shift;
    my $linkurl = shift;
    return $self->navhash("version_$linkurl");
}

sub isFirstResource {
    my $self = shift;
    my $map = shift;
    my $symb = shift;
    return unless (ref($map));
    my $isfirst;
    my $firstResource = $map->map_start();
    if (ref($firstResource)) {
        if ((!$firstResource->is_map()) && ($firstResource->src() ne ''))  {
            if ($firstResource->symb() eq $symb) {
                $isfirst = 1;
            } else {
                $isfirst = 0;
            }
        } else {
            my $it = $self->getIterator($firstResource,undef,undef,1);
            while ( my $res=$it->next()) {
                if ((ref($res)) && ($res->src() ne '') && (!$res->is_map())) {
                    if ($res->symb() eq $symb) {
                        $isfirst = 1;
                    } else {
                        $isfirst = 0;
                    }
                    last;
                }
            }
        }
    }
    return $isfirst;
}

sub isLastResource {
    my $self = shift;
    my $map = shift;
    my $symb = shift;
    return unless (ref($map));
    my $islast;
    my $lastResource = $map->map_finish();
    if (ref($lastResource)) {
        if ((!$lastResource->is_map()) && ($lastResource->src() ne ''))  {
            if ($lastResource->symb() eq $symb) {
                $islast = 1;
            } else {
                $islast = 0;
            }
        } else {
            my $currRes = $self->getBySymb($symb);
            if (ref($currRes)) {
                my $it = $self->getIterator($currRes,undef,undef,1);
                while ( my $res=$it->next()) {
                    if ((ref($res)) && ($res->src() ne '') && (!$res->is_map())) {
                        if ($res->symb() eq $symb) {
                            $islast = 1;
                        } else {
                            $islast = 0;
                        }
                        last;
                    }
                }
            }
        }
    }
    return $islast;
}

1;

package Apache::lonnavmaps::iterator;
use Scalar::Util qw(weaken);
use Apache::lonnet;

=pod

=back

=head1 Object: navmap Iterator

An I<iterator> encapsulates the logic required to traverse a data
structure. navmap uses an iterator to traverse the course map
according to the criteria you wish to use.

To obtain an iterator, call the B<getIterator>() function of a
B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
directly.) This will return a reference to the iterator:

C<my $resourceIterator = $navmap-E<gt>getIterator();>

To get the next thing from the iterator, call B<next>:

C<my $nextThing = $resourceIterator-E<gt>next()>

getIterator behaves as follows:

=over 4

=item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap, $deeplinklisted):

All parameters are optional. firstResource is a resource reference
corresponding to where the iterator should start. It defaults to
navmap->firstResource() for the corresponding nav map. finishResource
corresponds to where you want the iterator to end, defaulting to
navmap->finishResource(). filterHash is a hash used as a set
containing strings representing the resource IDs, defaulting to
empty. Condition is a 1 or 0 that sets what to do with the filter
hash: If a 0, then only resources that exist IN the filterHash will be
recursed on. If it is a 1, only resources NOT in the filterHash will
be recursed on. Defaults to 0. forceTop is a boolean value. If it is
false (default), the iterator will only return the first level of map
that is not just a single, 'redirecting' map. If true, the iterator
will return all information, starting with the top-level map,
regardless of content. returnTopMap, if true (default false), will
cause the iterator to return the top-level map object (resource 0.0)
before anything else. deeplinklisted if true (default false), will
check "listed" status of a resource with a deeplink, and unless "absent"
will exclude deeplink checking when retrieving the browsePriv from
lonnet::allowed().

Thus, by default, only top-level resources will be shown. Change the
condition to a 1 without changing the hash, and all resources will be
shown. Changing the condition to 1 and including some values in the
hash will allow you to selectively suppress parts of the navmap, while
leaving it on 0 and adding things to the hash will allow you to
selectively add parts of the nav map. See the handler code for
examples.

The iterator will return either a reference to a resource object, or a
token representing something in the map, such as the beginning of a
new branch. The possible tokens are:

=over 4

=item * B<END_ITERATOR>:

The iterator has returned all that it's going to. Further calls to the
iterator will just produce more of these. This is a "false" value, and
is the only false value the iterator which will be returned, so it can
be used as a loop sentinel.

=item * B<BEGIN_MAP>:

A new map is being recursed into. This is returned I<after> the map
resource itself is returned.

=item * B<END_MAP>:

The map is now done.

=item * B<BEGIN_BRANCH>:

A branch is now starting. The next resource returned will be the first
in that branch.

=item * B<END_BRANCH>:

The branch is now done.

=back

The tokens are retreivable via methods on the iterator object, i.e.,
$iterator->END_MAP.

Maps can contain empty resources. The iterator will automatically skip
over such resources, but will still treat the structure
correctly. Thus, a complicated map with several branches, but
consisting entirely of empty resources except for one beginning or
ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
but only one resource will be returned.

=back

=head2 Normal Usage

Normal usage of the iterator object is to do the following:

 my $it = $navmap->getIterator([your params here]);
 my $curRes;
 while ($curRes = $it->next()) {
   [your logic here]
 }

Note that inside of the loop, it's frequently useful to check if
"$curRes" is a reference or not with the reference function; only
resource objects will be references, and any non-references will 
be the tokens described above.

The next() routine can take two (optional) arguments:
closeAllPages - if true will not recurse down a .page
noblockcheck - passed to browsePriv() for passing as sixth arg to
call to lonnet::allowed. This needs to be set if retrieveResources
was already called from another routine called within lonnet::allowed, 
so as to prevent recursion.

Also note there is some old code floating around that tries to track
the depth of the iterator to see when it's done; do not copy that 
code. It is difficult to get right and harder to understand than
this. They should be migrated to this new style.

=cut

# Here are the tokens for the iterator:

sub END_ITERATOR { return 0; }
sub BEGIN_MAP { return 1; }    # begining of a new map
sub END_MAP { return 2; }      # end of the map
sub BEGIN_BRANCH { return 3; } # beginning of a branch
sub END_BRANCH { return 4; }   # end of a branch
sub FORWARD { return 1; }      # go forward
sub BACKWARD { return 2; }

sub min {
    (my $a, my $b) = @_;
    if ($a < $b) { return $a; } else { return $b; }
}

sub new {
    # magic invocation to create a class instance
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};

    weaken($self->{NAV_MAP} = shift);
    return undef unless ($self->{NAV_MAP});

    $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
    $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};

    # Handle the parameters
    $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
    $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();

    # If the given resources are just the ID of the resource, get the
    # objects
    if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
             $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
    if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
             $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }

    $self->{FILTER} = shift;

    # A hash, used as a set, of resource already seen
    $self->{ALREADY_SEEN} = shift;
    if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
    $self->{CONDITION} = shift;

    # Do we want to automatically follow "redirection" maps?
    $self->{FORCE_TOP} = shift;

    # Do we want to return the top-level map object (resource 0.0)?
    $self->{RETURN_0} = shift;
    # have we done that yet?
    $self->{HAVE_RETURNED_0} = 0;

    # Do we want to check the "listed" status for a resource for which
    # deeplinking applies.
    $self->{DEEPLINKLISTED} = shift;

    # Now, we need to pre-process the map, by walking forward and backward
    # over the parts of the map we're going to look at.

    # The processing steps are exactly the same, except for a few small 
    # changes, so I bundle those up in the following list of two elements:
    # (direction_to_iterate, VAL_name, next_resource_method_to_call,
    # first_resource).
    # This prevents writing nearly-identical code twice.
    my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
                        'FIRST_RESOURCE'],
                       [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
                        'FINISH_RESOURCE'] );

    my $maxDepth = 0; # tracks max depth

    # If there is only one resource in this map, and it's a map, we
    # want to remember that, so the user can ask for the first map
    # that isn't just a redirector.
    my $resource; my $resourceCount = 0;

    # Documentation on this algorithm can be found in the CVS repository at 
    # /docs/lonnavdocs; these "**#**" markers correspond to documentation
    # in that file.
    # **1**

    foreach my $pass (@iterations) {
        my $direction = $pass->[0];
        my $valName = $pass->[1];
        my $nextResourceMethod = $pass->[2];
        my $firstResourceName = $pass->[3];

        my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
                                                            $self->{FIRST_RESOURCE},
                                                            $self->{FINISH_RESOURCE},
                                                            {}, undef, 0, $direction);
    
        # prime the recursion
        $self->{$firstResourceName}->{DATA}->{$valName} = 0;
	$iterator->next();
        my $curRes = $iterator->next();
	my $depth = 1;
        while ($depth > 0) {
	    if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
	    if ($curRes == $iterator->END_MAP()) { $depth--; }

            if (ref($curRes)) {
                # If there's only one resource, this will save it
                # we have to filter empty resources from consideration here,
                # or even "empty", redirecting maps have two (start & finish)
                # or three (start, finish, plus redirector)
                if($direction == FORWARD && $curRes->src()) { 
                    $resource = $curRes; $resourceCount++; 
                }
                my $resultingVal = $curRes->{DATA}->{$valName};
                my $nextResources = $curRes->$nextResourceMethod();
                my $nextCount = scalar(@{$nextResources});

                if ($nextCount == 1) { # **3**
                    my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
                    $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
                }
                
                if ($nextCount > 1) { # **4**
                    foreach my $res (@{$nextResources}) {
                        my $current = $res->{DATA}->{$valName} || 999999999;
                        $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
                    }
                }
            }
            
            # Assign the final val (**2**)
            if (ref($curRes) && $direction == BACKWARD()) {
                my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
                                     $curRes->{DATA}->{BOT_UP_VAL});
                
                $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
                if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
            }

	    $curRes = $iterator->next();
        }
    }

    # Check: Was this only one resource, a map?
    if ($resourceCount == 1 && $resource->is_sequence() && !$self->{FORCE_TOP}) { 
        my $firstResource = $resource->map_start();
        my $finishResource = $resource->map_finish();
	return Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
						 $finishResource, $self->{FILTER},
						 $self->{ALREADY_SEEN}, 
						 $self->{CONDITION},
						 $self->{FORCE_TOP},
                                                 undef,$self->{DEEPLINKLISTED});
    }

    # Set up some bookkeeping information.
    $self->{CURRENT_DEPTH} = 0;
    $self->{MAX_DEPTH} = $maxDepth;
    $self->{STACK} = [];
    $self->{RECURSIVE_ITERATOR_FLAG} = 0;
    $self->{FINISHED} = 0; # When true, the iterator has finished

    for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
        push @{$self->{STACK}}, [];
    }

    # Prime the recursion w/ the first resource **5**
    push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
    $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;

    bless ($self);
    return $self;
}

sub next {
    my $self = shift;
    my $closeAllPages=shift;
    my $noblockcheck = shift;
    if ($self->{FINISHED}) {
	return END_ITERATOR();
    }

    # If we want to return the top-level map object, and haven't yet,
    # do so.
    if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
        $self->{HAVE_RETURNED_0} = 1;
	my $nextTopLevel = $self->{NAV_MAP}->getById('0.0');
        return $self->{NAV_MAP}->getById('0.0');
    }
    if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0_BEGIN_MAP}) {
	$self->{HAVE_RETURNED_0_BEGIN_MAP} = 1;
	return $self->BEGIN_MAP();
    }

    if ($self->{RECURSIVE_ITERATOR_FLAG}) {
        # grab the next from the recursive iterator 
        my $next = $self->{RECURSIVE_ITERATOR}->next($closeAllPages);

        # is it a begin or end map? If so, update the depth
        if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
        if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }

        # Are we back at depth 0? If so, stop recursing
        if ($self->{RECURSIVE_DEPTH} == 0) {
            $self->{RECURSIVE_ITERATOR_FLAG} = 0;
        }
        return $next;
    }

    if (defined($self->{FORCE_NEXT})) {
        my $tmp = $self->{FORCE_NEXT};
        $self->{FORCE_NEXT} = undef;
        return $tmp;
    }

    # Have we not yet begun? If not, return BEGIN_MAP and
    # remember we've started.
    if ( !$self->{STARTED} ) { 
        $self->{STARTED} = 1;
        return $self->BEGIN_MAP();
    }

    # Here's the guts of the iterator.
    
    # Find the next resource, if any.
    my $found = 0;
    my $i = $self->{MAX_DEPTH};
    my $newDepth;
    my $here;
    while ( $i >= 0 && !$found ) {
        if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
            $here = pop @{$self->{STACK}->[$i]}; # **7**
            $found = 1;
            $newDepth = $i;
        }
        $i--;
    }

    # If we still didn't find anything, we're done.
    if ( !$found ) {
        # We need to get back down to the correct branch depth
        if ( $self->{CURRENT_DEPTH} > 0 ) {
            $self->{CURRENT_DEPTH}--;
            return END_BRANCH();
        } else {
	    $self->{FINISHED} = 1;
            return END_MAP();
        }
    }

    # If this is not a resource, it must be an END_BRANCH marker we want
    # to return directly.
    if (!ref($here)) { # **8**
        if ($here == END_BRANCH()) { # paranoia, in case of later extension
            $self->{CURRENT_DEPTH}--;
            return $here;
        }
    }

    # Otherwise, it is a resource and it's safe to store in $self->{HERE}
    $self->{HERE} = $here;

    # Get to the right level
    if ( $self->{CURRENT_DEPTH} > $newDepth ) {
        push @{$self->{STACK}->[$newDepth]}, $here;
        $self->{CURRENT_DEPTH}--;
        return END_BRANCH();
    }
    if ( $self->{CURRENT_DEPTH} < $newDepth) {
        push @{$self->{STACK}->[$newDepth]}, $here;
        $self->{CURRENT_DEPTH}++;
        return BEGIN_BRANCH();
    }

    # If we made it here, we have the next resource, and we're at the
    # right branch level. So let's examine the resource for where
    # we can get to from here.

    # So we need to look at all the resources we can get to from here,
    # categorize them if we haven't seen them, remember if we have a new
    my $nextUnfiltered = $here->getNext();


    my $maxDepthAdded = -1;
    
    for (@$nextUnfiltered) {
        if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
            my $depth = $_->{DATA}->{DISPLAY_DEPTH};
            push @{$self->{STACK}->[$depth]}, $_;
            $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
            if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
        }
    }

    # Is this the end of a branch? If so, all of the resources examined above
    # led to lower levels than the one we are currently at, so we push a END_BRANCH
    # marker onto the stack so we don't forget.
    # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
    # BC branch and gets to C, it will see F as the only next resource, but it's
    # one level lower. Thus, this is the end of the branch, since there are no
    # more resources added to this level or above.
    # We don't do this if the examined resource is the finish resource,
    # because the condition given above is true, but the "END_MAP" will
    # take care of things and we should already be at depth 0.
    my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
    if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
        push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
    }

    # That ends the main iterator logic. Now, do we want to recurse
    # down this map (if this resource is a map)?
    if ( ($self->{HERE}->is_sequence() || (!$closeAllPages && $self->{HERE}->is_page())) &&
        (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION}) &&
        ($env{'request.role.adv'} || !$self->{HERE}->randomout())) {
        $self->{RECURSIVE_ITERATOR_FLAG} = 1;
        my $firstResource = $self->{HERE}->map_start();
        my $finishResource = $self->{HERE}->map_finish();
        $self->{RECURSIVE_ITERATOR} = 
            Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                                              $finishResource, $self->{FILTER},
                                              $self->{ALREADY_SEEN},
					      $self->{CONDITION},
					      $self->{FORCE_TOP},
                                              undef,$self->{DEEPLINKLISTED});
    }

    # If this is a blank resource, don't actually return it.
    # Should you ever find you need it, make sure to add an option to the code
    #  that you can use; other things depend on this behavior.
    my $browsePriv = $self->{HERE}->browsePriv($noblockcheck,$self->{DEEPLINKLISTED});
    if (!$self->{HERE}->src() || 
        (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
        return $self->next($closeAllPages);
    }

    return $self->{HERE};

}

=pod

The other method available on the iterator is B<getStack>, which
returns an array populated with the current 'stack' of maps, as
references to the resource objects. Example: This is useful when
making the navigation map, as we need to check whether we are under a
page map to see if we need to link directly to the resource, or to the
page. The first elements in the array will correspond to the top of
the stack (most inclusive map).

=cut

sub getStack {
    my $self=shift;

    my @stack;

    $self->populateStack(\@stack);

    return \@stack;
}

# Private method: Calls the iterators recursively to populate the stack.
sub populateStack {
    my $self=shift;
    my $stack = shift;

    push @$stack, $self->{HERE} if ($self->{HERE});

    if ($self->{RECURSIVE_ITERATOR_FLAG}) {
        $self->{RECURSIVE_ITERATOR}->populateStack($stack);
    }
}

1;

package Apache::lonnavmaps::DFSiterator;
use Scalar::Util qw(weaken);
use Apache::lonnet;

# Not documented in the perldoc: This is a simple iterator that just walks
#  through the nav map and presents the resources in a depth-first search
#  fashion, ignorant of conditionals, randomized resources, etc. It presents
#  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
#  useful for pre-processing of some kind, and is in fact used by the main
#  iterator that way, but that's about it.
# One could imagine merging this into the init routine of the main iterator,
#  but this might as well be left separate, since it is possible some other
#  use might be found for it. - Jeremy

# Unlike the main iterator, this DOES return all resources, even blank ones.
#  The main iterator needs them to correctly preprocess the map.

sub BEGIN_MAP { return 1; }    # begining of a new map
sub END_MAP { return 2; }      # end of the map
sub FORWARD { return 1; }      # go forward
sub BACKWARD { return 2; }

# Params: Nav map ref, first resource id/ref, finish resource id/ref,
#         filter hash ref (or undef), already seen hash or undef, condition
#         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
sub new {
    # magic invocation to create a class instance
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};

    weaken($self->{NAV_MAP} = shift);
    return undef unless ($self->{NAV_MAP});

    $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
    $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};

    $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
    $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();

    # If the given resources are just the ID of the resource, get the
    # objects
    if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
             $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
    if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
             $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }

    $self->{FILTER} = shift;

    # A hash, used as a set, of resource already seen
    $self->{ALREADY_SEEN} = shift;
     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
    $self->{CONDITION} = shift;
    $self->{DIRECTION} = shift || FORWARD();

    # Flag: Have we started yet?
    $self->{STARTED} = 0;

    # Should we continue calling the recursive iterator, if any?
    $self->{RECURSIVE_ITERATOR_FLAG} = 0;
    # The recursive iterator, if any
    $self->{RECURSIVE_ITERATOR} = undef;
    # Are we recursing on a map, or a branch?
    $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
    # And the count of how deep it is, so that this iterator can keep track of
    # when to pick back up again.
    $self->{RECURSIVE_DEPTH} = 0;

    # For keeping track of our branches, we maintain our own stack
    $self->{STACK} = [];

    # Start with the first resource
    if ($self->{DIRECTION} == FORWARD) {
        push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
    } else {
        push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
    }

    bless($self);
    return $self;
}

sub next {
    my $self = shift;
    
    # Are we using a recursive iterator? If so, pull from that and
    # watch the depth; we want to resume our level at the correct time.
    if ($self->{RECURSIVE_ITERATOR_FLAG}) {
        # grab the next from the recursive iterator
        my $next = $self->{RECURSIVE_ITERATOR}->next();
        
        # is it a begin or end map? Update depth if so
        if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
        if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }

        # Are we back at depth 0? If so, stop recursing.
        if ($self->{RECURSIVE_DEPTH} == 0) {
            $self->{RECURSIVE_ITERATOR_FLAG} = 0;
        }
        
        return $next;
    }

    # Is there a current resource to grab? If not, then return
    # END_MAP, which will end the iterator.
    if (scalar(@{$self->{STACK}}) == 0) {
        return $self->END_MAP();
    }

    # Have we not yet begun? If not, return BEGIN_MAP and 
    # remember that we've started.
    if ( !$self->{STARTED} ) {
        $self->{STARTED} = 1;
        return $self->BEGIN_MAP;
    }

    # Get the next resource in the branch
    $self->{HERE} = pop @{$self->{STACK}};

    # remember that we've seen this, so we don't return it again later
    $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
    
    # Get the next possible resources
    my $nextUnfiltered;
    if ($self->{DIRECTION} == FORWARD()) {
        $nextUnfiltered = $self->{HERE}->getNext();
    } else {
        $nextUnfiltered = $self->{HERE}->getPrevious();
    }
    my $next = [];

    # filter the next possibilities to remove things we've 
    # already seen.
    foreach my $item (@$nextUnfiltered) {
        if (!defined($self->{ALREADY_SEEN}->{$item->{ID}})) {
            push @$next, $item;
        }
    }

    while (@$next) {
        # copy the next possibilities over to the stack
        push @{$self->{STACK}}, shift @$next;
    }

    # If this is a map and we want to recurse down it... (not filtered out)
    if ($self->{HERE}->is_map() && 
         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
        $self->{RECURSIVE_ITERATOR_FLAG} = 1;
        my $firstResource = $self->{HERE}->map_start();
        my $finishResource = $self->{HERE}->map_finish();

        $self->{RECURSIVE_ITERATOR} =
          Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
                     $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
                                             $self->{CONDITION}, $self->{DIRECTION});
    }

    return $self->{HERE};
}

# Identical to the full iterator methods of the same name. Hate to copy/paste
# but I also hate to "inherit" either iterator from the other.

sub getStack {
    my $self=shift;

    my @stack;

    $self->populateStack(\@stack);

    return \@stack;
}

# Private method: Calls the iterators recursively to populate the stack.
sub populateStack {
    my $self=shift;
    my $stack = shift;

    push @$stack, $self->{HERE} if ($self->{HERE});

    if ($self->{RECURSIVE_ITERATOR_FLAG}) {
        $self->{RECURSIVE_ITERATOR}->populateStack($stack);
    }
}

1;

package Apache::lonnavmaps::resource;
use Scalar::Util qw(weaken);
use Apache::lonnet;

=pod

=head1 Object: resource 

X<resource, navmap object>
A resource object encapsulates a resource in a resource map, allowing
easy manipulation of the resource, querying the properties of the
resource (including user properties), and represents a reference that
can be used as the canonical representation of the resource by
lonnavmap clients like renderers.

A resource only makes sense in the context of a navmap, as some of the
data is stored in the navmap object.

You will probably never need to instantiate this object directly. Use
Apache::lonnavmaps::navmap, and use the "start" method to obtain the
starting resource.

Resource objects respect the parameter_hiddenparts, which suppresses 
various parts according to the wishes of the map author. As of this
writing, there is no way to override this parameter, and suppressed
parts will never be returned, nor will their response types or ids be
stored.

=head2 Overview

A B<Resource> is the most granular type of object in LON-CAPA that can
be included in a course. It can either be a particular resource, like
an HTML page, external resource, problem, etc., or it can be a
container sequence, such as a "page" or a "map".

To see a sequence from the user's point of view, please see the
B<Creating a Course: Maps and Sequences> chapter of the Author's
Manual.

A Resource Object, once obtained from a navmap object via a B<getBy*>
method of the navmap, or from an iterator, allows you to query
information about that resource.

Generally, you do not ever want to create a resource object yourself,
so creation has been left undocumented. Always retrieve resources
from navmap objects.

=head3 Identifying Resources

X<big hash>Every resource is identified by a Resource ID in the big hash that is
unique to that resource for a given course. X<resource ID, in big hash>
The Resource ID has the form #.#, where the first number is the same
for every resource in a map, and the second is unique. For instance,
for a course laid out like this:

 * Problem 1
 * Map
   * Resource 2
   * Resource 3

C<Problem 1> and C<Map> will share a first number, and C<Resource 2>
C<Resource 3> will share a first number. The second number may end up
re-used between the two groups.

The resource ID is only used in the big hash, but can be used in the
context of a course to identify a resource easily. (For instance, the
printing system uses it to record which resources from a sequence you 
wish to print.)

X<symb> X<resource, symb>
All resources also have B<symb>s, which uniquely identify a resource
in a course. Many internal LON-CAPA functions expect a symb. A symb
carries along with it the URL of the resource, and the map it appears
in. Symbs are much larger than resource IDs.

=cut

sub new {
    # magic invocation to create a class instance
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};

    weaken($self->{NAV_MAP} = shift);
    $self->{ID} = shift;

    $self->{USERNAME} = $self->{NAV_MAP}->{USERNAME};
    $self->{DOMAIN}   = $self->{NAV_MAP}->{DOMAIN};

    # Store this new resource in the parent nav map's cache.
    $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
    $self->{RESOURCE_ERROR} = 0;

    $self->{DUEDATE_CACHE} = undef;

    # A hash that can be used by two-pass algorithms to store data
    # about this resource in. Not used by the resource object
    # directly.
    $self->{DATA} = {};
    
    bless($self);
    
    # This is a speed optimization, to avoid calling symb() too often.
    $self->{SYMB} = $self->symb();

    return $self;
}

# private function: simplify the NAV_HASH lookups we keep doing
# pass the name, and to automatically append my ID, pass a true val on the
# second param
sub navHash {
    my $self = shift;
    my $param = shift;
    my $id = shift;
    my $arg = $param . ($id?$self->{ID}:"");
    if (ref($self) && ref($self->{NAV_MAP}) && defined($arg)) {
        return $self->{NAV_MAP}->navhash($arg);
    }
    return;
}

=pod

=head2 Methods

Once you have a resource object, here's what you can do with it:

=head3 Attribute Retrieval

Every resource has certain attributes that can be retrieved and used:

=over 4

=item * B<ID>: Every resource has an ID that is unique for that
    resource in the course it is in. The ID is actually in the hash
    representing the resource, so for a resource object $res, obtain
    it via C<$res->{ID}).

=item * B<compTitle>:

Returns a "composite title", that is equal to $res->title() if the
resource has a title, and is otherwise the last part of the URL (e.g.,
"problem.problem").

=item * B<ext>:

Returns true if the resource is external.

=item * B<kind>:

Returns the kind of the resource from the compiled nav map.

=item * B<randomout>:

Returns true if this resource was chosen to NOT be shown to the user
by the random map selection feature. In other words, this is usually
false.

=item * B<randompick>:

Returns the number of randomly picked items for a map if the randompick
feature is being used on the map. 

=item * B<randomorder>:

Returns true for a map if the randomorder feature is being used on the
map.

=item * B<src>:

Returns the source for the resource.

=item * B<symb>:

Returns the symb for the resource.

=item * B<title>:

Returns the title of the resource.

=back

=cut

# These info functions can be used directly, as they don't return
# resource information.
sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
sub encrypted { my $self=shift; return $self->navHash("encrypted_", 1); }
sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
sub from { my $self=shift; return $self->navHash("from_", 1); }
# considered private and undocumented
sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
sub kind { my $self=shift; return $self->navHash("kind_", 1); }
sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
sub deeplinkout { my $self=shift; return $self->navHash("deeplinkout_", 1); }
sub randompick { 
    my $self = shift;
    my $randompick = $self->parmval('randompick');
    return $randompick;
}
sub randomorder { 
    my $self = shift;
    my $randomorder = $self->parmval('randomorder');
    return ($randomorder =~ /^yes$/i);
}
sub link {
    my $self=shift;
    if ($self->encrypted()) { return &Apache::lonenc::encrypted($self->src); }
    return $self->src;
}
sub src { 
    my $self=shift;
    return $self->navHash("src_", 1);
}
sub shown_symb {
    my $self=shift;
    if ($self->encrypted()) {return &Apache::lonenc::encrypted($self->{SYMB});}
    return $self->{SYMB};
}
sub id {
    my $self=shift;
    return $self->{ID};
}
sub enclosing_map_src {
    my $self=shift;
    (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
    return $self->navHash('map_id_'.$first);
}
sub symb {
    my $self=shift;
    if (defined $self->{SYMB}) { return $self->{SYMB}; }
    (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
    my $symbSrc = &Apache::lonnet::declutter($self->src());
    my $symb = &Apache::lonnet::declutter($self->navHash('map_id_'.$first)) 
        . '___' . $second . '___' . $symbSrc;
    return &Apache::lonnet::symbclean($symb);
}
sub wrap_symb {
    my $self = shift;
    return $self->{NAV_MAP}->wrap_symb($self->{SYMB});
}
sub title { 
    my $self=shift; 
    if ($self->{ID} eq '0.0') {
	# If this is the top-level map, return the title of the course
	# since this map can not be titled otherwise.
	return $env{'course.'.$env{'request.course.id'}.'.description'};
    }
    return $self->navHash("title_", 1); }
# considered private and undocumented
sub to { my $self=shift; return $self->navHash("to_", 1); }
sub condition {
    my $self=shift;
    my $undercond=$self->navHash("undercond_", 1);
    if (!defined($undercond)) { return 1; };
    my $condid=$self->navHash("condid_$undercond");
    if (!defined($condid)) { return 1; };
    my $condition=&Apache::lonnet::directcondval($condid);
    return $condition;
}
sub condval {
    my $self=shift;
    my ($pathname,$filename) = 
	&Apache::lonnet::split_uri_for_cond($self->src());

    my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
	       /\&\Q$filename\E\:([\d\|]+)\&/);
    if ($match) {
	return &Apache::lonnet::condval($1);
    }
    return 0;
}
sub compTitle {
    my $self = shift;
    my $title = $self->title();
    $title=~s/\&colon\;/\:/gs;
    if (!$title) {
        $title = $self->src();
        $title = substr($title, rindex($title, '/') + 1);
    }
    return $title;
}

=pod

B<Predicate Testing the Resource>

These methods are shortcuts to deciding if a given resource has a given property.

=over 4

=item * B<is_map>:

Returns true if the resource is a map type.

=item * B<is_problem>:

Returns true if the resource is a problem type, false
otherwise. (Looks at the extension on the src field; might need more
to work correctly.)

=item * B<is_page>:

Returns true if the resource is a page.

=item * B<is_sequence>:

Returns true if the resource is a sequence.

=back

=cut

sub hasResource {
   my $self = shift;
   return $self->{NAV_MAP}->hasResource(@_);
}

sub retrieveResources {
   my $self = shift;
   return $self->{NAV_MAP}->retrieveResources(@_);
}

sub is_exam {
    my ($self,$part) = @_;
    my $type = $self->parmval('type',$part);
    if ($type eq 'exam') {
        return 1;
    }
    if ($self->src() =~ /\.(exam)$/) {
        return 1;
    }
    return 0;
}
sub is_html {
    my $self=shift;
    my $src = $self->src();
    return ($src =~ /html$/);
}
sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
sub is_page {
    my $self=shift;
    my $src = $self->src();
    return $self->navHash("is_map_", 1) && 
	$self->navHash("map_type_" . $self->map_pc()) eq 'page';
}
sub is_practice {
    my $self=shift;
    my ($part) = @_;
    my $type = $self->parmval('type',$part);
    if ($type eq 'practice') {
        return 1;
    }
    return 0;
}
sub is_problem {
    my $self=shift;
    my $src = $self->src();
    if ($src =~ /$LONCAPA::assess_re/) {
	return !($self->is_practice());
    }
    return 0;
}
sub is_tool {
    my $self=shift;
    my $src = $self->src();
    return ($src =~ /ext\.tool$/);
}
sub is_gradable {
    my $self=shift;
    my $src = $self->src();
    if (($src =~ /$LONCAPA::assess_re/) ||
        (($self->is_tool()) && ($self->parmval('gradable',0) =~ /^yes$/i))) {
        return !($self->is_practice());
    }
}
#
#  The has below is the set of status that are considered 'incomplete'
#
my %incomplete_hash = 
(
 TRIES_LEFT()     => 1,
 OPEN()           => 1,
 ATTEMPTED()      => 1

 );
#
#  Return tru if a problem is incomplete... for now incomplete means that
#  any part of the problem is incomplete. 
#  Note that if the resources is not a problem, 0 is returned.
#
sub is_incomplete {
    my $self = shift;
    if ($self->is_problem()) {
	foreach my $part (@{$self->parts()}) {
	    if (exists($incomplete_hash{$self->status($part)})) {
		return 1;
	    }
	}
    }
    return 0;
       
}
sub is_raw_problem {
    my $self=shift;
    my $src = $self->src();
    if ($src =~ /$LONCAPA::assess_re/) {
        return 1;
    }
    return 0;
}

sub contains_problem {
    my $self=shift;
    if ($self->is_page()) {
	my $hasProblem=$self->hasResource($self,sub { $_[0]->is_problem() },1);
	return $hasProblem;
    }
    return 0;
}
sub map_contains_problem {
    my $self=shift;
    if ($self->is_map()) {
	my $has_problem=
	    $self->hasResource($self,sub { $_[0]->is_problem() },1);
	return $has_problem;
    }
    return 0;
}
sub is_sequence {
    my $self=shift;
    return $self->navHash("is_map_", 1) && 
    $self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
}
sub is_survey {
    my $self = shift();
    my $part = shift();
    my $type = $self->parmval('type',$part);
    if (($type eq 'survey') || ($type eq 'surveycred')) {
        return 1;
    }
    if ($self->src() =~ /\.(survey)$/) {
        return 1;
    }
    return 0;
}
sub is_anonsurvey {
    my $self = shift();
    my $part = shift();
    my $type = $self->parmval('type',$part);
    if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
        return 1;
    }
    return 0;
}
sub is_task {
    my $self=shift;
    my $src = $self->src();
    return ($src =~ /\.(task)$/)
}

sub is_empty_sequence {
    my $self=shift;
    return !$self->is_page() && $self->navHash("is_map_", 1) && !$self->navHash("map_type_" . $self->map_pc());
}

# Private method: Shells out to the parmval in the nav map, handler parts.
sub parmval {
    my $self = shift;
    my $what = shift;
    my $part = shift;
    if (!defined($part)) { 
        $part = '0'; 
    }
    return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->{SYMB});
}

=pod

B<Map Methods>

These methods are useful for getting information about the map
properties of the resource, if the resource is a map (B<is_map>).

=over 4

=item * B<map_finish>:

Returns a reference to a resource object corresponding to the finish
resource of the map.

=item * B<map_pc>:

Returns the pc value of the map, which is the first number that
appears in the resource ID of the resources in the map, and is the
number that appears around the middle of the symbs of the resources in
that map.

=item * B<map_start>:

Returns a reference to a resource object corresponding to the start
resource of the map.

=item * B<map_type>:

Returns a string with the type of the map in it.

=item * B<map_hierarchy>:

Returns a string with a comma-separated ordered list of map_pc IDs
for the hierarchy of maps containing a map, with the top level
map first, then descending to deeper levels, with the enclosing map last.

=item * B<map_breadcrumbs>:

Same as map_hierarchy, except maps containing only a single itemm if
it's a map, or containing no items are omitted, unless it's the top
level map (map_pc = 1), which is always included.

=back

=cut

sub map_finish {
    my $self = shift;
    my $src = $self->src();
    $src = &Apache::lonnet::clutter($src);
    my $res = $self->navHash("map_finish_$src", 0);
    $res = $self->{NAV_MAP}->getById($res);
    return $res;
}
sub map_pc {
    my $self = shift;
    my $src = $self->src();
    return $self->navHash("map_pc_$src", 0);
}
sub map_start {
    my $self = shift;
    my $src = $self->src();
    $src = &Apache::lonnet::clutter($src);
    my $res = $self->navHash("map_start_$src", 0);
    $res = $self->{NAV_MAP}->getById($res);
    return $res;
}
sub map_type {
    my $self = shift;
    my $pc = $self->map_pc();
    return $self->navHash("map_type_$pc", 0);
}
sub map_hierarchy {
    my $self = shift;
    my $pc = $self->map_pc();
    return $self->navHash("map_hierarchy_$pc", 0);
}
sub map_breadcrumbs {
    my $self = shift;
    my $pc = $self->map_pc();
    return $self->navHash("map_breadcrumbs_$pc", 0);
}

#####
# Property queries
#####

# These functions will be responsible for returning the CORRECT
# VALUE for the parameter, no matter what. So while they may look
# like direct calls to parmval, they can be more than that.
# So, for instance, the duedate function should use the "duedatetype"
# information, rather than the resource object user.

=pod

=head2 Resource Parameters

In order to use the resource parameters correctly, the nav map must
have been instantiated with genCourseAndUserOptions set to true, so
the courseopt and useropt is read correctly. Then, you can call these
functions to get the relevant parameters for the resource. Each
function defaults to part "0", but can be directed to another part by
passing the part as the parameter.

These methods are responsible for getting the parameter correct, not
merely reflecting the contents of the GDBM hashes. As we move towards
dates relative to other dates, these methods should be updated to
reflect that. (Then, anybody using these methods will not have to update
their code.)

=over 4


=item * B<printable>

returns true if the current date is such that the 
specified resource part is printable.


=item * B<resprintable>

Returns true if all parts in the resource are printable making the
entire resource printable.

=item * B<acc>

Get the Client IP/Name Access Control information.

=item * B<answerdate>:

Get the answer-reveal date for the problem.

=item * B<awarded>: 

Gets the awarded value for the problem part. Requires genUserData set to
true when the navmap object was created.

=item * B<duedate>:

Get the due date for the problem.

=item * B<tries>:

Get the number of tries the student has used on the problem.

=item * B<maxtries>:

Get the number of max tries allowed.

=item * B<opendate>:

Get the open date for the problem.

=item * B<sig>:

Get the significant figures setting.

=item * B<tol>:

Get the tolerance for the problem.

=item * B<tries>:

Get the number of tries the user has already used on the problem.

=item * B<type>:

Get the question type for the problem.

=item * B<weight>:

Get the weight for the problem.

=back

=cut




sub printable {

    my ($self, $part) = @_;

    #  The following cases apply:
    #  - If a start date is not set, it is replaced by the open date.
    #  - Ditto for start/open replaced by content open.
    #  - If neither start nor printdates are set the part is printable.
    #  - Start date set but no end date: Printable if now >= start date.
    #  - End date set but no start date: Printable if now <= end date.
    #  - both defined: printable if start <= now <= end
    #

    # Get the print open/close dates for the resource.

    my $start = $self->parmval("printstartdate", $part);
    my $end   = $self->parmval("printenddate", $part);

    if (!$start) {
	$start = $self->parmval("opendate", $part);
    }
    if (!$start) {
	$start = $self->parmval("contentopen", $part);
    }


    my $now  = time();


    my $startok = 1;
    my $endok   = 1;

    if ((defined $start) && ($start ne '')) {
	$startok = $start <= $now;
    }
    if ((defined $end) && ($end != '')) {
	$endok = $end >= $now;
    }
    return $startok && $endok;
}

sub resprintable {
    my $self = shift;

    # get parts...or realize there are no parts.

    my $partsref = $self->parts();
    my @parts    = @$partsref;

    if (!@parts) {
	return $self->printable(0);
    } else {
	foreach my $part  (@parts) {
	    if (!$self->printable($part)) { 
		return 0; 
	    }
	}
	return 1;
    }
}

sub acc {
    (my $self, my $part) = @_;
    my $acc = $self->parmval("acc", $part);
    return $acc;
}
sub answerdate {
    (my $self, my $part) = @_;
    # Handle intervals
    my $answerdatetype = $self->parmval("answerdate.type", $part);
    my $answerdate = $self->parmval("answerdate", $part);
    my $duedate = $self->parmval("duedate", $part);
    if ($answerdatetype eq 'date_interval') {
        $answerdate = $duedate + $answerdate; 
    }
    return $answerdate;
}
sub awarded { 
    my $self = shift; my $part = shift;
    $self->{NAV_MAP}->get_user_data();
    if (!defined($part)) { $part = '0'; }
    return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.awarded'};
}
sub taskversion {
    my $self = shift; my $part = shift;
    $self->{NAV_MAP}->get_user_data();
    if (!defined($part)) { $part = '0'; }
    return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.version'};
}
sub taskstatus {
    my $self = shift; my $part = shift;
    $self->{NAV_MAP}->get_user_data();
    if (!defined($part)) { $part = '0'; }
    return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$self->taskversion($part).'.'.$part.'.status'};
}
sub solved {
    my $self = shift; my $part = shift;
    $self->{NAV_MAP}->get_user_data();
    if (!defined($part)) { $part = '0'; }
    return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.solved'};
}
sub checkedin {
    my $self = shift; my $part = shift;
    $self->{NAV_MAP}->get_user_data();
    if (!defined($part)) { $part = '0'; }
    if ($self->is_task()) {
        my $version = $self->taskversion($part);
        return ($self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$version .'.'.$part.'.checkedin'},$self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$version .'.'.$part.'.checkedin.slot'});
    } else {
        return ($self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.checkedin'},$self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}}->{'resource.'.$part.'.checkedin.slot'});
    }
}
# this should work exactly like the copy in lonhomework.pm
# Why is there a copy in lonhomework?  Why not centralized?
#
#  TODO: Centralize duedate.
#

sub duedate {
    (my $self, my $part) = @_;
    if (defined ($self->{DUEDATE_CACHE}->{$part})) {
        return $self->{DUEDATE_CACHE}->{$part};
    }
    my $date;
    my @interval=$self->parmval("interval", $part);
    my $due_date=$self->parmval("duedate", $part);
    if ($interval[0] =~ /^(\d+)/) {
        my $timelimit = $1;
        my $first_access=&Apache::lonnet::get_first_access($interval[1],
                                                           $self->{SYMB});
	if (defined($first_access)) {
            my $interval = $first_access+$timelimit;
	    $date = (!$due_date || $interval < $due_date) ? $interval 
                                                          : $due_date;
	} else {
	    $date = $due_date;
	}
    } else {
	$date = $due_date;
    }
    $self->{DUEDATE_CACHE}->{$part} = $date;
    return $date;
}
sub handgrade {
    (my $self, my $part) = @_;
    my @response_ids = $self->responseIds($part);
    if (@response_ids) {
	foreach my $response_id (@response_ids) {
            my $handgrade = $self->parmval("handgrade",$part.'_'.$response_id);
	    if (lc($handgrade) eq 'yes') {
		return 'yes';
	    }
	}
    }
    my $handgrade = $self->parmval("handgrade", $part);
    return $handgrade;
}
sub maxtries {
    (my $self, my $part) = @_;
    my $maxtries = $self->parmval("maxtries", $part);
    return $maxtries;
}
sub opendate {
    (my $self, my $part) = @_;
    my $opendatetype = $self->parmval("opendate.type", $part);
    my $opendate = $self->parmval("opendate", $part); 
    if ($opendatetype eq 'date_interval') {
        my $duedate = $self->duedate($part);
        $opendate = $duedate - $opendate; 
    }
    return $opendate;
}
sub problemstatus {
    (my $self, my $part) = @_;
    my $problemstatus = $self->parmval("problemstatus", $part);
    return lc($problemstatus);
}
sub sig {
    (my $self, my $part) = @_;
    my $sig = $self->parmval("sig", $part);
    return $sig;
}
sub tol {
    (my $self, my $part) = @_;
    my $tol = $self->parmval("tol", $part);
    return $tol;
}
sub tries {
    my $self = shift; 
    my $tries = $self->queryRestoreHash('tries', shift);
    if (!defined($tries)) { return '0';}
    return $tries;
}
sub type {
    (my $self, my $part) = @_;
    my $type = $self->parmval("type", $part);
    return $type;
}
sub weight { 
    my $self = shift; my $part = shift;
    if (!defined($part)) { $part = '0'; }
    my $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                                $self->{SYMB}, $self->{DOMAIN},
                                $self->{USERNAME},
                                $env{'request.course.sec'});
    return $weight;
}
sub part_display {
    my $self= shift(); my $partID = shift();
    if (! defined($partID)) { $partID = '0'; }
    my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',
                                     $self->{SYMB});
    if (! defined($display) || $display eq '') {
        $display = $partID;
    }
    return $display;
}
sub slot_control {
    my $self=shift(); my $part = shift();
    if (!defined($part)) { $part = '0'; }
    my $useslots = $self->parmval("useslots", $part);
    my $availablestudent = $self->parmval("availablestudent", $part);
    my $available = $self->parmval("available", $part); 
    return ($useslots,$availablestudent,$available);
}
sub deeplink {
    my ($self,$caller,$action) = @_;
    my $deeplink = $self->parmval("deeplink");
    if ($deeplink) {
        my ($state,$others,$listed,$scope) = split(/,/,$deeplink);
        if ($action eq 'getlisted') {
            return $listed;
        }
        if ($env{'request.deeplink.login'}) {
            my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
            my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
            my $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
            if ($deeplink_symb) {
                my ($loginmap,$mapname);
                if ($deeplink_symb =~ /\.(page|sequence)$/) {
                    $mapname = $self->enclosing_map_src();
                    $loginmap = &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                    return if ($mapname eq $loginmap);
                } else {
                    return if ($deeplink_symb eq $self->symb());
                    if (($scope eq 'map') || ($scope eq 'rec')) {
                        $mapname = $self->enclosing_map_src();
                        $loginmap = &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($deeplink_symb))[0]);
                        return if ($mapname eq $loginmap);
                    }
                }
                if ($scope eq 'rec') {
                    my $map_pc = $self->navHash('map_pc_'.$mapname);
                    my @recurseup = split(/,/,$self->navHash('map_hierarchy_'.$map_pc));
                    my $login_pc = $self->navHash('map_pc_'.$loginmap);
                    return if (grep(/^\Q$login_pc\E$/,@recurseup));
                }
            }
        }
        unless (($caller eq 'sequence') || ($state eq 'both')) {
            return $listed;
        }
    }
    return;
}

# Multiple things need this
sub getReturnHash {
    my $self = shift;
    
    if (!defined($self->{RETURN_HASH})) {
        #my %tmpHash  = &Apache::lonnet::restore($self->{SYMB},undef,$self->{DOMAIN},$self->{USERNAME});
        #$self->{RETURN_HASH} = \%tmpHash;
        # When info is retrieved for several resources (as when rendering a directory),
        # it is much faster to use the user profile dump and avoid repeated lonnet requests
        # (especially since lonnet::currentdump is using Lond directly whenever possible,
        # and lonnet::restore is not at this point).
        $self->{NAV_MAP}->get_user_data();
        $self->{RETURN_HASH} = $self->{NAV_MAP}->{STUDENT_DATA}->{$self->{SYMB}};
    }
}       

######
# Status queries
######

# These methods query the status of problems.

# If we need to count parts, this function determines the number of
# parts from the metadata. When called, it returns a reference to a list
# of strings corresponding to the parts. (Thus, using it in a scalar context
# tells you how many parts you have in the problem:
# $partcount = scalar($resource->countParts());
# Don't use $self->{PARTS} directly because you don't know if it's been
# computed yet.

=pod

=head2 Resource misc

Misc. functions for the resource.

=over 4

=item * B<hasDiscussion>:

Returns a false value if there has been discussion since the user last
logged in, true if there has. Always returns false if the discussion
data was not extracted when the nav map was constructed.

=item * B<last_post_time>:

Returns a false value if there hasn't been discussion otherwise returns
unix timestamp of last time a discussion posting (or edit) was made.

=item * B<discussion_info>:

optional argument is a filter (currently can be 'unread');
returns in scalar context the count of the number of discussion postings.

returns in list context both the count of postings and a hash ref
containing information about the postings (subject, id, timestamp) in a hash.

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.

=item * B<getFeedback>:

Gets the feedback for the resource and returns the raw feedback string
for the resource, or the null string if there is no feedback or the
email data was not extracted when the nav map was constructed. Usually
used like this:

 for my $url (split(/\,/, $res->getFeedback())) {
    my $link = &escape($url);
    ...

and use the link as appropriate.

=cut

sub hasDiscussion {
    my $self = shift;
    return $self->{NAV_MAP}->hasDiscussion($self->{SYMB});
}

sub last_post_time {
    my $self = shift;
    return $self->{NAV_MAP}->last_post_time($self->{SYMB});
}

sub discussion_info {
    my ($self,$filter) = @_;
    return $self->{NAV_MAP}->discussion_info($self->{SYMB},$filter);
}

sub getFeedback {
    my $self = shift;
    my $source = $self->src();
    my $symb = $self->{SYMB};
    if ($source =~ /^\/res\//) { $source = substr $source, 5; }
    return $self->{NAV_MAP}->getFeedback($symb,$source);
}

sub getErrors {
    my $self = shift;
    my $source = $self->src();
    my $symb = $self->{SYMB};
    if ($source =~ /^\/res\//) { $source = substr $source, 5; }
    return $self->{NAV_MAP}->getErrors($symb,$source);
}

=pod

=item * B<parts>():

Returns a list reference containing sorted strings corresponding to
each part of the problem. Single part problems have only a part '0'.
Multipart problems do not return their part '0', since they typically
do not really matter. 

=item * B<countParts>():

Returns the number of parts of the problem a student can answer. Thus,
for single part problems, returns 1. For multipart, it returns the
number of parts in the problem, not including psuedo-part 0. 

=item * B<countResponses>():

Returns the total number of responses in the problem a student can answer.

=item * B<responseTypes>():

Returns a hash whose keys are the response types.  The values are the number 
of times each response type is used.  This is for the I<entire> problem, not 
just a single part.

=item * B<multipart>():

Returns true if the problem is multipart, false otherwise. Use this instead
of countParts if all you want is multipart/not multipart.

=item * B<responseType>($part):

Returns the response type of the part, without the word "response" on the
end. Example return values: 'string', 'essay', 'numeric', etc.

=item * B<responseIds>($part):

Retreives the response IDs for the given part as an array reference containing
strings naming the response IDs. This may be empty.

=back

=cut

sub parts {
    my $self = shift;

    if ($self->ext) { return []; }
    if (($self->is_tool()) &&
        ($self->is_gradable())) { return ['0']; }

    $self->extractParts();
    return $self->{PARTS};
}

sub countParts {
    my $self = shift;
    
    my $parts = $self->parts();

    # If I left this here, then it's not necessary.
    #my $delta = 0;
    #for my $part (@$parts) {
    #    if ($part eq '0') { $delta--; }
    #}

    if ($self->{RESOURCE_ERROR}) {
        return 0;
    }

    return scalar(@{$parts}); # + $delta;
}

sub countResponses {
    my $self = shift;
    my $count;
    foreach my $part (@{$self->parts()}) {
        $count+= scalar($self->responseIds($part));
    }
    return $count;
}

sub responseTypes {
    my $self = shift;
    my %responses;
    foreach my $part (@{$self->parts()}) {
        foreach my $responsetype ($self->responseType($part)) {
            $responses{$responsetype}++ if (defined($responsetype));
        }
    }
    return %responses;
}

sub multipart {
    my $self = shift;
    return $self->countParts() > 1;
}

sub singlepart {
    my $self = shift;
    return $self->countParts() == 1;
}

sub responseType {
    my $self = shift;
    my $part = shift;

    $self->extractParts();
    if (defined($self->{RESPONSE_TYPES}->{$part})) {
	return @{$self->{RESPONSE_TYPES}->{$part}};
    } else {
	return undef;
    }
}

sub responseIds {
    my $self = shift;
    my $part = shift;

    $self->extractParts();
    if (defined($self->{RESPONSE_IDS}->{$part})) {
	return @{$self->{RESPONSE_IDS}->{$part}};
    } else {
	return undef;
    }
}

# Private function: Extracts the parts information, both part names and
# part types, and saves it. 
sub extractParts { 
    my $self = shift;
    
    return if (defined($self->{PARTS}));
    return if ($self->ext);

    $self->{PARTS} = [];

    my %parts;

    # Retrieve part count, if this is a problem
    if ($self->is_raw_problem()) {
	my $partorder = &Apache::lonnet::metadata($self->src(), 'partorder');
        my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');

	if ($partorder) {
	    my @parts;
	    for my $part (split (/,/,$partorder)) {
		if (!Apache::loncommon::check_if_partid_hidden($part, $self->{SYMB})) {
		    push @parts, $part;
		    $parts{$part} = 1;
		}
	    }
	    $self->{PARTS} = \@parts;
	} else {
	    if (!$metadata) {
		$self->{RESOURCE_ERROR} = 1;
		$self->{PARTS} = [];
		$self->{PART_TYPE} = {};
		return;
	    }
	    foreach my $entry (split(/\,/,$metadata)) {
		if ($entry =~ /^(?:part|Task)_(.*)$/) {
		    my $part = $1;
		    # This floods the logs if it blows up
		    if (defined($parts{$part})) {
			&Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->{SYMB});
		    }
		    
		    # check to see if part is turned off.
		    
		    if (!Apache::loncommon::check_if_partid_hidden($part, $self->{SYMB})) {
			$parts{$part} = 1;
		    }
		}
	    }
	    my @sortedParts = sort(keys(%parts));
	    $self->{PARTS} = \@sortedParts;
        }
        

        # These hashes probably do not need names that end with "Hash"....
        my %responseIdHash;
        my %responseTypeHash;


        # Init the responseIdHash
        foreach my $part (@{$self->{PARTS}}) {
            $responseIdHash{$part} = [];
        }

        # Now, the unfortunate thing about this is that parts, part name, and
        # response id are delimited by underscores, but both the part
        # name and response id can themselves have underscores in them.
        # So we have to use our knowlege of part names to figure out 
        # where the part names begin and end, and even then, it is possible
        # to construct ambiguous situations.
        foreach my $data (split(/,/, $metadata)) {
            if ($data =~ /^([a-zA-Z]+)response_(.*)/
		|| $data =~ /^(Task)_(.*)/) {
                my $responseType = $1;
                my $partStuff = $2;
                my $partIdSoFar = '';
                my @partChunks = split(/_/, $partStuff);
                my $i = 0;
                for ($i = 0; $i < scalar(@partChunks); $i++) {
                    if ($partIdSoFar) { $partIdSoFar .= '_'; }
                    $partIdSoFar .= $partChunks[$i];
                    if ($parts{$partIdSoFar}) {
                        my @otherChunks = @partChunks[$i+1..$#partChunks];
                        my $responseId = join('_', @otherChunks);
			if ($self->is_task()) {
			    push(@{$responseIdHash{$partIdSoFar}},
				 $partIdSoFar);
			} else {
			    push(@{$responseIdHash{$partIdSoFar}},
				 $responseId);
			}
                        push(@{$responseTypeHash{$partIdSoFar}},
			     $responseType);
                    }
                }
            }
        }
	my $resorder = &Apache::lonnet::metadata($self->src(),'responseorder');
        #
        # Reorder the arrays in the %responseIdHash and %responseTypeHash
	if ($resorder) {
	    my @resorder=split(/,/,$resorder);
	    foreach my $part (keys(%responseIdHash)) {
		my $i=0;
		my %resids = map { ($_,$i++) } @{ $responseIdHash{$part} };
		my @neworder;
		foreach my $possibleid (@resorder) {
		    if (exists($resids{$possibleid})) {
			push(@neworder,$resids{$possibleid});
		    }
		}
		my @ids;
		my @type;
		foreach my $element (@neworder) {
		    push (@ids,$responseIdHash{$part}->[$element]);
		    push (@type,$responseTypeHash{$part}->[$element]);
		}
		$responseIdHash{$part}=\@ids;
		$responseTypeHash{$part}=\@type;
	    }
	}
        $self->{RESPONSE_IDS} = \%responseIdHash;
        $self->{RESPONSE_TYPES} = \%responseTypeHash;
    }

    return;
}

=pod

=head2 Resource Status

Problem resources have status information, reflecting their various
dates and completion statuses.

There are two aspects to the status: the date-related information and
the completion information.

Idiomatic usage of these two methods would probably look something
like

 foreach my $part ($resource->parts()) {
    my $dateStatus = $resource->getDateStatus($part);
    my $completionStatus = $resource->getCompletionStatus($part);

    or

    my $status = $resource->status($part);

    ... use it here ...
 }

Which you use depends on exactly what you are looking for. The
status() function has been optimized for the nav maps display and may
not precisely match what you need elsewhere.

The symbolic constants shown below can be accessed through the
resource object: C<$res->OPEN>.

=over 4

=item * B<getDateStatus>($part):

($part defaults to 0). A convenience function that returns a symbolic
constant telling you about the date status of the part. The possible
return values are:

=back

B<Date Codes>

=over 4

=item * B<OPEN_LATER>:

The problem will be opened later.

=item * B<OPEN>:

Open and not yet due.


=item * B<PAST_DUE_ANSWER_LATER>:

The due date has passed, but the answer date has not yet arrived.

=item * B<PAST_DUE_NO_ANSWER>:

The due date has passed and there is no answer opening date set.

=item * B<ANSWER_OPEN>:

The answer date is here.

=item * B<NETWORK_FAILURE>:

The information is unknown due to network failure.

=back

=cut

# Apparently the compiler optimizes these into constants automatically
sub OPEN_LATER             { return 0; }
sub OPEN                   { return 1; }
sub PAST_DUE_NO_ANSWER     { return 2; }
sub PAST_DUE_ANSWER_LATER  { return 3; }
sub ANSWER_OPEN            { return 4; }
sub NOTHING_SET            { return 5; }
sub NETWORK_FAILURE        { return 100; }

# getDateStatus gets the date status for a given problem part. 
# Because answer date, due date, and open date are fully independent
# (i.e., it is perfectly possible to *only* have an answer date), 
# we have to completely cover the 3x3 maxtrix of (answer, due, open) x
# (past, future, none given). This function handles this with a decision
# tree. Read the comments to follow the decision tree.

sub getDateStatus {
    my $self = shift;
    my $part = shift;
    $part = "0" if (!defined($part));

    # Always return network failure if there was one.
    return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});

    my $now = time();

    my $open = $self->opendate($part);
    my $due = $self->duedate($part);
    my $answer = $self->answerdate($part);

    if (!$open && !$due && !$answer) {
        # no data on the problem at all
        # should this be the same as "open later"? think multipart.
        return $self->NOTHING_SET;
    }
    if (!$open || $now < $open) {return $self->OPEN_LATER}
    if (!$due || $now < $due) {return $self->OPEN}
    if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
    if ($answer) { return $self->ANSWER_OPEN; }
    return PAST_DUE_NO_ANSWER;
}

=pod

B<>

=over 4

=item * B<getCompletionStatus>($part):

($part defaults to 0.) A convenience function that returns a symbolic
constant telling you about the completion status of the part, with the
following possible results:

=back

B<Completion Codes>

=over 4

=item * B<NOT_ATTEMPTED>:

Has not been attempted at all.

=item * B<INCORRECT>:

Attempted, but wrong by student.

=item * B<INCORRECT_BY_OVERRIDE>:

Attempted, but wrong by instructor override.

=item * B<CORRECT>:

Correct or correct by instructor.

=item * B<CORRECT_BY_OVERRIDE>:

Correct by instructor override.

=item * B<EXCUSED>:

Excused. Not yet implemented.

=item * B<NETWORK_FAILURE>:

Information not available due to network failure.

=item * B<ATTEMPTED>:

Attempted, and not yet graded.

=item * B<CREDIT_ATTEMPTED>:

Attempted, and credit received for attempt (survey and anonymous survey only).

=item * B<INCORRECT_BY_PASSBACK>:

Attempted, but wrong for LTI Tool Provider by passback of grade

=item * B<CORRECT_BY_PASSBACK>:

Correct for LTI Tool Provider by passback of grade

=back

=cut

sub NOT_ATTEMPTED         { return 10; }
sub INCORRECT             { return 11; }
sub INCORRECT_BY_OVERRIDE { return 12; }
sub CORRECT               { return 13; }
sub CORRECT_BY_OVERRIDE   { return 14; }
sub EXCUSED               { return 15; }
sub ATTEMPTED             { return 16; }
sub CREDIT_ATTEMPTED      { return 17; }
sub INCORRECT_BY_PASSBACK { return 18; }
sub CORRECT_BY_PASSBACK   { return 19; }

sub getCompletionStatus {
    my $self = shift;
    my $part = shift;
    return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});

    my $status = $self->queryRestoreHash('solved', $part);

    # Left as separate if statements in case we ever do more with this
    if ($status eq 'correct_by_student') {return $self->CORRECT;}
    if ($status eq 'correct_by_scantron') {return $self->CORRECT;}
    if ($status eq 'correct_by_override') {
	return $self->CORRECT_BY_OVERRIDE;
    }
    if ($status eq 'correct_by_passback') {
        return $self->CORRECT_BY_PASSBACK;
    }
    if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
    if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
    if ($status eq 'incorrect_by_passback') {return $self->INCORRECT_BY_PASSBACK; }
    if ($status eq 'excused') {return $self->EXCUSED; }
    if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
    if ($status eq 'credit_attempted') {
        if ($self->is_anonsurvey($part) || $self->is_survey($part)) {
            return $self->CREDIT_ATTEMPTED;
        } else {
            return $self->ATTEMPTED;
        }
    }
    return $self->NOT_ATTEMPTED;
}

sub queryRestoreHash {
    my $self = shift;
    my $hashentry = shift;
    my $part = shift;
    $part = "0" if (!defined($part) || $part eq '');
    return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});

    $self->getReturnHash();

    return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
}

=pod

B<Composite Status>

Along with directly returning the date or completion status, the
resource object includes a convenience function B<status>() that will
combine the two status tidbits into one composite status that can
represent the status of the resource as a whole. This method represents
the concept of the thing we want to display to the user on the nav maps
screen, which is a combination of completion and open status. The precise logic is
documented in the comments of the status method. The following results
may be returned, all available as methods on the resource object
($res->NETWORK_FAILURE): In addition to the return values that match
the date or completion status, this function can return "ANSWER_SUBMITTED"
if that problemstatus parameter value is set to No, suppressing the
incorrect/correct feedback.

=over 4

=item * B<NETWORK_FAILURE>:

The network has failed and the information is not available.

=item * B<NOTHING_SET>:

No dates have been set for this problem (part) at all. (Because only
certain parts of a multi-part problem may be assigned, this can not be
collapsed into "open later", as we do not know a given part will EVER
be opened. For single part, this is the same as "OPEN_LATER".)

=item * B<CORRECT>:

For any reason at all, the part is considered correct.

=item * B<EXCUSED>:

For any reason at all, the problem is excused.

=item * B<PAST_DUE_NO_ANSWER>:

The problem is past due, not considered correct, and no answer date is
set.

=item * B<PAST_DUE_ANSWER_LATER>:

The problem is past due, not considered correct, and an answer date in
the future is set.

=item * B<ANSWER_OPEN>:

The problem is past due, not correct, and the answer is now available.

=item * B<OPEN_LATER>:

The problem is not yet open.

=item * B<TRIES_LEFT>:

The problem is open, has been tried, is not correct, but there are
tries left.

=item * B<INCORRECT>:

The problem is open, and all tries have been used without getting the
correct answer.

=item * B<OPEN>:

The item is open and not yet tried.

=item * B<ATTEMPTED>:

The problem has been attempted.

=item * B<CREDIT_ATTEMPTED>:

The problem has been attempted, and credit given for the attempt (survey and anonymous survey only).

=item * B<ANSWER_SUBMITTED>:

An answer has been submitted, but the student should not see it.

=back

=cut

sub TRIES_LEFT        { return 20; }
sub ANSWER_SUBMITTED  { return 21; }
sub PARTIALLY_CORRECT { return 22; }

sub RESERVED_LATER    { return 30; }
sub RESERVED          { return 31; }
sub RESERVED_LOCATION { return 32; }
sub RESERVABLE        { return 33; }
sub RESERVABLE_LATER  { return 34; }
sub NOTRESERVABLE     { return 35; }
sub NOT_IN_A_SLOT     { return 36; }
sub NEEDS_CHECKIN     { return 37; }
sub WAITING_FOR_GRADE { return 38; }
sub UNKNOWN           { return 39; }

sub status {
    my $self = shift;
    my $part = shift;
    if (!defined($part)) { $part = "0"; }
    my $completionStatus = $self->getCompletionStatus($part);
    my $dateStatus = $self->getDateStatus($part);

    # What we have is a two-dimensional matrix with 4 entries on one
    # dimension and 5 entries on the other, which we want to colorize,
    # plus network failure and "no date data at all".

    #if ($self->{RESOURCE_ERROR}) { return NETWORK_FAILURE; }
    if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }

    my $suppressFeedback = 0;
    if (($self->problemstatus($part) eq 'no') ||
        ($self->problemstatus($part) eq 'no_feedback_ever')) {
        $suppressFeedback = 1;
    }
    # If there's an answer date and we're past it, don't
    # suppress the feedback; student should know
    if ($self->duedate($part) && $self->duedate($part) < time() &&
	$self->answerdate($part) && $self->answerdate($part) < time()) {
	$suppressFeedback = 0;
    }

    # There are a few whole rows we can dispose of:
    if ($completionStatus == CORRECT ||
        $completionStatus == CORRECT_BY_OVERRIDE ||
        $completionStatus == CORRECT_BY_PASSBACK ) {
	if ( $suppressFeedback ) { return ANSWER_SUBMITTED }
	my $awarded=$self->awarded($part);
	if ($awarded < 1 && $awarded > 0) {
            return PARTIALLY_CORRECT;
	} elsif ($awarded<1) {
	    return INCORRECT;
	}
	return CORRECT; 
    }

    # If it's WRONG... and not open
    if ( ($completionStatus == INCORRECT || 
	  $completionStatus == INCORRECT_BY_OVERRIDE ||
	  $completionStatus == INCORRECT_BY_PASSBACK)
	 && (!$self->opendate($part) ||  $self->opendate($part) > time()) ) {
	return INCORRECT;
    }

    if ($completionStatus == ATTEMPTED) {
        return ATTEMPTED;
    }

    if ($completionStatus == CREDIT_ATTEMPTED) {
        return CREDIT_ATTEMPTED;
    }

    # If it's EXCUSED, then return that no matter what
    if ($completionStatus == EXCUSED) {
        return EXCUSED; 
    }

    if ($dateStatus == NOTHING_SET) {
        return NOTHING_SET;
    }

    # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
    # by 4 matrix (date statuses).

    if ($dateStatus == PAST_DUE_ANSWER_LATER ||
        $dateStatus == PAST_DUE_NO_ANSWER ) {
        return $suppressFeedback ? ANSWER_SUBMITTED : $dateStatus; 
    }

    if ($dateStatus == ANSWER_OPEN) {
        return ANSWER_OPEN;
    }

    # Now: (incorrect, incorrect_override, not_attempted) x 
    # (open_later), (open)
    
    if ($dateStatus == OPEN_LATER) {
        return OPEN_LATER;
    }

    # If it's WRONG...
    if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE ||
        $completionStatus == INCORRECT_BY_PASSBACK) {
        # and there are TRIES LEFT:
        if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
            return $suppressFeedback ? ANSWER_SUBMITTED : TRIES_LEFT;
        }
        return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
    }

    # Otherwise, it's untried and open
    return OPEN;
}

sub check_for_slot {
    my $self = shift;
    my $part = shift;
    my $symb = $self->{SYMB};
    my ($use_slots,$available,$availablestudent) = $self->slot_control($part);
    if (($use_slots ne '') && ($use_slots !~ /^\s*no\s*$/i)) {
        my @slots = (split(/:/,$availablestudent),split(/:/,$available));
        my $cid=$env{'request.course.id'};
        my $cdom=$env{'course.'.$cid.'.domain'};
        my $cnum=$env{'course.'.$cid.'.num'};
        my $now = time;
        my $num_usable_slots = 0;
        my ($checkedin,$checkedinslot,%consumed_uniq,%slots);
        if (@slots > 0) {
            %slots=&Apache::lonnet::get('slots',[@slots],$cdom,$cnum);
            if (&Apache::lonnet::error(%slots)) {
                return (UNKNOWN);
            }
            my @sorted_slots = &Apache::loncommon::sorted_slots(\@slots,\%slots,'starttime');
            foreach my $slot_name (@sorted_slots) {
                next if (!defined($slots{$slot_name}) || !ref($slots{$slot_name}));
                my $end = $slots{$slot_name}->{'endtime'};
                my $start = $slots{$slot_name}->{'starttime'};
                my $ip = $slots{$slot_name}->{'ip'};
                if ($self->simpleStatus() == OPEN) {
                    if ($end > $now) {
                        if ($start > $now) {
                            return (RESERVED_LATER,$start,$slot_name);
                        } else {
                            if ($ip ne '') {
                                if (!&Apache::loncommon::check_ip_acc($ip)) {
                                    return (RESERVED_LOCATION,$end,$slot_name);
                                }
                            }
                            my @proctors;
                            if ($slots{$slot_name}->{'proctor'} ne '') {
                                @proctors = split(',',$slots{$slot_name}->{'proctor'});
                            }
                            if (@proctors > 0) {
                                ($checkedin,$checkedinslot) = $self->checkedin();
                                unless ((grep(/^\Q$checkedin\E/,@proctors)) &&
                                        ($checkedinslot eq $slot_name)) {
                                    return (NEEDS_CHECKIN,$end,$slot_name); 
                                }
                            }
                            return (RESERVED,$end,$slot_name);
                        }
                    }
                } elsif ($end > $now) {
                    $num_usable_slots ++;
                }
            }
            my ($is_correct,$wait_for_grade);
            if ($self->is_task()) {
                my $taskstatus = $self->taskstatus();
                $is_correct = (($taskstatus eq 'pass') || 
                               ($self->solved() =~ /^correct_/));
                unless ($taskstatus =~ /^(?:pass|fail)$/) {
                    $wait_for_grade = 1;
                }
            } else {
                unless ($self->completable()) {
                    $wait_for_grade = 1;
                }
                unless (($self->problemstatus($part) eq 'no') ||
                        ($self->problemstatus($part) eq 'no_feedback_ever')) {
                    $is_correct = ($self->solved($part) =~ /^correct_/);
                    $wait_for_grade = 0;
                }
            }
            ($checkedin,$checkedinslot) = $self->checkedin();
            if ($checkedin) {
                if (ref($slots{$checkedinslot}) eq 'HASH') {
                    $consumed_uniq{$checkedinslot} = $slots{$checkedinslot}{'uniqueperiod'};
                }
                if ($wait_for_grade) {
                    return (WAITING_FOR_GRADE);
                } elsif ($is_correct) {
                    return (CORRECT); 
                }
            }
            if ($num_usable_slots) {
                return(NOT_IN_A_SLOT);
            }
        }
        my $reservable = &Apache::lonnet::get_reservable_slots($cnum,$cdom,$env{'user.name'},
                                                               $env{'user.domain'});
        if (ref($reservable) eq 'HASH') {
            my ($map) = &Apache::lonnet::decode_symb($symb);
            if ((ref($reservable->{'now_order'}) eq 'ARRAY') && (ref($reservable->{'now'}) eq 'HASH')) {
                foreach my $slot (reverse (@{$reservable->{'now_order'}})) {
                    my $canuse;
                    if ($reservable->{'now'}{$slot}{'symb'} eq '') {
                        $canuse = 1;
                    } else {
                        my %oksymbs;
                        my @slotsymbs = split(/\s*,\s*/,$reservable->{'now'}{$slot}{'symb'});
                        map { $oksymbs{$_} = 1; } @slotsymbs;
                        if ($oksymbs{$symb}) {
                            $canuse = 1;
                        } else {
                            foreach my $item (@slotsymbs) {
                                if ($item =~ /\.(page|sequence)$/) {
                                    (undef,undef, my $sloturl) = &Apache::lonnet::decode_symb($item);
                                    if (($map ne '') && ($map eq $sloturl)) {
                                        $canuse = 1;
                                        last;
                                    }
                                }
                            }
                        }
                    }
                    if ($canuse) {
                        if ($checkedin) {
                            if (ref($consumed_uniq{$checkedinslot}) eq 'ARRAY') {
                                my ($uniqstart,$uniqend)=@{$consumed_uniq{$checkedinslot}};
                                if ($reservable->{'now'}{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
                                    my ($new_uniq_start,$new_uniq_end) = ($1,$2);
                                    next if (!
                                        ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
                                        ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
                                }
                            }
                        }
                        return(RESERVABLE,$reservable->{'now'}{$slot}{'endreserve'});
                    }
                }
            }
            if ((ref($reservable->{'future_order'}) eq 'ARRAY') && (ref($reservable->{'future'}) eq 'HASH')) {
                foreach my $slot (@{$reservable->{'future_order'}}) {
                    my $canuse;
                    if ($reservable->{'future'}{$slot}{'symb'} eq '') {
                        $canuse = 1;
                    } elsif ($reservable->{'future'}{$slot}{'symb'} =~ /,/) {
                        my %oksymbs;
                        my @slotsymbs = split(/\s*,\s*/,$reservable->{'future'}{$slot}{'symb'});
                        map { $oksymbs{$_} = 1; } @slotsymbs;
                        if ($oksymbs{$symb}) {
                            $canuse = 1;
                        } else {
                            foreach my $item (@slotsymbs) {
                                if ($item =~ /\.(page|sequence)$/) {
                                    (undef,undef, my $sloturl) = &Apache::lonnet::decode_symb($item);
                                    if (($map ne '') && ($map eq $sloturl)) {
                                        $canuse = 1;
                                        last;
                                    }
                                }
                            }
                        }
                    } elsif ($reservable->{'future'}{$slot}{'symb'} eq $symb) {
                        $canuse = 1;
                    }
                    if ($canuse) {
                        if ($checkedin) {
                            if (ref($consumed_uniq{$checkedinslot}) eq 'ARRAY') {
                                my ($uniqstart,$uniqend)=@{$consumed_uniq{$checkedinslot}};
                                if ($reservable->{'future'}{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
                                    my ($new_uniq_start,$new_uniq_end) = ($1,$2);
                                    next if (!
                                        ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
                                        ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
                                }
                            }
                        }
                        return(RESERVABLE_LATER,$reservable->{'future'}{$slot}{'startreserve'});
                    }
                }
            }
        }
        return(NOTRESERVABLE);
    }
    return;
}

sub CLOSED { return 23; }
sub ERROR { return 24; }

=pod

B<Simple Status>

Convenience method B<simpleStatus> provides a "simple status" for the resource.
"Simple status" corresponds to "which icon is shown on the
Navmaps". There are six "simple" statuses:

=over 4

=item * B<CLOSED>: The problem is currently closed. (No icon shown.)

=item * B<OPEN>: The problem is open and unattempted.

=item * B<CORRECT>: The problem is correct for any reason.

=item * B<INCORRECT>: The problem is incorrect and can still be
completed successfully.

=item * B<ATTEMPTED>: The problem has been attempted, but the student
does not know if they are correct. (The ellipsis icon.)

=item * B<ERROR>: There is an error retrieving information about this
problem.

=back

=cut

# This hash maps the composite status to this simple status, and
# can be used directly, if you like
my %compositeToSimple = 
    (
      NETWORK_FAILURE()       => ERROR,
      NOTHING_SET()           => CLOSED,
      CORRECT()               => CORRECT,
      PARTIALLY_CORRECT()     => PARTIALLY_CORRECT,
      EXCUSED()               => CORRECT,
      PAST_DUE_NO_ANSWER()    => INCORRECT,
      PAST_DUE_ANSWER_LATER() => INCORRECT,
      ANSWER_OPEN()           => INCORRECT,
      OPEN_LATER()            => CLOSED,
      TRIES_LEFT()            => OPEN,
      INCORRECT()             => INCORRECT,
      OPEN()                  => OPEN,
      ATTEMPTED()             => ATTEMPTED,
      CREDIT_ATTEMPTED()      => CORRECT,
      ANSWER_SUBMITTED()      => ATTEMPTED
     );

sub simpleStatus {
    my $self = shift;
    my $part = shift;
    my $status = $self->status($part);
    return $compositeToSimple{$status};
}

=pod

B<simpleStatusCount> will return an array reference containing, in
this order, the number of OPEN, CLOSED, CORRECT, INCORRECT, ATTEMPTED,
and ERROR parts the given problem has.

=cut
    
# This maps the status to the slot we want to increment
my %statusToSlotMap = 
    (
     OPEN()      => 0,
     CLOSED()    => 1,
     CORRECT()   => 2,
     INCORRECT() => 3,
     ATTEMPTED() => 4,
     ERROR()     => 5
     );

sub statusToSlot { return $statusToSlotMap{shift()}; }

sub simpleStatusCount {
    my $self = shift;

    my @counts = (0, 0, 0, 0, 0, 0, 0);
    foreach my $part (@{$self->parts()}) {
	$counts[$statusToSlotMap{$self->simpleStatus($part)}]++;
    }

    return \@counts;
}

=pod

B<Completable>

The completable method represents the concept of I<whether the student can
currently do the problem>. If the student can do the problem, which means
that it is open, there are tries left, and if the problem is manually graded
or the grade is suppressed via problemstatus, the student has not tried it
yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
either the student has tried it and there is no feedback, or that for
some reason it is no longer completable (not open yet, successfully completed,
out of tries, etc.). As an example, this is used as the filter for the
"Uncompleted Homework" option for the nav maps.

If this does not quite meet your needs, do not fiddle with it (unless you are
fixing it to better match the student's conception of "completable" because
it's broken somehow)... make a new method.

=cut

sub completable {
    my $self = shift;
    if (!$self->is_problem()) { return 0; }
    my $partCount = $self->countParts();

    foreach my $part (@{$self->parts()}) {
        if ($part eq '0' && $partCount != 1) { next; }
        my $status = $self->status($part);
        # "If any of the parts are open, or have tries left (implies open),
        # and it is not "attempted" (manually graded problem), it is
        # not "complete"
	if ($self->getCompletionStatus($part) == ATTEMPTED() ||
            $self->getCompletionStatus($part) == CREDIT_ATTEMPTED() ||
	    $status == ANSWER_SUBMITTED() ) {
	    # did this part already, as well as we can
	    next;
	}
	if ($status == OPEN() || $status == TRIES_LEFT()) {
	    return 1;
	}
    }
        
    # If all the parts were complete, so was this problem.
    return 0;
}

=pod

B<Answerable>

The answerable method differs from the completable method in its handling of problem parts
for which feedback on correctness is suppressed, but the student still has tries left, and
the problem part is not past due, (i.e., the student could submit a different answer if
he/she so chose). For that case completable will return 0, whereas answerable will return 1.

=cut

sub answerable {
    my $self = shift;
    if (!$self->is_problem()) { return 0; }
    my $partCount = $self->countParts();
    foreach my $part (@{$self->parts()}) {
        if ($part eq '0' && $partCount != 1) { next; }
        my $status = $self->status($part);
        if ($self->getCompletionStatus($part) == ATTEMPTED() ||
            $self->getCompletionStatus($part) == CREDIT_ATTEMPTED() ||
            $status == ANSWER_SUBMITTED() ) {
            if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
                return 1;
            }
        }
        if ($status == OPEN() || $status == TRIES_LEFT() || $status == NETWORK_FAILURE()) {
            return 1;
        }
    }
    # None of the parts were answerable, so neither is this problem.
    return 0;
}

=pod

=head2 Resource/Nav Map Navigation

=over 4

=item * B<getNext>():

Retreive an array of the possible next resources after this
one. Always returns an array, even in the one- or zero-element case.

=item * B<getPrevious>():

Retreive an array of the possible previous resources from this
one. Always returns an array, even in the one- or zero-element case.

=cut

sub getNext {
    my $self = shift;
    my @branches;
    my $to = $self->to();
    foreach my $branch ( split(/,/, $to) ) {
        my $choice = $self->{NAV_MAP}->getById($branch);
        #if (!$choice->condition()) { next; }
        my $next = $choice->goesto();
        $next = $self->{NAV_MAP}->getById($next);

        push @branches, $next;
    }
    return \@branches;
}

sub getPrevious {
    my $self = shift;
    my @branches;
    my $from = $self->from();
    foreach my $branch ( split(/,/, $from)) {
        my $choice = $self->{NAV_MAP}->getById($branch);
        my $prev = $choice->comesfrom();
        $prev = $self->{NAV_MAP}->getById($prev);

        push @branches, $prev;
    }
    return \@branches;
}

sub browsePriv {
    my $self = shift;
    my $noblockcheck = shift;
    my $deeplinklisted = shift;
    if (defined($self->{BROWSE_PRIV})) {
        return $self->{BROWSE_PRIV};
    }
    my ($nodeeplinkcheck,$nodeeplinkout);
    if ($deeplinklisted) {
        my $deeplink = $self->deeplink(undef,'getlisted');
        if (($deeplink) && ($deeplink ne 'absent')) {
            $nodeeplinkcheck = 1;
        }
        $nodeeplinkout = 1;
    }
    $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre',$self->src(),
						    $self->{SYMB},undef,
                                                    undef,$noblockcheck,
                                                    undef,$nodeeplinkcheck,
                                                    $nodeeplinkout);
}

=pod

=back

=cut

1;

__END__



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