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

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

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