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

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

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