File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.373: download - view: text, annotated - select for diffs
Sun Mar 19 19:50:40 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- domain and username migth contain more than \w

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

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