File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.390: download - view: text, annotated - select for diffs
Tue Jul 25 00:57:51 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: version_2_2_X, version_2_2_2, version_2_2_1, version_2_2_0, version_2_1_99_3, version_2_1_99_2, HEAD
- interval needs to have a value for us to care about it

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

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