File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.374: download - view: text, annotated - select for diffs
Thu Mar 23 22:32:10 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
-start_page
-eliminate calls to bodytag in favor of start_page
- elimintate call to xmlbegin

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

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