File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.305: download - view: text, annotated - select for diffs
Thu Nov 11 22:47:55 2004 UTC (19 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_1_2_99_0, HEAD
- adding use lonenc in needed places
- reenabling encrypturl in DOCS

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

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