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

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

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