File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.382: download - view: text, annotated - select for diffs
Mon May 15 19:29:03 2006 UTC (18 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4758 due date should beat interval

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

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