Annotation of loncom/interface/lonnavmaps.pm, revision 1.278

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

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