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

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

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