File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.349.2.2: download - view: text, annotated - select for diffs
Mon Dec 5 21:37:19 2005 UTC (18 years, 5 months ago) by albertel
Branches: version_2_1_X
- backport 1.352 1.353

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

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