--- loncom/interface/lonnavmaps.pm 2001/01/06 20:17:33 1.5 +++ loncom/interface/lonnavmaps.pm 2004/10/07 22:12:47 1.300 @@ -1,236 +1,4713 @@ # The LearningOnline Network with CAPA # Navigate Maps Handler # -# (Page Handler +# $Id: lonnavmaps.pm,v 1.300 2004/10/07 22:12:47 albertel Exp $ # -# (TeX Content Handler +# Copyright Michigan State University Board of Trustees # -# 05/29/00,05/30 Gerd Kortemeyer) -# 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23, -# 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer) +# This file is part of the LearningOnline Network with CAPA (LON-CAPA). # -# 3/1/1,6/1 Gerd Kortemeyer +# 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/ +# +### package Apache::lonnavmaps; use strict; use Apache::Constants qw(:common :http); -use Apache::lonnet(); -use HTML::TokeParser; -use GDBM_File; +use Apache::loncommon(); +use Apache::lonmenu(); +use Apache::lonlocal; +use POSIX qw (floor strftime); +use Data::Dumper; # for debugging, not always + +# symbolic constants +sub SYMB { return 1; } +sub URL { return 2; } +sub NOTHING { return 3; } + +# Some data + +my $resObj = "Apache::lonnavmaps::resource"; -# -------------------------------------------------------------- Module Globals -my %hash; -my @rows; - -# ------------------------------------------------------------------ Euclid gcd - -sub euclid { - my ($e,$f)=@_; - my $a; my $b; my $r; - if ($e>$f) { $b=$e; $r=$f; } else { $r=$e; $b=$f; } - while ($r!=0) { - $a=$b; $b=$r; - $r=$a%$b; - } - return $b; -} - -# ------------------------------------------------------------ Build page table - -sub tracetable { - my ($sofar,$rid,$beenhere)=@_; - my $further=$sofar; - unless ($beenhere=~/\&$rid\&/) { - $beenhere.=$rid.'&'; - - if (defined($hash{'is_map_'.$rid})) { - if ((defined($hash{'map_start_'.$hash{'src_'.$rid}})) && - (defined($hash{'map_finish_'.$hash{'src_'.$rid}}))) { - my $frid=$hash{'map_finish_'.$hash{'src_'.$rid}}; - $sofar= - &tracetable($sofar,$hash{'map_start_'.$hash{'src_'.$rid}}, - '&'.$frid.'&'); - $sofar++; - if ($hash{'src_'.$frid}) { - my $brepriv=&Apache::lonnet::allowed('bre',$hash{'src_'.$frid}); - if (($brepriv eq '2') || ($brepriv eq 'F')) { - if (defined($rows[$sofar])) { - $rows[$sofar].='&'.$frid; - } else { - $rows[$sofar]=$frid; - } - } - } - } - } else { - $sofar++; - if ($hash{'src_'.$rid}) { - my $brepriv=&Apache::lonnet::allowed('bre',$hash{'src_'.$rid}); - if (($brepriv eq '2') || ($brepriv eq 'F')) { - if (defined($rows[$sofar])) { - $rows[$sofar].='&'.$rid; - } else { - $rows[$sofar]=$rid; - } - } - } - } - - if (defined($hash{'to_'.$rid})) { - my $mincond=1; - my $next=''; - map { - my $thiscond= - &Apache::lonnet::directcondval($hash{'condid_'.$hash{'undercond_'.$_}}); - if ($thiscond>=$mincond) { - if ($next) { - $next.=','.$_.':'.$thiscond; - } else { - $next=$_.':'.$thiscond; - } - if ($thiscond>$mincond) { $mincond=$thiscond; } - } - } split(/\,/,$hash{'to_'.$rid}); - map { - my ($linkid,$condval)=split(/\:/,$_); - if ($condval>=$mincond) { - my $now=&tracetable($sofar,$hash{'goesto_'.$linkid},$beenhere); - if ($now>$further) { $further=$now; } - } - } split(/\,/,$next); +# Keep these mappings in sync with lonquickgrades, which uses the colors +# instead of the icons. +my %statusIconMap = + ( + $resObj->CLOSED => '', + $resObj->OPEN => 'navmap.open.gif', + $resObj->CORRECT => 'navmap.correct.gif', + $resObj->INCORRECT => 'navmap.wrong.gif', + $resObj->ATTEMPTED => 'navmap.ellipsis.gif', + $resObj->ERROR => '' + ); - } +my %iconAltTags = + ( 'navmap.correct.gif' => 'Correct', + 'navmap.wrong.gif' => 'Incorrect', + 'navmap.open.gif' => 'Open' ); + +# 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->ANSWER_SUBMITTED => '' + ); +# And a special case in the nav map; what to do when the assignment +# is not yet done and due in less then 24 hours +my $hurryUpColor = "#FF0000"; + +sub launch_win { + my ($mode,$script,$toplinkitems)=@_; + my $result; + if ($script ne 'no') { + $result.=''; + } + if ($mode eq 'link') { + &add_linkitem($toplinkitems,'launchnav','launch_navmapwin()', + "Launch navigation window"); } - return $further; + return $result; } -# ================================================================ Main Handler +sub close { + if ($ENV{'environment.remotenavmap'} ne 'on') { return ''; } + return(< +window.status='Accessing Nav Control'; +menu=window.open("/adm/rat/empty.html","loncapanav", + "height=600,width=400,scrollbars=1"); +window.status='Closing Nav Control'; +menu.close(); +window.status='Done.'; + +ENDCLOSE +} + +sub nav_control_js { + my $nav=($ENV{'environment.remotenavmap'} eq 'on'); + return (< + +ENDUPDATE +} sub handler { - my $r=shift; + my $r = shift; + real_handler($r); +} +sub real_handler { + my $r = shift; -# ------------------------------------------- Set document type for header only + # Handle header-only request + if ($r->header_only) { + if ($ENV{'browser.mathml'}) { + &Apache::loncommon::content_type($r,'text/xml'); + } else { + &Apache::loncommon::content_type($r,'text/html'); + } + $r->send_http_header; + return OK; + } - if ($r->header_only) { - if ($ENV{'browser.mathml'}) { - $r->content_type('text/xml'); - } else { - $r->content_type('text/html'); - } - $r->send_http_header; - return OK; - } + # Send header, don't cache this page + if ($ENV{'browser.mathml'}) { + &Apache::loncommon::content_type($r,'text/xml'); + } else { + &Apache::loncommon::content_type($r,'text/html'); + } + &Apache::loncommon::no_cache($r); + $r->send_http_header; - my $requrl=$r->uri; -# ----------------------------------------------------------------- Tie db file - if ($ENV{'request.course.fn'}) { - my $fn=$ENV{'request.course.fn'}; - if (-e "$fn.db") { - if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER,0640)) { -# ------------------------------------------------------------------- Hash tied - my $firstres=$hash{'map_start_/res/'.$ENV{'request.course.uri'}}; - my $lastres=$hash{'map_finish_/res/'.$ENV{'request.course.uri'}}; - if (($firstres) && ($lastres)) { -# ----------------------------------------------------------------- Render page - - @rows=(); - - &tracetable(0,$firstres,'&'.$lastres.'&'); - if ($hash{'src_'.$lastres}) { - my $brepriv= - &Apache::lonnet::allowed('bre',$hash{'src_'.$lastres}); - if (($brepriv eq '2') || ($brepriv eq 'F')) { - $rows[$#rows+1]=''.$lastres; - } - } - -# ------------------------------------------------------------------ Page parms - - my $j; - my $i; - my $lcm=1; - my $contents=0; - -# ---------------------------------------------- Go through table to get layout - - for ($i=0;$i<=$#rows;$i++) { - if ($rows[$i]) { - $contents++; - my @colcont=split(/\&/,$rows[$i]); - $lcm*=($#colcont+1)/euclid($lcm,($#colcont+1)); - } - } - - - unless ($contents) { - $r->content_type('text/html'); - $r->send_http_header; - $r->print('Empty Map.'); - } else { -# ------------------------------------------------------------------ Build page - -# ---------------------------------------------------------------- Send headers - - $r->content_type('text/html'); - $r->send_http_header; - $r->print( - 'Navigate LON-CAPA Maps'); - - $r->print(''. - '

Navigate Course Map

'); - $r->rflush(); -# ----------------------------------------------------------------- Start table - $r->print(''); - for ($i=0;$i<=$#rows;$i++) { - if ($rows[$i]) { - $r->print("\n"); - my @colcont=split(/\&/,$rows[$i]); - my $avespan=$lcm/($#colcont+1); - for ($j=0;$j<=$#colcont;$j++) { - my $rid=$colcont[$j]; - $r->print(''); - } - $r->print(''); - } + my %toplinkitems=(); + + if ($ENV{QUERY_STRING} eq 'collapseExternal') { + &Apache::lonnet::put('environment',{'remotenavmap' => 'off'}); + &Apache::lonnet::appenv('environment.remotenavmap' => 'off'); + my $menu=&Apache::lonmenu::reopenmenu(); + my $navstatus=&Apache::lonmenu::get_nav_status(); + if ($menu) { + $menu=(<print(<<"ENDSUBM"); + + + + + + +ENDSUBM + return; + } + if ($ENV{QUERY_STRING} eq 'launchExternal') { + &Apache::lonnet::put('environment',{'remotenavmap' => 'on'}); + &Apache::lonnet::appenv('environment.remotenavmap' => 'on'); + } + + # Create the nav map + my $navmap = Apache::lonnavmaps::navmap->new(); + + if (!defined($navmap)) { + my $requrl = $r->uri; + $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized"; + return HTTP_NOT_ACCEPTABLE; + } + + $r->print("\n"); + $r->print("".&mt('Navigate Course Contents').""); +# ------------------------------------------------------------ Get query string + &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register','sort','showOnlyHomework']); + +# ----------------------------------------------------- Force menu registration + my $addentries=''; + my $more_unload; + my $body_only=''; + if ($ENV{'environment.remotenavmap'} eq 'on') { + $r->print(''); +# FIXME need to be smarter to only catch window close events +# $more_unload="collapse()" + $body_only=1; + } + if ($ENV{'form.register'}) { + $addentries=' onLoad="'.&Apache::lonmenu::loadevents(). + '" onUnload="'.&Apache::lonmenu::unloadevents().';'. + $more_unload.'"'; + $r->print(&Apache::lonmenu::registerurl(1)); + } else { + $addentries=' onUnload="'.$more_unload.'"'; + } + + # Header + $r->print(''. + &Apache::loncommon::bodytag('Navigate Course Contents','', + $addentries,$body_only,'', + $ENV{'form.register'})); + $r->print(''); + + $r->rflush(); + + # Check that it's defined + if (!($navmap->courseMapDefined())) { + $r->print(&Apache::loncommon::help_open_menu('','Navigation Screen','Navigation_Screen','',undef,'RAT')); + $r->print('Coursemap undefined.' . + ''); + return OK; + } + + # See if there's only one map in the top-level, if we don't + # already have a filter... if so, automatically display it + # (older code; should use retrieveResources) + if ($ENV{QUERY_STRING} !~ /filter/) { + my $iterator = $navmap->getIterator(undef, undef, undef, 0); + my $curRes; + my $sequenceCount = 0; + my $sequenceId; + while ($curRes = $iterator->next()) { + if (ref($curRes) && $curRes->is_sequence()) { + $sequenceCount++; + $sequenceId = $curRes->map_pc(); + } + } + + if ($sequenceCount == 1) { + # The automatic iterator creation in the render call + # will pick this up. We know the condition because + # the defined($ENV{'form.filter'}) also ensures this + # is a fresh call. + $ENV{'form.filter'} = "$sequenceId"; + } + } + + if ($ENV{QUERY_STRING} eq 'launchExternal') { + $r->print(' +
+ '); + $r->print(' + '); + } + + if ($ENV{'environment.remotenavmap'} ne 'on') { + $r->print(&launch_win('link','yes',\%toplinkitems)); + } + if ($ENV{'environment.remotenavmap'} eq 'on') { + &add_linkitem(\%toplinkitems,'closenav','collapse()', + "Close navigation window"); + } + + my $jumpToFirstHomework = 0; + # Check to see if the student is jumping to next open, do-able problem + if ($ENV{QUERY_STRING} =~ /^jumpToFirstHomework/) { + $jumpToFirstHomework = 1; + # Find the next homework problem that they can do. + my $iterator = $navmap->getIterator(undef, undef, undef, 1); + my $curRes; + my $foundDoableProblem = 0; + my $problemRes; + + while (($curRes = $iterator->next()) && !$foundDoableProblem) { + if (ref($curRes) && $curRes->is_problem()) { + my $status = $curRes->status(); + if ($curRes->completable()) { + $problemRes = $curRes; + $foundDoableProblem = 1; + + # Pop open all previous maps + my $stack = $iterator->getStack(); + pop @$stack; # last resource in the stack is the problem + # itself, which we don't need in the map stack + my @mapPcs = map {$_->map_pc()} @$stack; + $ENV{'form.filter'} = join(',', @mapPcs); + + # Mark as both "here" and "jump" + $ENV{'form.postsymb'} = $curRes->symb(); + } + } + } + + # If we found no problems, print a note to that effect. + if (!$foundDoableProblem) { + $r->print("All homework assignments have been completed.

"); + } + } else { + &add_linkitem(\%toplinkitems,'firsthomework', + 'location.href="navmaps?jumpToFirstHomework"', + "Show Me My First Homework Problem"); + } + + my $suppressEmptySequences = 0; + my $filterFunc = undef; + my $resource_no_folder_link = 0; + + # Display only due homework. + my $showOnlyHomework = 0; + if ($ENV{'form.showOnlyHomework'} eq "1") { + $showOnlyHomework = 1; + $suppressEmptySequences = 1; + $filterFunc = sub { my $res = shift; + return $res->completable() || $res->is_map(); + }; + &add_linkitem(\%toplinkitems,'everything', + 'location.href="navmaps?sort='.$ENV{'form.sort'}.'"', + "Show Everything"); + $r->print("

".&mt("Uncompleted Homework")."

"); + $ENV{'form.filter'} = ''; + $ENV{'form.condition'} = 1; + $resource_no_folder_link = 1; + } else { + &add_linkitem(\%toplinkitems,'uncompleted', + 'location.href="navmaps?sort='.$ENV{'form.sort'}. + '&showOnlyHomework=1"', + "Show Only Uncompleted Homework"); + } + + my %selected=($ENV{'form.sort'} => 'selected=on'); + my $sort_html=("
+ + + + + + "); + # renderer call + my $renderArgs = { 'cols' => [0,1,2,3], + 'sort' => $ENV{'form.sort'}, + 'url' => '/adm/navmaps', + 'navmap' => $navmap, + 'suppressNavmap' => 1, + 'suppressEmptySequences' => $suppressEmptySequences, + 'filterFunc' => $filterFunc, + 'resource_no_folder_link' => $resource_no_folder_link, + 'sort_html'=> $sort_html, + 'r' => $r, + 'caller' => 'navmapsdisplay', + 'linkitems' => \%toplinkitems}; + my $render = render($renderArgs); + + # If no resources were printed, print a reassuring message so the + # user knows there was no error. + if ($renderArgs->{'counter'} == 0) { + if ($showOnlyHomework) { + $r->print("

".&mt("All homework is currently completed").".

"); + } else { # both jumpToFirstHomework and normal use the same: course must be empty + $r->print("

This course is empty.

"); + } + } + + $r->print(""); + $r->rflush(); + + return OK; +} + +# 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 +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)); +} + +# Convenience function: Given a stack returned from getStack on the iterator, +# return the correct src() value. +# Later, this should add an anchor when we start putting anchors in pages. +sub getLinkForResource { + my $stack = shift; + my $res; + + # Check to see if there are any pages in the stack + foreach $res (@$stack) { + if (defined($res)) { + if ($res->is_page()) { + return $res->src(); + } + # in case folder was skipped over as "only sequence" + my ($map,$id,$src)=&Apache::lonnet::decode_symb($res->symb()); + if ($map=~/\.page$/) { + return &Apache::lonnet::clutter($map).'#'. + &Apache::lonnet::escape(&Apache::lonnet::declutter($src)); + } + } + } + + # 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 (@$stack) { + if (defined($_)) { $res = $_; } + } + + return $res->src(); +} + +# 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. + +sub getDescription { + my $res = shift; + my $part = shift; + my $status = $res->status($part); + + if ($status == $res->NETWORK_FAILURE) { + return &mt("Having technical difficulties; please check status later"); + } + if ($status == $res->NOTHING_SET) { + return &mt("Not currently assigned."); + } + if ($status == $res->OPEN_LATER) { + return "Open " . timeToHumanString($res->opendate($part)); + } + if ($status == $res->OPEN) { + if ($res->duedate($part)) { + return &mt("Due")." " .timeToHumanString($res->duedate($part)); + } else { + return &mt("Open, no due date"); + } + } + if ($status == $res->PAST_DUE_ANSWER_LATER) { + return &mt("Answer open")." " . timeToHumanString($res->answerdate($part)); + } + if ($status == $res->PAST_DUE_NO_ANSWER) { + return &mt("Was due")." " . timeToHumanString($res->duedate($part)); + } + if ($status == $res->ANSWER_OPEN) { + return &mt("Answer available"); + } + if ($status == $res->EXCUSED) { + return &mt("Excused by instructor"); + } + if ($status == $res->ATTEMPTED) { + return &mt("Answer submitted, not yet graded"); + } + if ($status == $res->TRIES_LEFT) { + my $tries = $res->tries($part); + my $maxtries = $res->maxtries($part); + my $triesString = ""; + if ($tries && $maxtries) { + $triesString = "($tries of $maxtries tries used)"; + if ($maxtries > 1 && $maxtries - $tries == 1) { + $triesString = "$triesString"; + } + } + if ($res->duedate($part)) { + return &mt("Due")." " . timeToHumanString($res->duedate($part)) . + " $triesString"; + } else { + return &mt("No due date")." $triesString"; + } + } + if ($status == $res->ANSWER_SUBMITTED) { + return &mt('Answer submitted'); + } +} + +# Convenience function, so others can use it: Is the problem due in less then +# 24 hours, and still can be done? + +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(); +} + +# Convenience function, so others can use it: Is there only one try remaining for the +# part, with more then one try to begin with, not due yet and still can be done? +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(); +} + +# This puts a human-readable name on the ENV variable. + +sub advancedUser { + return $ENV{'request.role.adv'}; +} + + +# timeToHumanString takes a time number and converts it to a +# human-readable representation, meant to be used in the following +# manner: +# print "Due $timestring" +# print "Open $timestring" +# print "Answer available $timestring" +# Very, very, very, VERY English-only... goodness help a localizer on +# this func... +sub timeToHumanString { + my ($time) = @_; + # 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(); + + my @time = localtime($time); + my @now = localtime($now); + + # 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 then a minute + if ( $delta < $minute ) { + if ($delta == 1) { return "${prefix}1 second$tense"; } + return "$prefix$delta seconds$tense"; + } - $r->print(''); -# -------------------------------------------------------------------- End page - } -# ------------------------------------------------------------- End render page - } else { - $r->content_type('text/html'); - $r->send_http_header; - $r->print('Coursemap undefined.'); - } -# ------------------------------------------------------------------ Untie hash - unless (untie(%hash)) { - &Apache::lonnet::logthis("WARNING: ". - "Could not untie coursemap $fn (browse)."); - } -# -------------------------------------------------------------------- All done - return OK; -# ----------------------------------------------- Errors, hash could no be tied - } - } - } + # Less then an hour + if ( $delta < $hour ) { + # If so, use minutes + my $minutes = floor($delta / 60); + if ($minutes == 1) { return "${prefix}1 minute$tense"; } + return "$prefix$minutes minutes$tense"; + } + + # Is it less then 24 hours away? If so, + # display hours + minutes + 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 = ""; + } + return "$prefix$hourString$minuteString$tense"; + } - $ENV{'user.error.msg'}="$requrl:bre:0:0:Course not initialized"; - return HTTP_NOT_ACCEPTABLE; + # Less then 5 days away, display day of the week and + # HH:MM + if ( $delta < $day * 5 ) { + my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time)); + $timeStr =~ s/12:00 am/00:00/; + $timeStr =~ s/12:00 pm/noon/; + return ($inPast ? "last " : "next ") . + $timeStr; + } + + # Is it this year? + if ( $time[5] == $now[5]) { + # Return on Month Day, HH:MM meridian + my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time)); + $timeStr =~ s/12:00 am/00:00/; + $timeStr =~ s/12:00 pm/noon/; + return $timeStr; + } + + # Not this year, so show the year + my $timeStr = strftime("on %A, %b %e %Y at %I:%M %P", localtime($time)); + $timeStr =~ s/12:00 am/00:00/; + $timeStr =~ s/12:00 pm/noon/; + return $timeStr; + } +} + + +=pod + +=head1 NAME + +Apache::lonnavmap - Subroutines to handle and render the navigation + maps + +=head1 SYNOPSIS + +The main handler generates the navigational listing for the course, +the other objects export this information in a usable fashion for +other modules. + +=head1 OVERVIEW + +X 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. You can see it if you are logged into +LON-CAPA, in a course, by going to /adm/test. (You may need to +tweak the /home/httpd/lonTabs/htpasswd file to view it.) The +content of the hash will be under the heading "Big Hash". + +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 then directly manipulating +the hash. It also provides access to several auxilary 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: Apache::lonnavmaps I works for the "currently +logged in user"; if you want things like "due dates for another +student" lonnavmaps can not directly retrieve information like +that. You need the EXT function. This module can still help, +because many things, such as the course structure, are 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 by + +=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 is 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 +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: + +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
'; } + return ''; + } + +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: 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: 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: 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: 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: default: empty (useless) + +An array reference + +=item * B: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: 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: 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: default: empty string + +A Symb identifying where to place the 'here' marker. The empty +string means no marker. + +=item * B: default: 25 pixel whitespace image + +A string identifying the indentation string to use. + +=item * B: 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: 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: 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: default: false + +If true, print the key that appears on the top of the standard +navmaps. + +=item * B: default: true + +If true, print the "Close all folders" or "open all folders" +links. + +=item * B: 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: 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"; + } else { + $result .= " $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText"; + } + + return $result; +} + +sub render_communication_status { + my ($resource, $part, $params) = @_; + my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = ""; + + my $link = $params->{"resourceLink"}; + my $linkopen = ""; + my $linkclose = ""; + my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc"); + if ($resource->hasDiscussion()) { + $discussionHTML = $linkopen . + '' . + $linkclose; + } + + if ($resource->getFeedback()) { + my $feedback = $resource->getFeedback(); + foreach (split(/\,/, $feedback)) { + if ($_) { + $feedbackHTML .= ' ' + . ''; + } + } + } + + if ($resource->getErrors()) { + my $errors = $resource->getErrors(); + my $errorcount = 0; + foreach (split(/,/, $errors)) { + last if ($errorcount>=10); # Only output 10 bombs maximum + if ($_) { + $errorcount++; + $errorHTML .= ' ' + . ''; + } + } + } + + if ($params->{'multipart'} && $part != '0') { + $discussionHTML = $feedbackHTML = $errorHTML = ''; + } + + return ""; + +} +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 = ""; + my $linkclose = ""; + + if ($resource->is_problem() && + !$firstDisplayed) { + + my $icon = $statusIconMap{$resource->simpleStatus($part)}; + my $alt = $iconAltTags{$icon}; + if ($icon) { + my $location= + &Apache::loncommon::lonhttpdurl("/adm/lonIcons/$icon"); + $result .= "\n"; + } else { + $result .= "\n"; + } + } else { # not problem, no icon + $result .= "\n"; + } + + return $result; +} +sub render_long_status { + my ($resource, $part, $params) = @_; + my $result = "\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); + +use Data::Dumper; +sub render_parts_summary_status { + my ($resource, $part, $params) = @_; + if (!$resource->is_problem() && !$resource->contains_problem) { return ''; } + if ($params->{showParts}) { + return ''; + } + + my $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.="" . $overallstatus{$status} . ' ' + . $statusStrings{$status} . ""; + } + } + $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 $mustCloseNavMap = 0; + 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 (split(/\,/, $ENV{"form.filter"})) { + if ($_) { + $filterHash->{$_} = "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() && + &$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(); + $mustCloseNavMap = 1; + } + + # 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'}) { + $here = $jump = $ENV{'form.postsymb'}; + } elsif ($ENV{'form.postdata'}) { + # couldn't find a symb, is there a URL? + my $currenturl = $ENV{'form.postdata'}; + #$currenturl=~s/^http\:\/\///; + #$currenturl=~s/^[^\/]+//; + + $here = $jump = &Apache::lonnet::symbread($currenturl); + } + + # 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(); + $mustCloseNavMap = 1; + } + + # See if we're being passed a specific map + if ($args->{'iterator_map'}) { + my $map = $args->{'iterator_map'}; + $map = $navmap->getResourceByUrl($map); + my $firstResource = $map->map_start(); + my $finishResource = $map->map_finish(); + + $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition); + } else { + $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition); + } + } + + # (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 .= '
'. - $hash{'title_'.$rid}.''); - $r->print('
' . $resource->{ID} . ' ' . $part . '' . $resource->{ID} . '"; + + 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'} ) { + $curMarkerBegin = '> '; + $curMarkerEnd = '<'; + $params->{'displayedHereMarker'} = 1; + } + + if ($resource->is_problem() && $part ne '0' && + !$params->{'condensed'}) { + my $displaypart=$resource->part_display($part); + $partLabel = " (Part: $displaypart)"; + $link.='#'.&Apache::lonnet::escape($part); + $title = ""; + } + + if ($params->{'condensed'} && $resource->countParts() > 1) { + $nonLinkedText .= ' (' . $resource->countParts() . ' parts)'; + } + + my $target; + if ($ENV{'environment.remotenavmap'} eq 'on') { + $target=' target="loncapaclient" '; + } + if (!$params->{'resource_nolink'} && !$resource->is_sequence() && !$resource->is_empty_sequence) { + $result .= " $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText$discussionHTML$feedbackHTML$errorHTML $linkopen$alt$linkclose  \n"; + my $firstDisplayed = !$params->{'condensed'} && + $params->{'multipart'} && $part eq "0"; + + my $color; + if ($resource->is_problem()) { + $color = $colormap{$resource->status}; + + if (dueInLessThan24Hours($resource, $part) || + lastTry($resource, $part)) { + $color = $hurryUpColor; + } + } + + if ($resource->kind() eq "res" && + $resource->is_problem() && + !$firstDisplayed) { + if ($color) {$result .= ""; } + $result .= getDescription($resource, $part); + if ($color) {$result .= ""; } + } + if ($resource->is_map() && advancedUser() && $resource->randompick()) { + $result .= '(randomly select ' . $resource->randompick() .')'; + } + + # Debugging code + #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) . + # ' - Part: ' . $part; + + $result .= "\n"; + my $endtd = "
'; + my $date=localtime; + $result.=''; + my $location=&Apache::loncommon::lonhttpdurl("/adm/lonMisc"); + if ($navmap->{LAST_CHECK}) { + $result .= + ' '.&mt('New discussion since').' '. + strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})). + ''; + } else { + $result .= ''; + } + + $result .= '
Key:    '. + ' '.&mt('New message (click to open)').'

'. + '

  '. + ' '.&mt('Discussions').''. + '   '.&mt('New message (click to open)'). + '
'; + } + + if ($printCloseAll && !$args->{'resource_no_folder_link'}) { + my ($link,$text); + if ($condition) { + $link='"navmaps?condition=0&filter=&'.$queryString. + '&here='.&Apache::lonnet::escape($here).'"'; + $text='Close All Folders'; + } else { + $link='"navmaps?condition=1&filter=&'.$queryString. + '&here='.&Apache::lonnet::escape($here).'"'; + $text='Open All Folders'; + } + if ($args->{'caller'} eq 'navmapsdisplay') { + &add_linkitem($args->{'linkitems'},'changefolder', + 'location.href='.$link,$text); + } else { + $result.=''.&mt($text).''; + } + $result .= "\n"; + } + + # Check for any unread discussions in all resources. + if ($args->{'caller'} eq 'navmapsdisplay') { + &add_linkitem($args->{'linkitems'},'clearbubbles', + 'document.clearbubbles.submit()', + 'Mark all posts read'); + my $time=time; + $result .= (< + + +END + if ($args->{'sort'} eq 'discussion') { + my $totdisc = 0; + my $haveDisc = ''; + my @allres=$navmap->retrieveResources(); + foreach my $resource (@allres) { + if ($resource->hasDiscussion()) { + my $ressymb; + if ($resource->symb() =~ m-(___adm/\w+/\w+)/(\d+)/bulletinboard$-) { + $ressymb = 'bulletin___'.$2.$1.'/'.$2.'/bulletinboard'; + } else { + $ressymb = $resource->symb(); + } + $haveDisc .= $ressymb.':'; + $totdisc ++; + } + } + if ($totdisc > 0) { + $haveDisc =~ s/:$//; + $result .= (< + +END + } + } + $result.=''; + } + + if ($args->{'caller'} eq 'navmapsdisplay') { + $result .= ''; + if ($ENV{'environment.remotenavmap'} ne 'on') { + $result .= ''; + } else { + $result .= ''; + } + $result.=&show_linkitems($args->{'linkitems'}); + if ($args->{'sort_html'}) { + if ($ENV{'environment.remotenavmap'} ne 'on') { + $result.=''. + ''; + } else { + $result.=''; + } + } + $result .= '
'. + &Apache::loncommon::help_open_menu('','Navigation Screen','Navigation_Screen','',undef,'RAT').' 
   '.$args->{'sort_html'}.'

'. + $args->{'sort_html'}.'
'; + } elsif ($args->{'sort_html'}) { + $result.=$args->{'sort_html'}; + } + + $result .= "
\n"; + if ($r) { + $r->print($result); + $r->rflush(); + $result = ""; + } + # End parameter setting + + # Data + $result .= '' ."\n"; + my $res = "Apache::lonnavmaps::resource"; + my %condenseStatuses = + ( $res->NETWORK_FAILURE => 1, + $res->NOTHING_SET => 1, + $res->CORRECT => 1 ); + my @backgroundColors = ("#FFFFFF", "#F6F6F6"); + + # Shared variables + $args->{'counter'} = 0; # counts the rows + $args->{'indentLevel'} = 0; + $args->{'isNewBranch'} = 0; + $args->{'condensed'} = 0; + my $location= + &Apache::loncommon::lonhttpdurl("/adm/lonIcons/whitespace1.gif"); + $args->{'indentString'} = setDefault($args->{'indentString'}, ""); + $args->{'displayedHereMarker'} = 0; + + # If we're suppressing empty sequences, look for them here. Use DFS for speed, + # since structure actually doesn't matter, except what map has what resources. + if ($args->{'suppressEmptySequences'}) { + 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. + } else { + # 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'}); + } + + + 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 + if ($curRes->is_map() && $args->{'suppressEmptySequences'} && + !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) { + 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 (!$curRes->opendate("0")) { + @parts = (); + $args->{'condensed'} = 1; + } + 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 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'; + } + + # Now, we've decided what parts to show. Loop through them and + # show them. + foreach my $part (@parts) { + $rownum ++; + my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)]; + + $result .= " \n"; + + # Set up some data about the parts that the cols might want + my $filter = $it->{FILTER}; + my $src; + if ($args->{'sort'}) { + $src = $curRes->src(); # FIXME this is wrong for .pages + } else { + my $stack = $it->getStack(); + $src=getLinkForResource($stack); + } + my $anchor=''; + if ($src=~s/(\#.*)$//) { + $anchor=$1; + } + my $srcHasQuestion = $src =~ /\?/; + $args->{"resourceLink"} = $src. + ($srcHasQuestion?'&':'?') . + 'symb=' . &Apache::lonnet::escape($curRes->symb()). + $anchor; + + # 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 \n"; + $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 ''; + } + } + } + + # 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 .= " +"; + } + + $result .= "
tag; + # necessary for valid HTML (which Mozilla requires) + $colHTML =~ s/\>/\>\/; + $displayedJumpMarker = 1; + } + $result .= $colHTML . "\n"; + } + $result .= "
"; + + 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 { + my ($linkitems)=@_; + my @linkorder = ("launchnav","closenav","firsthomework","everything", + "uncompleted","changefolder","clearbubbles"); + + my $result .= (< + +
+   +
'."\n"; + + return $result; } 1; -__END__ +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-EgetByX>, where X is B, B, B or B. 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, + not your first choice; it only 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. + +=item * CretrieveResources(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-EgetIterator(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 * Bnew>(): + +Creates a new navmap object. Returns the navmap object if this is +successful, or B if not. + +=back + +=head2 Methods + +=over 4 + +=item * B(first, finish, filter, condition): + +See iterator documentation below. + +=cut + +use strict; +use GDBM_File; + +sub new { + # magic invocation to create a class instance + my $proto = shift; + my $class = ref($proto) || $proto; + my $self = {}; + + # 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; + + # 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} = {}; + + bless($self); + + return $self; +} + +sub generate_course_user_opt { + my $self = shift; + if ($self->{COURSE_USER_OPT_GENERATED}) { return; } + + my $uname=$ENV{'user.name'}; + my $udom=$ENV{'user.domain'}; + my $uhome=$ENV{'user.home'}; + my $cid=$ENV{'request.course.id'}; + my $chome=$ENV{'course.'.$cid.'.home'}; + my ($cdom,$cnum)=split(/\_/,$cid); + + my $userprefix=$uname.'_'.$udom.'_'; + + my %courserdatas; my %useropt; my %courseopt; my %userrdatas; + unless ($uhome eq 'no_host') { +# ------------------------------------------------- Get coursedata (if present) + unless ((time-$courserdatas{$cid.'.last_cache'})<240) { + my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum. + ':resourcedata',$chome); + # Check for network failure + if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) { + $self->{NETWORK_FAILURE} = 1; + } elsif ($reply!~/^error\:/) { + $courserdatas{$cid}=$reply; + $courserdatas{$cid.'.last_cache'}=time; + } + } + foreach (split(/\&/,$courserdatas{$cid})) { + my ($name,$value)=split(/\=/,$_); + $courseopt{$userprefix.&Apache::lonnet::unescape($name)}= + &Apache::lonnet::unescape($value); + } +# --------------------------------------------------- Get userdata (if present) + unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) { + my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome); + if ($reply!~/^error\:/) { + $userrdatas{$uname.'___'.$udom}=$reply; + $userrdatas{$uname.'___'.$udom.'.last_cache'}=time; + } + # check to see if network failed + elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i ) + { + $self->{NETWORK_FAILURE} = 1; + } + } + foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) { + my ($name,$value)=split(/\=/,$_); + $useropt{$userprefix.&Apache::lonnet::unescape($name)}= + &Apache::lonnet::unescape($value); + } + $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,$cnum)=split(/\_/,$cid); + + my %emailstatus = &Apache::lonnet::dump('email_status'); + 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', + $ENV{'user.domain'},$ENV{'user.name'},'lastread'); + my %lastreadtime = (); + foreach (keys %lastread) { + my $key = $_; + $key =~ s/_lastread$//; + $lastreadtime{$key} = $lastread{$_}; + } + + my %feedback=(); + my %error=(); + my $keys = &Apache::lonnet::reply('keys:'. + $ENV{'user.domain'}.':'. + $ENV{'user.name'}.':nohist_email', + $ENV{'user.home'}); + + foreach my $msgid (split(/\&/, $keys)) { + $msgid=&Apache::lonnet::unescape($msgid); + if ((!$emailstatus{$msgid}) || ($emailstatus{$msgid} eq 'new')) { + my $plain= + &Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid)); + if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) { + my ($what,$url)=($1,$2); + if ($what eq 'Error') { + $error{$url}.=','.$msgid; + } else { + $feedback{$url}.=','.$msgid; + } + } + } + } + + #url's of resources that have feedbacks + $self->{FEEDBACK} = \%feedback; + #or errors + $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'}, + $ENV{'user.domain'}, + $ENV{'user.name'}); + $self->{STUDENT_DATA} = \%student_data; + + $self->{RETRIEVED_USER_DATA} = 1; +} + +# 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(): 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