File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.63: download - view: text, annotated - select for diffs
Thu Oct 3 19:40:33 2002 UTC (21 years, 8 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Folders default to being closed, allowing us to save the time processing
the non-showing information.

Putting off displaying the current position because it's hard to find the
current position; I need to be able to scan up the maps backwards and I don't
think I can do that with the data in the nav hash (not sure).

    1: # The LearningOnline Network with CAPA
    2: # Navigate Maps Handler
    3: #
    4: # $Id: lonnavmaps.pm,v 1.63 2002/10/03 19:40:33 bowersj2 Exp $
    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: #
   28: # (Page Handler
   29: #
   30: # (TeX Content Handler
   31: #
   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)
   35: #
   36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
   37: # YEAR=2002
   38: # 1/1 Gerd Kortemeyer
   39: #
   40: 
   41: package Apache::lonnavmaps;
   42: 
   43: use strict;
   44: use Apache::Constants qw(:common :http);
   45: use Apache::lonnet();
   46: use Apache::loncommon();
   47: use HTML::TokeParser;
   48: use GDBM_File;
   49: 
   50: # -------------------------------------------------------------- Module Globals
   51: my %hash;
   52: my @rows;
   53: 
   54: #
   55: # These cache hashes need to be independent of user, resource and course
   56: # (user and course can/should be in the keys)
   57: #
   58: 
   59: my %courserdatas;
   60: my %userrdatas;
   61: 
   62: #
   63: # These global hashes are dependent on user, course and resource, 
   64: # and need to be initialized every time when a sheet is calculated
   65: #
   66: my %courseopt;
   67: my %useropt;
   68: my %parmhash;
   69: 
   70: # This parameter keeps track of whether obtaining the user's information
   71: # failed, which the colorizer in astatus can use
   72: my $networkFailedFlag = 0;
   73: 
   74: # ------------------------------------------------------------------ Euclid gcd
   75: 
   76: sub euclid {
   77:     my ($e,$f)=@_;
   78:     my $a; my $b; my $r;
   79:     if ($e>$f) { $b=$e; $r=$f; } else { $r=$e; $b=$f; }
   80:     while ($r!=0) {
   81:         $a=$b; $b=$r;
   82:         $r=$a%$b;
   83:     }
   84:     return $b;
   85: }
   86: 
   87: # --------------------------------------------------------------------- Parmval
   88: 
   89: # -------------------------------------------- Figure out a cascading parameter
   90: #
   91: # For this function to work
   92: #
   93: # * parmhash needs to be tied
   94: # * courseopt and useropt need to be initialized for this user and course
   95: #
   96: 
   97: sub parmval {
   98:     my ($what,$symb)=@_;
   99:     my $cid=$ENV{'request.course.id'};
  100:     my $csec=$ENV{'request.course.sec'};
  101:     my $uname=$ENV{'user.name'};
  102:     my $udom=$ENV{'user.domain'};
  103: 
  104:     unless ($symb) { return ''; }
  105:     my $result='';
  106: 
  107:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
  108: 
  109: # ----------------------------------------------------- Cascading lookup scheme
  110:     my $rwhat=$what;
  111:     $what=~s/^parameter\_//;
  112:     $what=~s/\_/\./;
  113: 
  114:     my $symbparm=$symb.'.'.$what;
  115:     my $mapparm=$mapname.'___(all).'.$what;
  116:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
  117: 
  118:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
  119:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
  120:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
  121: 
  122:     my $courselevel= $usercourseprefix.'.'.$what;
  123:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
  124:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
  125: 
  126: # ---------------------------------------------------------- first, check user
  127:     if (defined($uname)) {
  128:         if (defined($useropt{$courselevelr})) { return $useropt{$courselevelr}; }
  129:         if (defined($useropt{$courselevelm})) { return $useropt{$courselevelm}; }
  130:         if (defined($useropt{$courselevel})) { return $useropt{$courselevel}; }
  131:     }
  132: 
  133: # ------------------------------------------------------- second, check course
  134:     if (defined($csec)) {
  135:         if (defined($courseopt{$seclevelr})) { return $courseopt{$seclevelr}; }
  136:         if (defined($courseopt{$seclevelm})) { return $courseopt{$seclevelm}; }
  137:         if (defined($courseopt{$seclevel})) { return $courseopt{$seclevel}; }
  138:     }
  139: 
  140:     if (defined($courseopt{$courselevelr})) { return $courseopt{$courselevelr}; }
  141:     if (defined($courseopt{$courselevelm})) { return $courseopt{$courselevelm}; }
  142:     if (defined($courseopt{$courselevel})) { return $courseopt{$courselevel}; }
  143: 
  144: # ----------------------------------------------------- third, check map parms
  145: 
  146:     my $thisparm=$parmhash{$symbparm};
  147:     if (defined($thisparm)) { return $thisparm; }
  148: 
  149: # ----------------------------------------------------- fourth , check default
  150: 
  151:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
  152:     if (defined($default)) { return $default}
  153: 
  154: # --------------------------------------------------- fifth , cascade up parts
  155: 
  156:     my ($space,@qualifier)=split(/\./,$rwhat);
  157:     my $qualifier=join('.',@qualifier);
  158:     unless ($space eq '0') {
  159:         my ($part,$id)=split(/\_/,$space);
  160:         if ($id) {
  161:             my $partgeneral=&parmval($part.".$qualifier",$symb);
  162:             if (defined($partgeneral)) { return $partgeneral; }
  163:         } else {
  164:             my $resourcegeneral=&parmval("0.$qualifier",$symb);
  165:             if (defined($resourcegeneral)) { return $resourcegeneral; }
  166:         }
  167:     }
  168:     return '';
  169: }
  170: 
  171: 
  172: 
  173: # ------------------------------------------------------------- Find out status
  174: # return codes
  175: # tcode (timecode)
  176: # 1: will open later
  177: # 2: is open and not past due yet
  178: # 3: is past due date
  179: # 4: due in the next 24 hours
  180: #
  181: # code (curent solved status)
  182: # 1: not attempted
  183: # 2: attempted but wrong, or incorrect by instructor
  184: # 3: solved or correct by instructor
  185: # 4: partially correct (one or more parts correct)
  186: # "excused" needs to be supported, but is not yet.
  187: sub astatus {
  188:     my $rid=shift;
  189:     my $code=0;
  190:     my $ctext='';
  191:     $rid=~/(\d+)\.(\d+)/;
  192:     my $symb=&Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.
  193:         &Apache::lonnet::declutter($hash{'src_'.$rid});
  194:     my %duedate=();
  195:     my %opendate=();
  196:     my %answerdate=();
  197:     # need to always check part 0's open/due/answer status
  198:     foreach (sort(split(/\,/,&Apache::lonnet::metadata($hash{'src_'.$rid},'allpo\ssiblekeys')))) {
  199:         if ($_=~/^parameter\_(.*)\_opendate$/) {
  200:             my $part=$1;
  201:             $duedate{$part}=&parmval($part.'.duedate',$symb);
  202:             $opendate{$part}=&parmval($part.'.opendate',$symb);
  203:             $answerdate{$part}=&parmval($part.'.answerdate',$symb);
  204:             if (&parmval($part.'.opendate.type',$symb) eq 'date_interval') {
  205:                 $opendate{$part}=$duedate{$part}-$opendate{$part};
  206:             }
  207:             if (&parmval($part.'.answerdate.type',$symb) eq 'date_interval') {
  208:                 $answerdate{$part}=$duedate{$part}+$answerdate{$part};
  209:             }
  210:         }
  211:     }
  212:     my $now=time;
  213:     my $tcode=0;
  214: 
  215:     my %returnhash=&Apache::lonnet::restore($symb);
  216: 
  217:     foreach (sort(keys(%opendate))) {
  218:         my $duedate=$duedate{$_};
  219:         my $opendate=$opendate{$_};
  220:         my $answerdate=$answerdate{$_};
  221:         my $preface='';
  222:         unless ($_ eq '0') { $preface=' Part: '.$_.' '; }
  223:         if ($opendate) {
  224:             if ($now<$duedate || (!$duedate)) {
  225:                 unless ($tcode==4) { $tcode=2; }
  226:                 if ($duedate) {
  227:                     $ctext.=$preface.'Due: '.localtime($duedate);
  228:                 } else {
  229:                     $ctext.=$preface.'No Due Date';
  230:                 }
  231:                 if ($now<$opendate) {
  232:                     unless ($tcode) { $tcode=1; }
  233:                     $ctext.=$preface.'Open: '.localtime($opendate);
  234:                 }
  235:                 if ($duedate && $duedate-$now<86400) {
  236:                     $tcode=4;
  237:                     $ctext.=$preface.'Due: '.localtime($duedate);
  238:                 }
  239:             } else {
  240:                 unless (($tcode==4) || ($tcode eq 2)) { $tcode=3; }
  241:                 if ($now<$answerdate) {
  242:                     $ctext.='Answer: '.localtime($duedate);
  243:                 }
  244:             }
  245:         } else {
  246:             unless (($tcode==2) || ($tcode==4)) { $tcode=1; }
  247:         }
  248:         
  249:         my $status=$returnhash{'resource.'.$_.'.solved'};
  250:         
  251:         if ($status eq 'correct_by_student') {
  252:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  253:             $ctext.=' solved';
  254:         } elsif ($status eq 'correct_by_override') {
  255:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  256:             $ctext.=' override';
  257:         } elsif ($status eq 'incorrect_attempted') {
  258:             if ($code!=4 && $code!=3) { $code=2; }
  259:             if ($code==3) { $code=4; }
  260:             $ctext.=' ('.
  261:                 ($returnhash{'resource.'.$_.'.tries'}?
  262:                  $returnhash{'resource.'.$_.'.tries'}:'0');
  263:             my $numtries = &parmval($_.'.maxtries',$symb);
  264:             if ($numtries) { $ctext.='/'.$numtries.' tries'; }
  265:             $ctext.=')';
  266:         } elsif ($status eq 'incorrect_by_override') {
  267:             if ($code!=4 && $code!=3) { $code=2; }
  268:             if ($code==3) { $code=4; }
  269:             $ctext.=' override';
  270:         } elsif ($status eq 'excused') {
  271:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  272:             $ctext.=' excused';
  273:         } else {
  274:             if ($code==0) { $code=1; }
  275:         }
  276:     }
  277: 
  278:     return 'p'.$code.$tcode.'"'.$ctext.'"';
  279: }
  280: 
  281: 
  282: sub addresource {
  283:     my ($resource,$sofar,$rid,$showtypes,$indent,$linkid)=@_;
  284:     if ($showtypes eq 'problems') {
  285:         if ($resource!~/\.(problem|exam|quiz|assess|survey|form)$/) {
  286:             return;
  287:         }
  288:     }
  289:     my $brepriv=&Apache::lonnet::allowed('bre',$resource);
  290:     if ($hash{'src_'.$rid}) {
  291:         if (($brepriv eq '2') || ($brepriv eq 'F')) {
  292:             my $pprefix='';
  293:             if ($resource=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  294:                 $pprefix=&astatus($rid);
  295:             }
  296:             $$sofar++;
  297:             if ($indent) { $pprefix='i'.$indent.','.$pprefix; }
  298:             if ($linkid) { $pprefix='l'.$linkid.','.$pprefix; }
  299:             if (defined($rows[$$sofar])) {
  300:                 $rows[$$sofar].='&'.$pprefix.$rid;
  301:             } else {
  302:                 $rows[$$sofar]=$pprefix.$rid;
  303:             }
  304:         }
  305:     }
  306: }
  307: 
  308: sub followlinks () {
  309:     my ($rid,$sofar,$beenhere,$further,$showtypes,$indent,$linkid)=@_;
  310:     my $mincond=1;
  311:     my $next='';
  312:     foreach (split(/\,/,$hash{'to_'.$rid})) {
  313:         my $thiscond=
  314:             &Apache::lonnet::directcondval($hash{'condid_'.$hash{'undercond_'.$_}});
  315:         if ($thiscond>=$mincond) {
  316:             if ($next) {
  317:                 $next.=','.$_.':'.$thiscond;
  318:             } else {
  319:                 $next=$_.':'.$thiscond;
  320:             }
  321:             if ($thiscond>$mincond) { $mincond=$thiscond; }
  322:         }
  323:     }
  324:     my $col=0;
  325:     &Apache::lonxml::debug("following links -$next-");
  326:     foreach (split(/\,/,$next)) {
  327:         my ($nextlinkid,$condval)=split(/\:/,$_);
  328:         if ($condval>=$mincond) {
  329:             my $now=&tracetable($sofar,$hash{'goesto_'.$nextlinkid},
  330:                                 $beenhere,$showtypes,$indent,$linkid);
  331:             if ($now>$further) {                
  332:                 if ($col>0) {
  333:                     my $string;
  334:                     for(my $i=0;$i<$col;$i++) { $string.='&'; }
  335:                     for(my $i=$further+1;$now-1>$i;$i++) {
  336:                         $rows[$i]=$string.$rows[$i];
  337:                     }
  338:                 }
  339:                 $further=$now;
  340:             }
  341:         }
  342:         $col++;
  343:     }
  344:     return $further;
  345: }
  346: # ------------------------------------------------------------ Build page table
  347: 
  348: sub tracetable {
  349:     my ($sofar,$rid,$beenhere,$showtypes,$indent,$linkid)=@_;
  350:     my $newshowtypes=$showtypes;
  351:     my $further=$sofar;
  352: # $Apache::lonxml::debug=1;
  353:     &Apache::lonxml::debug("$rid ; $linkid ; $sofar ; $beenhere ; ".$hash{'src_'.$rid});
  354:     if ($beenhere=~/\&$rid\&/) { return $further; }
  355:     $beenhere.=$rid.'&';
  356: 
  357:     if (defined($hash{'is_map_'.$rid})) {
  358:         $sofar++;
  359:         my $tprefix='';
  360:         if ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
  361:             eq 'sequence') {
  362:             $tprefix='h';
  363:         } elsif ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
  364:                  eq 'page') {
  365:             $tprefix='j';
  366:             if ($indent) { $tprefix='i'.$indent.','.$tprefix; }
  367:             if ($linkid) { $tprefix='l'.$linkid.','.$tprefix; }
  368:             $newshowtypes='problems';
  369:             $indent++;
  370:             #if in a .page continue to link the encompising .page
  371:             if (!$linkid) { $linkid=$rid; }
  372:         }
  373:         if (defined($rows[$sofar])) {
  374:             $rows[$sofar].='&'.$tprefix.$rid;
  375:         } else {
  376:             $rows[$sofar]=$tprefix.$rid;
  377:         }
  378:         if ((defined($hash{'map_start_'.$hash{'src_'.$rid}})) &&
  379:             (defined($hash{'map_finish_'.$hash{'src_'.$rid}}))) {
  380:             my $frid=$hash{'map_finish_'.$hash{'src_'.$rid}};
  381:             $sofar=&tracetable($sofar,$hash{'map_start_'.$hash{'src_'.$rid}},
  382:                                '&'.$frid.'&',$newshowtypes,$indent,$linkid);
  383:             &addresource($hash{'src_'.$frid},\$sofar,$frid,$newshowtypes,
  384:                          $indent,$linkid);
  385:             if ($tprefix =~ /j$/) { $indent--; $linkid=''; }
  386:         }
  387:     } else {
  388:         &addresource($hash{'src_'.$rid},\$sofar,$rid,$showtypes,
  389:                      $indent,$linkid);
  390:     }
  391: 
  392:     if (defined($hash{'to_'.$rid})) {
  393:         $further=&followlinks($rid,$sofar,$beenhere,$further,$showtypes,
  394:                               $indent,$linkid);
  395:     }
  396: 
  397:     return $further;
  398: }
  399: 
  400: # ================================================================ Main Handler
  401: 
  402: sub handler {
  403:     my $r=shift;
  404: 
  405:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
  406: 
  407:     if ($ENV{'form.jtest'} ne "1")
  408:     {
  409:         return new_handle($r);
  410:     }
  411: 
  412: # ------------------------------------------- Set document type for header only
  413: 
  414:     if ($r->header_only) {
  415:         if ($ENV{'browser.mathml'}) {
  416:             $r->content_type('text/xml');
  417:         } else {
  418:             $r->content_type('text/html');
  419:         }
  420:         $r->send_http_header;
  421:         return OK;
  422:     }
  423:     my $requrl=$r->uri;
  424:     my $hashtied;
  425: # ----------------------------------------------------------------- Tie db file
  426:     my $fn;
  427:     if ($ENV{'request.course.fn'}) {
  428:         $fn=$ENV{'request.course.fn'};
  429:         if (-e "$fn.db") {
  430:             if ((tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) &&
  431:                 (tie(%parmhash,'GDBM_File',
  432:                      $ENV{'request.course.fn'}.'_parms.db',
  433:                      &GDBM_READER(),0640))) {
  434:                 $hashtied=1;
  435:             }
  436:         }
  437:     }
  438:     if (!$hashtied) {
  439:         $ENV{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
  440:         return HTTP_NOT_ACCEPTABLE; 
  441:     }
  442: 
  443: # ------------------------------------------------------------------- Hash tied
  444: 
  445:     if ($ENV{'browser.mathml'}) {
  446:         $r->content_type('text/xml');
  447:     } else {
  448:         $r->content_type('text/html');
  449:     }
  450:     &Apache::loncommon::no_cache($r);
  451:     $r->send_http_header;
  452: 
  453:     my $firstres=$hash{'map_start_'.
  454:            &Apache::lonnet::clutter($ENV{'request.course.uri'})};
  455:     my $lastres=$hash{'map_finish_'.
  456:            &Apache::lonnet::clutter($ENV{'request.course.uri'})};
  457:     if (!(($firstres) && ($lastres))) {
  458:         $r->print('<html><body>Coursemap undefined.</body></html>');
  459:     } else {
  460: 
  461: # ----------------------------------------------------------------- Render page
  462: # -------------------------------------------------------------- Set parameters
  463: 
  464: 
  465: # ---------------------------- initialize coursedata and userdata for this user
  466:         undef %courseopt;
  467:         undef %useropt;
  468: 
  469:         my $uname=$ENV{'user.name'};
  470:         my $udom=$ENV{'user.domain'};
  471:         my $uhome=$ENV{'user.home'};
  472:         my $cid=$ENV{'request.course.id'};
  473:         my $chome=$ENV{'course.'.$cid.'.home'};
  474:         my ($cdom,$cnum)=split(/\_/,$cid);
  475: 
  476:         my $userprefix=$uname.'_'.$udom.'_';
  477:         
  478:         unless ($uhome eq 'no_host') { 
  479: # ------------------------------------------------- Get coursedata (if present)
  480:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
  481:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
  482:                                                  ':resourcedata',$chome);
  483:                 if ($reply!~/^error\:/) {
  484:                     $courserdatas{$cid}=$reply;
  485:                     $courserdatas{$cid.'.last_cache'}=time;
  486:                 }
  487:                 # check to see if network failed
  488:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
  489:                 {
  490:                     $networkFailedFlag = 1;
  491:                 }
  492:             }
  493:             foreach (split(/\&/,$courserdatas{$cid})) {
  494:                 my ($name,$value)=split(/\=/,$_);
  495:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
  496:                     &Apache::lonnet::unescape($value);
  497:             }
  498: # --------------------------------------------------- Get userdata (if present)
  499:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
  500:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
  501:                 if ($reply!~/^error\:/) {
  502:                     $userrdatas{$uname.'___'.$udom}=$reply;
  503:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
  504:                 }
  505:             }
  506:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
  507:                 my ($name,$value)=split(/\=/,$_);
  508:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
  509:                     &Apache::lonnet::unescape($value);
  510:             }
  511:         }
  512: 
  513:         @rows=();
  514: 
  515:         &tracetable(0,$firstres,'&','',0);
  516: 
  517: # ------------------------------------------------------------------ Page parms
  518: 
  519:         my $j;
  520:         my $i;
  521:         my $lcm=1;
  522:         my $contents=0;
  523: 
  524: # ---------------------------------------------- Go through table to get layout
  525: 
  526:         for ($i=0;$i<=$#rows;$i++) {
  527:             if ($rows[$i]) {
  528:                 &Apache::lonxml::debug("Row $i is:".$rows[$i]);
  529:                 $contents++;
  530:                 my @colcont=split(/\&/,$rows[$i]);
  531:                 $lcm*=($#colcont+1)/euclid($lcm,($#colcont+1));
  532:             } 
  533:         }
  534: 
  535: 
  536:         unless ($contents) {
  537:             $r->print('<html><body>Empty Map.</body></html>');
  538:         } else {
  539: 
  540: # ------------------------------------------------------------------ Build page
  541: 
  542:             my $currenturl=$ENV{'form.postdata'};
  543:             $currenturl=~s/^http\:\/\///;
  544:             $currenturl=~s/^[^\/]+//;
  545: 
  546: # ---------------------------------------------------------------- Send headers
  547: 
  548:             my $date=localtime;
  549:             my $now=time;
  550: # ----------------------------------------- Get email status and discussiontime
  551: 
  552:             my %emailstatus=&Apache::lonnet::dump('email_status');
  553:             my $logouttime=$emailstatus{'logout'};
  554:             my $courseleave=$emailstatus{'logout_'.$ENV{'request.course.id'}};
  555:             my $lastcheck=($courseleave>$logouttime?$courseleave:$logouttime);
  556: 
  557:             my %discussiontimes=&Apache::lonnet::dump('discussiontimes',
  558:                                                           $cdom,$cnum);
  559: 
  560:             my %feedback=();
  561:             my %error=();
  562:             foreach my $msgid (split(/\&/,&Apache::lonnet::reply('keys:'.
  563:                                                                  $ENV{'user.domain'}.':'.
  564:                                                                  $ENV{'user.name'}.':nohist_email',
  565:                                                                  $ENV{'user.home'}))) {
  566:                 $msgid=&Apache::lonnet::unescape($msgid);
  567:                 my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
  568:                 if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
  569:                     my ($what,$url)=($1,$2);
  570:                     my %status=
  571:                         &Apache::lonnet::get('email_status',[$msgid]);
  572:                     if ($status{$msgid}=~/^error\:/) { 
  573:                         $status{$msgid}=''; 
  574:                     }
  575:                         
  576:                     if (($status{$msgid} eq 'new') || 
  577:                         (!$status{$msgid})) { 
  578:                         if ($what eq 'Error') {
  579:                             $error{$url}.=','.$msgid; 
  580:                         } else {
  581:                             $feedback{$url}.=','.$msgid;
  582:                         }
  583:                     }
  584:                 }
  585:             }
  586: # ----------------------------------------------------------- Start Page Output
  587:             my $bodytagadd='';
  588:             $r->print(
  589:                    '<html><head><title>Navigate Course Map</title></head>');
  590:             if (($currenturl=~/^\/res/) &&
  591:                 ($currenturl!~/^\/res\/adm/)) {
  592:                 $bodytagadd='onLoad="window.location.hash='."'curloc'".'"';
  593:             }
  594:             $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
  595:                                                   $bodytagadd));
  596:             $r->print('<script>window.focus();</script>');
  597:             my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  598:             if (defined($desc)) { $r->print("<h2>$desc</h2>\n"); }
  599:             $r->print("<h3>$date</h3>\n");
  600:             $r->rflush();
  601:             $r->print('<img src="/adm/lonMisc/chat.gif"> New discussion since '.
  602:                       localtime($lastcheck).
  603:                       '<br><img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'); 
  604:             if (($currenturl=~/^\/res/) &&
  605:                 ($currenturl!~/^\/res\/adm/)) {
  606:                 $r->print('<a href="#curloc">Current Location</a><p>');
  607:             }
  608: 
  609:             # Handle a network error
  610: 
  611:             if ($networkFailedFlag)
  612:             {
  613:                 $r->print('<H2>LON-CAPA network failure.</H2>'."\n");
  614:                 $r->print("<p>LON-CAPA's network is having difficulties, some problem" .
  615:                           " information, such as due dates, will not be available.");
  616:             }
  617: # ----------------------------------------------------- The little content list
  618:             for ($i=0;$i<=$#rows;$i++) {
  619:                 if ($rows[$i]) {
  620:                     my @colcont=split(/\&/,$rows[$i]);
  621:                     my $avespan=$lcm/($#colcont+1);
  622:                     for ($j=0;$j<=$#colcont;$j++) {
  623:                         my $rid=$colcont[$j];
  624:                         if ($rid=~/^h(.+)/) {
  625:                             $rid=$1;
  626:                             $r->print('&nbsp;&nbsp;&nbsp;<a href="#'.
  627:                                       $rid.'">'.$hash{'title_'.$rid}.
  628:                                       '</a><br>');
  629:                         }
  630:                     }
  631:                 }
  632:             }
  633: # ----------------------------------------------------------------- Start table
  634:             $r->print('<hr><table cols="'.$lcm.'" border="0">');
  635:             for ($i=0;$i<=$#rows;$i++) {
  636:                 if ($rows[$i]) {
  637:                     $r->print("\n<tr>");
  638:                     my @colcont=split(/\&/,$rows[$i]);
  639:                     my $avespan=$lcm/($#colcont+1);
  640: 
  641:                     # for each item I wish to print on this row...
  642:                     for ($j=0;$j<=$#colcont;$j++) {
  643:                         my $indent;my $indentstr;
  644:                         my $linkid;
  645:                         my $rid=$colcont[$j];
  646:                         $rid=~/(\d+)\.(\d+)$/;
  647:                         my $src=
  648:                            &Apache::lonnet::declutter($hash{'src_'.$1.'.'.$2});
  649:                         my $symb=
  650:           &Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.$src;
  651:                         my $add='<td>';
  652:                         my $adde='</td>';
  653:                         my $hwk='<font color="#223322">';
  654:                         my $hwke='</font>';
  655:                         if ($rid=~/^l(\d+\.\d+),(.+)/) { $linkid=$1; $rid=$2; }
  656:                         if ($rid=~/^i(\d+),(.+)/) { $indent=$1; $rid=$2; }
  657:                         if ($rid=~/^h(.+)/) {
  658:                             $rid=$1;
  659:                             $add='<th bgcolor="#AAFF55"><a name="'.$rid.'">';
  660:                             $adde='</th>';
  661:                             if (($ENV{'user.adv'}) && 
  662:                                 ($parmhash{$symb.'.0.parameter_randompick'})) {
  663:                                $adde=' (randomly select '.
  664:                                    $parmhash{$symb.'.0.parameter_randompick'}.
  665:                                    ')</th>';
  666:                             }
  667:                         }
  668:                         if ($rid=~/^j(.+)/) { $rid=$1; }
  669:                         if ($rid=~/^p(\d)(\d)\"([\w\: \(\)\/\,]*)\"(.+)/) {
  670:                             # sub astatus describes what code/tcode mean
  671:                             my $code=$1;
  672:                             my $tcode=$2;
  673:                             my $ctext=$3;
  674:                             $rid=$4;
  675:                             
  676:                             # will open later
  677:                             if ($tcode eq '1') { 
  678:                                 $add='<td bgcolor="#AAAAAA">';
  679:                             }
  680: 
  681:                             # solved/correct
  682:                             if ($code eq '3') {
  683:                                 $add='<td bgcolor="#AAFFAA">';
  684:                             } elsif ($code eq '4') { # partially correct
  685:                                 $add='<td bgcolor="#E0FFAA">';
  686:                             } else {
  687:                                 # not attempted
  688:                                 
  689:                                 # we end up here on network failure, so pick a neutral
  690:                                 # color if the network failed instead of bright red.
  691:                                 if ( $networkFailedFlag )
  692:                                 {
  693:                                     $add = '<td bgcolor="#AAAAAA">';
  694:                                 }
  695:                                 else
  696:                                 {
  697:                                     $add='<td bgcolor="#FFAAAA">';
  698:                                 }
  699: 
  700:                                 if ($tcode eq '2') { # open, not past due
  701:                                     $add='<td bgcolor="#FFFFAA">';
  702:                                 }
  703: 
  704:                                 if ($tcode eq '4') { # due in next 24 hours
  705:                                     $add='<td bgcolor="#FFFF33">';
  706:                                     $adde='</td>';
  707:                                 }
  708:                             }
  709:                             $hwk='<font color="#888811"><b>';
  710:                             $hwke='</b></font>';
  711:                             if ($code eq '1') {
  712:                                 $hwke='</b> ('.$ctext.')</font>';
  713:                             }
  714:                             if ($code eq '2' || $code eq '4') {
  715:                                 $hwk='<font color="#992222"><b>';
  716:                                 $hwke='</b> ('.$ctext.')</font>';
  717:                             }
  718:                             if ($code eq '3') {
  719:                                 $hwk='<font color="#229922"><b>';
  720:                                 $hwke='</b> ('.$ctext.')</font>';
  721:                             }
  722:                             if ($networkFailedFlag) 
  723:                             {
  724:                                 $hwke='</b> (status unavailable)</font>';
  725:                             }
  726:                         }
  727:                         if ($rid && $hash{'src_'.$rid} eq $currenturl) {
  728:                             $add=$add.'<a name="curloc"></a>'.
  729:                                 '<font color=red size=+2><b>&gt; </b></font>';
  730:                             $adde=
  731:                                 '<font color=red size=+2><b> &lt;</b></font>'.$adde;
  732:                         }
  733:                         if ($discussiontimes{$symb}>$lastcheck) {
  734:                             $adde=
  735:                                 '<img border=0 src="/adm/lonMisc/chat.gif">'.
  736:                                     $adde;
  737:                         }
  738:                         if ($error{$src}) {
  739:                             foreach (split(/\,/,$error{$src})) {
  740:                                 if ($_) {
  741:                                     $adde=
  742:                                         '&nbsp;<a href="/adm/email?display='.
  743:                                             &Apache::lonnet::escape($_).
  744:                                                 '"><img src="/adm/lonMisc/bomb.gif" border=0></a>'
  745:                                                     .$adde;
  746:                                 }
  747:                             }
  748:                         }
  749:                         if ($feedback{$src}) {
  750:                             foreach (split(/\,/,$feedback{$src})) {
  751:                                 if ($_) {
  752:                                     $adde=
  753:                                         '&nbsp;<a href="/adm/email?display='.
  754:                                             &Apache::lonnet::escape($_).
  755:                                                 '"><img src="/adm/lonMisc/feedback.gif" border=0></a>'
  756:                                                     .$adde;
  757:                                 }
  758:                             }
  759:                         }
  760:                         if ($indent) {
  761:                             my $is="&nbsp;&nbsp;";
  762:                             for(my $i=-1;$i<$indent;$i++) { $indentstr.=$is; }
  763:                         }
  764:                         if (!$linkid) { $linkid=$rid; }
  765:                         if ($hash{'randomout_'.$rid}) {
  766:                             $adde=' <i>(hidden)</i>'.$adde;
  767:                         }
  768:                         $r->print($add.$indentstr);
  769:                         if ($rid) {
  770:                             $r->print('<a href="'.$hash{'src_'.$linkid}.
  771:                                       (($hash{'src_'.$linkid}=~/\?/)?'&':'?').
  772:                                       'symb='.&Apache::lonnet::escape($symb)
  773:                                        .'">'.
  774:                                       $hwk.$hash{'title_'.$rid}.$hwke.'</a>');
  775:                         }
  776:                         $r->print($adde);
  777:                     }
  778:                     $r->print('</tr>');
  779:                 }
  780:             }
  781:             $r->print("\n</table>");
  782:             $r->print('</body></html>');
  783: # -------------------------------------------------------------------- End page
  784:         }                  
  785: # ------------------------------------------------------------- End render page
  786:     }
  787: # ------------------------------------------------------------------ Untie hash
  788:     unless (untie(%hash)) {
  789:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  790:                                  "Could not untie coursemap $fn (browse).</font>"); 
  791:     }
  792:     unless (untie(%parmhash)) {
  793:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  794:                                  "Could not untie parmhash (browse).</font>"); 
  795:     }
  796:     return OK;
  797: }
  798: 
  799: sub new_handle {
  800:     my $r = shift;
  801: 
  802:     # Handle header-only request
  803:     if ($r->header_only) {
  804:         if ($ENV{'browser.mathml'}) {
  805:             $r->content_type('text/xml');
  806:         } else {
  807:             $r->content_type('text/html');
  808:         }
  809:         $r->send_http_header;
  810:         return OK;
  811:     }
  812: 
  813:     # Send header, don't cache this page
  814:     if ($ENV{'browser.mathml'}) {
  815:         $r->content_type('text/xml');
  816:     } else {
  817:         $r->content_type('text/html');
  818:     }
  819:     &Apache::loncommon::no_cache($r);
  820:     $r->send_http_header;
  821: 
  822:     # Header
  823:     $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
  824:                                           ''));
  825:     # Initialize the nav map
  826:     my $navmap = Apache::lonnavmaps::navmap->new(
  827:                         $ENV{"request.course.fn"}.".db",
  828:                         $ENV{"request.course.fn"}."_parms.db", 1);
  829: 
  830: 
  831:     if (!defined($navmap)) {
  832:         my $requrl = $r->uri;
  833:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
  834:         return HTTP_NOT_ACCEPTABLE;
  835:     }
  836: 
  837:     # Check that it's defined
  838:     if (!($navmap->courseMapDefined())) {
  839:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  840:                   '</body></html>');
  841:         return OK;
  842:     }
  843: 
  844:     # Grab a resource object so we have access to the constants; this
  845:     # is technically not proper, but should be harmless
  846:     my $res = $navmap->firstResource();
  847: 
  848:     # Defines a status->color mapping, null string means don't color
  849:     my %colormap = 
  850:     ( $res->NETWORK_FAILURE        => '',
  851:       $res->CORRECT                => '',
  852:       $res->EXCUSED                => '#BBBBFF',
  853:       $res->PAST_DUE_ANSWER_LATER  => '',
  854:       $res->PAST_DUE_NO_ANSWER     => '',
  855:       $res->ANSWER_OPEN            => '#CCFFCC',
  856:       $res->OPEN_LATER             => '',
  857:       $res->TRIES_LEFT             => '',
  858:       $res->INCORRECT              => '',
  859:       $res->OPEN                   => '',
  860:       $res->NOTHING_SET            => ''        );
  861:     # And a special case in the nav map; what to do when the assignment
  862:     # is not yet done and due in less then 24 hours
  863:     my $hurryUpColor = "#FFCCCC";
  864: 
  865:     my %statusIconMap = 
  866: 	( $res->NETWORK_FAILURE    => '',
  867: 	  $res->NOTHING_SET        => '',
  868: 	  $res->CORRECT            => 'navmap.correct.gif',
  869: 	  $res->EXCUSED            => 'navmap.correct.gif',
  870: 	  $res->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
  871: 	  $res->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
  872: 	  $res->ANSWER_OPEN        => 'navmap.wrong.gif',
  873: 	  $res->OPEN_LATER         => '',
  874: 	  $res->TRIES_LEFT         => 'navmap.open.gif',
  875: 	  $res->INCORRECT          => 'navmap.wrong.gif',
  876: 	  $res->OPEN               => 'navmap.open.gif' );
  877: 
  878:     my %condenseStatuses =
  879: 	( $res->NETWORK_FAILURE    => 1,
  880: 	  $res->NOTHING_SET        => 1,
  881: 	  $res->CORRECT            => 1 );
  882: 
  883:     my %filterHash;
  884:     # Figure out what we're not displaying
  885:     foreach (split(/\,/, $ENV{"form.filter"})) {
  886:         if ($_) {
  887:             $filterHash{$_} = "1";
  888:         }
  889:     }
  890: 
  891:     my $currenturl = $ENV{'form.postdata'};
  892:     $currenturl=~s/^http\:\/\///;
  893:     $currenturl=~s/^[^\/]+//;
  894:     my $queryAdd = "postdata=" . &Apache::lonnet::escape($currenturl);
  895: 
  896:     $r->print("$currenturl<br/>");
  897:     
  898: 
  899:     # Begin the HTML table
  900:     # four cols: resource + indent, chat+feedback, icon, text string
  901:     $r->print('<table cellspacing="3" cellpadding="0" bgcolor="#FFFFFF">' ."\n");
  902: 
  903:     my $mapIterator = $navmap->getIterator(undef, undef, \%filterHash, 0);
  904:     my $curRes = $mapIterator->next();
  905:     undef $res; # so we don't accidentally use it later
  906:     my $indentLevel = -1;
  907:     my $indentString = "<img src=\"/adm/lonIcons/whitespace1.gif\" width=\"25\" height=\"1\" alt=\"\" border=\"0\" />";
  908: 
  909:     my $isNewBranch = 0;
  910:     my $now = time();
  911:     my $in24Hours = $now + 24 * 60 * 60;
  912: 
  913:     while ($curRes != $mapIterator->END_NAV_MAP) {
  914:         if ($curRes == $mapIterator->BEGIN_MAP() ||
  915:             $curRes == $mapIterator->BEGIN_BRANCH()) {
  916:             $indentLevel++;
  917:         }
  918:         if ($curRes == $mapIterator->END_MAP() ||
  919:             $curRes == $mapIterator->END_BRANCH()) {
  920:             $indentLevel--;
  921:         }
  922:         if ($curRes == $mapIterator->BEGIN_BRANCH()) {
  923:             $isNewBranch = 1;
  924:         }
  925: 
  926:         if (ref($curRes) && $curRes->src()) {
  927: 
  928: 	    # Step one: Decide which parts to show
  929: 	    my @parts = @{$curRes->parts()};
  930: 	    my $multipart = scalar(@parts) > 1;
  931: 	    my $condensed = 0;
  932: 		
  933:             if ($curRes->is_problem()) {
  934: 		# Is it multipart?
  935: 
  936: 		if ($multipart) {
  937: 		    # If it's multipart, see if part 0 is "open"
  938: 		    # if it is, display all parts, if it isn't,
  939: 		    # just display first
  940: 		    if (!$curRes->opendate("0")) {
  941: 			@parts = ("0"); # just display the zero-th part
  942: 		    } else {
  943: 			# Otherwise, only display part 0 if we want to 
  944: 			# attach feedback or email information to it
  945: 			if ($curRes->hasDiscussion() || $curRes->getFeedback()) {
  946: 			    shift @parts;
  947: 			} else {
  948: 			    # If there's discussion or feedback, that counts
  949: 			    # as a difference, so display the parts.
  950: 			    
  951: 			    # Now, we decide whether to condense the
  952: 			    # parts due to similarity
  953: 			    my $status = $curRes->status($parts[1]);
  954: 			    my $due = $curRes->duedate($parts[1]);
  955: 			    my $open = $curRes->opendate($parts[1]);
  956: 			    my $statusAllSame = 1;
  957: 			    my $dueAllSame = 1;
  958: 			    my $openAllSame = 1;
  959: 			    for (my $i = 2; $i < scalar(@parts); $i++) {
  960: 				if ($curRes->status($parts[$i]) != $status){
  961: 				    $statusAllSame = 0;
  962: 				}
  963: 				if ($curRes->duedate($parts[$i]) != $due ) {
  964: 				    $dueAllSame = 0;
  965: 				}
  966: 				if ($curRes->opendate($parts[$i]) != $open) {
  967: 				    $openAllSame = 0;
  968: 				}
  969: 			    }
  970: 			    
  971: 			    # $allSame is true if all the statuses were
  972: 			    # the same. Now, if they are all the same and
  973: 			    # match one of the statuses to condense, or they
  974: 			    # are all open with the same due date, or they are
  975: 			    # all OPEN_LATER with the same open date, display the
  976: 			    # status of the first non-zero part (to get the 'correct'
  977: 			    # status right, since 0 is never 'correct' or 'open').
  978: 			    if (($statusAllSame && defined($condenseStatuses{$status})) ||
  979: 				($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
  980: 				($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
  981: 				@parts = ($parts[1]);
  982: 				$condensed = 1;
  983: 			    }
  984: 			}
  985: 		    }
  986: 		}
  987: 
  988:             } else {
  989:                 @parts[0] = "0"; # this is to get past foreach loop below
  990:                  # you can consider a non-problem resource as a resource
  991:                  # with only one part without loss
  992:             }
  993: 
  994: 	    # Step two: Show the parts
  995:             foreach my $part (@parts) {
  996: 
  997: 		my $deltalevel = 0; # for inserting the branch icon
  998:                 
  999:                 # For each thing we're displaying...
 1000: 
 1001:                 my $stack = $mapIterator->getStack();
 1002:                 my $src = getLinkForResource($stack);
 1003: 
 1004:                 my $srcHasQuestion = $src =~ /\?/;
 1005:                 my $link = $src.
 1006:                     ($srcHasQuestion?'&':'?') .
 1007:                     'symb='.&Apache::lonnet::escape($curRes->symb()).
 1008:                     '"';
 1009:                 my $title = $curRes->title();
 1010:                 my $partLabel = "";
 1011:                 my $newBranchText = "";
 1012: 
 1013:                 # If this is a new branch, label it so
 1014:                 # (temporary, this should be an icon w/ alt text)
 1015:                 if ($isNewBranch) {
 1016:                     $newBranchText = "<img src=\"/adm/lonIcons/branch.gif\" border=\"0\">";
 1017:                     $isNewBranch = 0;
 1018: 		    $deltalevel = 1;
 1019:                 }
 1020: 
 1021:                 # links to open and close the folders
 1022:                 my $linkopen = "<a href=\"$link\">";
 1023:                 my $linkclose = "</a>";
 1024: 
 1025:                 my $icon = "<img src=\"/adm/lonIcons/html.gif\" alt=\"\" border=\"0\" />";
 1026:                 if ($curRes->is_problem()) { 
 1027: 		    if ($part eq "0" || $condensed) {
 1028: 			$icon = '<img src="/adm/lonIcons/problem.gif" alt="" border=\"0\" />'; 
 1029: 		    } else {
 1030: 			$icon = $indentString;
 1031: 		    }
 1032:                 }
 1033: 
 1034:                 # Display the correct icon, link to open or shut map
 1035:                 if ($curRes->is_map()) { 
 1036:                     my $mapId = $curRes->map_pc();
 1037:                     my $nowOpen = !defined($filterHash{$mapId});
 1038:                     $icon = $nowOpen ?
 1039:                         "folder_closed.gif" : "folder_opened.gif";
 1040: 		    $icon = "<img src=\"/adm/lonIcons/$icon\" alt=\"\" border=\"0\" />";
 1041:                     $linkopen = "<a href=\"/adm/navmaps?filter=";
 1042:                     $linkopen .= $nowOpen ? 
 1043:                         addToFilter(\%filterHash, $mapId) :
 1044:                         removeFromFilter(\%filterHash, $mapId);
 1045:                     $linkopen .= "&$queryAdd\">";
 1046:                     $linkclose = "</a>";
 1047:                     
 1048:                 }
 1049:                 
 1050:                 my $colorizer = "";
 1051:                 if ($curRes->is_problem()) {
 1052:                     my $status = $curRes->status($part);
 1053:                     my $color = $colormap{$status};
 1054:                     if ($color ne "") {
 1055:                         $colorizer = "bgcolor=\"$color\"";
 1056:                     }
 1057:                 }
 1058: 
 1059: 		# FIRST ROW: The resource indentation, branch icon, and name
 1060:                 $r->print("  <tr><td align=\"left\" valign=\"top\">\n");
 1061: 
 1062:                 # print indentation
 1063:                 for (my $i = 0; $i < $indentLevel - $deltalevel; $i++) {
 1064:                     $r->print($indentString);
 1065:                 }
 1066: 
 1067:                 $r->print("  ${newBranchText}${linkopen}$icon${linkclose}\n");
 1068: 
 1069:                 if ($curRes->is_problem() && $part != "0" && !$condensed) { 
 1070: 		    $partLabel = " (Part $part)"; 
 1071: 		    $title = "";
 1072: 		}
 1073: 
 1074:                 $r->print("  <a href=\"$link\">$title$partLabel</a></td>");
 1075: 
 1076: 		my $discussionHTML = ""; my $feedbackHTML = "";
 1077: 
 1078: 		# SECOND ROW: Is there text or feedback?
 1079: 		if ($curRes->hasDiscussion()) {
 1080: 		    $discussionHTML = $linkopen .
 1081: 			'<img border="0" src="/adm/lonMisc/chat.gif" />' .
 1082: 			$linkclose;
 1083: 		}
 1084: 
 1085: 		if ($curRes->getFeedback()) {
 1086: 		    my $feedback = $curRes->getFeedback();
 1087: 		    foreach (split(/\,/, $feedback)) {
 1088: 			if ($_) {
 1089: 			    $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
 1090: 				. &Apache::lonnet::escape($_) . '">'
 1091: 				. '<img src="/adm/lonMisc/feedback.gif" '
 1092: 				. 'border="0" /></a>';
 1093: 			}
 1094: 		    }
 1095: 		}
 1096: 
 1097: 		$r->print("<td align=\"left\">$discussionHTML$feedbackHTML</td>");
 1098: 
 1099: 		# Is this the first displayed part of a multi-part problem
 1100: 		# that has not been condensed, so we should suppress these two
 1101: 		# columns?
 1102: 		my $firstDisplayed = !$condensed && $multipart && $part eq "0";
 1103: 
 1104: 		# THIRD ROW: Problem status icon
 1105: 		if ($curRes->is_problem() &&
 1106: 		    !$firstDisplayed) {
 1107: 		    my $icon = $statusIconMap{$curRes->status($part)};
 1108: 		    if ($icon) {
 1109: 			$r->print("<td width=\"50\" align=\"right\">$linkopen<img src=\"/adm/lonIcons/$icon\" border=\"0\" />$linkclose</td>\n");
 1110: 		    } else {
 1111: 			$r->print("<td></td>\n");
 1112: 		    }
 1113: 		} else { # not problem, no icon
 1114: 		    $r->print("<td></td>\n");
 1115: 		}
 1116: 
 1117:  		# FOURTH ROW: Text description
 1118: 		$r->print("<td $colorizer align=\"right\">\n");
 1119:                 
 1120:                 if ($curRes->kind() eq "res" &&
 1121:                     $curRes->is_problem() &&
 1122: 		    !$firstDisplayed) {
 1123:                     $r->print (getDescription($curRes, $part));
 1124:                 }
 1125: 
 1126: 		$r->print("</td></tr>\n");
 1127:             }
 1128:         }
 1129:         $curRes = $mapIterator->next();
 1130:     }
 1131: 
 1132:     $r->print("</table></body></html>");
 1133: 
 1134:     $navmap->untieHashes();
 1135: 
 1136:     return OK;
 1137: }
 1138: 
 1139: # Convenience functions: Returns a string that adds or subtracts
 1140: # the second argument from the first hash, appropriate for the 
 1141: # query string that determines which folders to recurse on
 1142: sub addToFilter {
 1143:     my $hashIn = shift;
 1144:     my $addition = shift;
 1145:     my %hash = %$hashIn;
 1146:     $hash{$addition} = 1;
 1147: 
 1148:     return join (",", keys(%hash));
 1149: }
 1150: 
 1151: sub removeFromFilter {
 1152:     my $hashIn = shift;
 1153:     my $subtraction = shift;
 1154:     my %hash = %$hashIn;
 1155: 
 1156:     delete $hash{$subtraction};
 1157:     return join(",", keys(%hash));
 1158: }
 1159: 
 1160: # Convenience function: Given a stack returned from getStack on the iterator,
 1161: # return the correct src() value.
 1162: # Later, this should add an anchor when we start putting anchors in pages.
 1163: sub getLinkForResource {
 1164:     my $stack = shift;
 1165:     my $res;
 1166: 
 1167:     # Check to see if there are any pages in the stack
 1168:     foreach $res (@$stack) {
 1169:         if (defined($res) && $res->is_page()) {
 1170:             return $res->src();
 1171:         }
 1172:     }
 1173: 
 1174:     # Failing that, return the src of the last resource that is defined
 1175:     # (when we first recurse on a map, it puts an undefined resource
 1176:     # on the bottom because $self->{HERE} isn't defined yet, and we
 1177:     # want the src for the map anyhow)
 1178:     foreach (@$stack) {
 1179:         if (defined($_)) { $res = $_; }
 1180:     }
 1181: 
 1182:     return $res->src();
 1183: }
 1184: 
 1185: # Convenience function: This seperates the logic of how to create
 1186: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
 1187: # etc.) into a seperate function. It takes a resource object as the
 1188: # first parameter, and the part number of the resource as the second.
 1189: # It's basically a big switch statement on the status of the resource.
 1190: 
 1191: sub getDescription {
 1192:     my $res = shift;
 1193:     my $part = shift;
 1194:     my $status = $res->getDateStatus();
 1195: 
 1196:     if ($status == $res->NETWORK_FAILURE) { return ""; }
 1197:     if ($status == $res->NOTHING_SET) {
 1198:         return "Not currently assigned.";
 1199:     }
 1200:     if ($status == $res->OPEN_LATER) {
 1201:         return "Opens: " . timeToHumanString($res->opendate($part));
 1202:     }
 1203:     if ($status == $res->OPEN) {
 1204: 	if ($res->duedate()) {
 1205: 	    return "Due: $status " . timeToHumanString($res->duedate($part));
 1206: 	} else {
 1207: 	    return "Open, no due date";
 1208: 	}
 1209:     }
 1210:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
 1211:         return "Answer opens: " . timeToHumanString($res->answerdate($part));
 1212:     }
 1213:     if ($status == $res->PAST_DUE_NO_ANSWER) {
 1214:         return "Was Due: " . timeToHumanString($res->duedate($part));
 1215:     }
 1216:     if ($status == $res->ANSWER_OPEN) {
 1217:         return "Answer available";
 1218:     }
 1219:     if ($status == $res->EXCUSED) {
 1220: 	return "Excused by instructor";
 1221:     }
 1222:     if ($status == $res->TRIES_LEFT) {
 1223: 	my $tries = $res->tries();
 1224: 	my $maxtries = $res->maxtries();
 1225: 	my $triesString = "($tries of $maxtries tries used)";
 1226: 	if ($res->duedate()) {
 1227: 	    return "Due: $status " . timeToHumanString($res->duedate($part)) .
 1228: 		" $triesString";
 1229: 	} else {
 1230: 	    return "No due date $triesString";
 1231: 	}
 1232:     }
 1233: }
 1234: 
 1235: # I want to change this into something more human-friendly. For
 1236: # now, this is a simple call to localtime. The final function
 1237: # probably belongs in loncommon.
 1238: sub timeToHumanString {
 1239:     my ($time) = @_;
 1240:     # zero, '0' and blank are bad times
 1241:     if ($time) {
 1242: 	return localtime($time);
 1243:     } else {
 1244: 	return 'Never';
 1245:     }
 1246: }
 1247: 
 1248: 1;
 1249: 
 1250: package Apache::lonnavmaps::navmap;
 1251: 
 1252: # LEFT:
 1253: # * Actual handler code (multi-part)
 1254: # * Branches (aieee!) (and conditionals)
 1255: 
 1256: =pod
 1257: 
 1258: lonnavmaps provides functions and objects for dealing with the compiled course hashes generated when a user enters the course, and also provides the Apache handler for the "Navigation Map" button.
 1259: 
 1260: =head1 navmap object: Encapsulating the compiled nav map
 1261: 
 1262: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
 1263: 
 1264: Most notably it provides a way to navigate the map sensibly and a flexible iterator that makes it easy to write various renderers based on nav maps.
 1265: 
 1266: You must obtain resource objects through the navmap object.
 1267: 
 1268: =head2 Methods
 1269: 
 1270: =over 4
 1271: 
 1272: =item * B<new>(filename, parmHashFile, genCourseAndUserOptions, genMailDiscussStatus): Binds a new navmap object to the compiled course representation and parmHashFile. genCourseAndUserOptions is a flag saying whether the course options and user options hash should be generated. This is for when you are using the parameters of the resources that require them; see documentation in resource object documentation. genMailDiscussStatus causes the nav map to retreive information about the email and discussion status of resources. Returns the navmap object if this is successful, or B<undef> if not. You must check for undef; errors will occur when you try to use the other methods otherwise.
 1273: 
 1274: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
 1275: 
 1276: =cut
 1277: 
 1278: use strict;
 1279: use GDBM_File;
 1280: 
 1281: sub new {
 1282:     # magic invocation to create a class instance
 1283:     my $proto = shift;
 1284:     my $class = ref($proto) || $proto;
 1285:     my $self = {};
 1286: 
 1287:     $self->{NAV_HASH_FILE} = shift;
 1288:     $self->{PARM_HASH_FILE} = shift;
 1289:     $self->{GENERATE_COURSE_USER_OPT} = shift;
 1290:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
 1291: 
 1292:     # Resource cache stores navmapresource's as we reference them. We generate
 1293:     # them on-demand so we don't pay for creating resources unless we use them.
 1294:     $self->{RESOURCE_CACHE} = {};
 1295: 
 1296:     # Network failure flag, if we accessed the course or user opt and
 1297:     # failed
 1298:     $self->{NETWORK_FAILURE} = 0;
 1299: 
 1300:     # tie the nav hash
 1301:     my %navmaphash;
 1302:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
 1303:               &GDBM_READER(), 0640))) {
 1304:         return undef;
 1305:     }
 1306:     $self->{NAV_HASH} = \%navmaphash;
 1307:     
 1308:     my %parmhash;
 1309:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
 1310:               &GDBM_READER(), 0640)))
 1311:     {
 1312: 	untie $self->{PARM_HASH};
 1313:         return undef;
 1314:     }
 1315:     $self->{PARM_HASH} = \%parmhash;
 1316:     $self->{HASH_TIED} = 1;
 1317: 
 1318:     # If the course opt hash and the user opt hash should be generated,
 1319:     # generate them
 1320:     if ($self->{GENERATE_COURSE_USER_OPT}) {
 1321:         my $uname=$ENV{'user.name'};
 1322:         my $udom=$ENV{'user.domain'};
 1323:         my $uhome=$ENV{'user.home'};
 1324:         my $cid=$ENV{'request.course.id'};
 1325:         my $chome=$ENV{'course.'.$cid.'.home'};
 1326:         my ($cdom,$cnum)=split(/\_/,$cid);
 1327:         
 1328:         my $userprefix=$uname.'_'.$udom.'_';
 1329:         
 1330:         my %courserdatas; my %useropt; my %courseopt;
 1331:         unless ($uhome eq 'no_host') { 
 1332: # ------------------------------------------------- Get coursedata (if present)
 1333:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1334:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1335:                                                  ':resourcedata',$chome);
 1336:                 if ($reply!~/^error\:/) {
 1337:                     $courserdatas{$cid}=$reply;
 1338:                     $courserdatas{$cid.'.last_cache'}=time;
 1339:                 }
 1340:                 # check to see if network failed
 1341:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1342:                 {
 1343:                     $self->{NETWORK_FAILURE} = 1;
 1344:                 }
 1345:             }
 1346:             foreach (split(/\&/,$courserdatas{$cid})) {
 1347:                 my ($name,$value)=split(/\=/,$_);
 1348:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1349:                     &Apache::lonnet::unescape($value);
 1350:             }
 1351: # --------------------------------------------------- Get userdata (if present)
 1352:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1353:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1354:                 if ($reply!~/^error\:/) {
 1355:                     $userrdatas{$uname.'___'.$udom}=$reply;
 1356:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1357:                 }
 1358:                 # check to see if network failed
 1359:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1360:                 {
 1361:                     $self->{NETWORK_FAILURE} = 1;
 1362:                 }
 1363:             }
 1364:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 1365:                 my ($name,$value)=split(/\=/,$_);
 1366:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1367:                     &Apache::lonnet::unescape($value);
 1368:             }
 1369:             $self->{COURSE_OPT} = \%courseopt;
 1370:             $self->{USER_OPT} = \%useropt;
 1371:         }
 1372:     }   
 1373: 
 1374:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
 1375:         my $cid=$ENV{'request.course.id'};
 1376:         my ($cdom,$cnum)=split(/\_/,$cid);
 1377:         
 1378:         my %emailstatus = &Apache::lonnet::dump('email_status');
 1379:         my $logoutTime = $emailstatus{'logout'};
 1380:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
 1381:         $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
 1382:                                $courseLeaveTime : $logoutTime);
 1383:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 1384:                                                    $cdom, $cnum);
 1385:         my %feedback=();
 1386:         my %error=();
 1387:         my $keys = &Apache::lonnet::reply('keys:'.
 1388:                                           $ENV{'user.domain'}.':'.
 1389:                                           $ENV{'user.name'}.':nohist_email',
 1390:                                           $ENV{'user.home'});
 1391: 
 1392:         foreach my $msgid (split(/\&/, $keys)) {
 1393:             $msgid=&Apache::lonnet::unescape($msgid);
 1394:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
 1395:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
 1396:                 my ($what,$url)=($1,$2);
 1397:                 my %status=
 1398:                     &Apache::lonnet::get('email_status',[$msgid]);
 1399:                 if ($status{$msgid}=~/^error\:/) { 
 1400:                     $status{$msgid}=''; 
 1401:                 }
 1402:                 
 1403:                 if (($status{$msgid} eq 'new') || 
 1404:                     (!$status{$msgid})) { 
 1405:                     if ($what eq 'Error') {
 1406:                         $error{$url}.=','.$msgid; 
 1407:                     } else {
 1408:                         $feedback{$url}.=','.$msgid;
 1409:                     }
 1410:                 }
 1411:             }
 1412:         }
 1413:         
 1414:         $self->{FEEDBACK} = \%feedback;
 1415:         $self->{ERROR_MSG} = \%error; # what is this? JB
 1416:         $self->{DISCUSSION_TIME} = \%discussiontime;
 1417:         $self->{EMAIL_STATUS} = \%emailstatus;
 1418:         
 1419:     }    
 1420:     
 1421:     bless($self);
 1422:         
 1423:     return $self;
 1424: }
 1425: 
 1426: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1427: sub courseMapDefined {
 1428:     my $self = shift;
 1429:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1430: 
 1431:     my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
 1432:     my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
 1433:     return $firstres && $lastres;
 1434: }
 1435: 
 1436: sub getIterator {
 1437:     my $self = shift;
 1438:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 1439:                                                      shift, undef, shift);
 1440:     return $iterator;
 1441: }
 1442: 
 1443: # unties the hash when done
 1444: sub untieHashes {
 1445:     my $self = shift;
 1446:     untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
 1447:     untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
 1448:     $self->{HASH_TIED} = 0;
 1449: }
 1450: 
 1451: # when the object is destroyed, be sure to untie all the hashes we tied.
 1452: sub DESTROY {
 1453:     my $self = shift;
 1454:     $self->untieHashes();
 1455: }
 1456: 
 1457: # Private function: Does the given resource (as a symb string) have
 1458: # current discussion? Returns 0 if chat/mail data not extracted.
 1459: sub hasDiscussion {
 1460:     my $self = shift;
 1461:     my $symb = shift;
 1462:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1463: 
 1464:     return $self->{DISCUSSION_TIME}->{$symb} >
 1465: 	   $self->{LAST_CHECK};
 1466: }
 1467: 
 1468: # Private function: Does the given resource (as a symb string) have
 1469: # current feedback? Returns the string in the feedback hash, which
 1470: # will be false if it does not exist.
 1471: sub getFeedback { 
 1472:     my $self = shift;
 1473:     my $symb = shift;
 1474: 
 1475:     if (!defined($self->{FEEDBACK})) { return ""; }
 1476:     
 1477:     return $self->{FEEDBACK}->{$symb};
 1478: }
 1479: 
 1480: =pod
 1481: 
 1482: =item * B<getById>(id): Based on the ID of the resource (1.1, 3.2, etc.), get a resource object for that resource. This method, or other methods that use it (as in the resource object) is the only proper way to obtain a resource object.
 1483: 
 1484: =cut
 1485: 
 1486: # The strategy here is to cache the resource objects, and only construct them
 1487: # as we use them. The real point is to prevent reading any more from the tied
 1488: # hash then we have to, which should hopefully alleviate speed problems.
 1489: # Caching is just an incidental detail I throw in because it makes sense.
 1490: 
 1491: sub getById {
 1492:     my $self = shift;
 1493:     my $id = shift;
 1494: 
 1495:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1496:     {
 1497:         return $self->{RESOURCE_CACHE}->{$id};
 1498:     }
 1499: 
 1500:     # resource handles inserting itself into cache.
 1501:     return Apache::lonnavmaps::resource->new($self, $id);
 1502: }
 1503: 
 1504: =pod
 1505: 
 1506: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
 1507: 
 1508: =cut
 1509: 
 1510: sub firstResource {
 1511:     my $self = shift;
 1512:     my $firstResource = $self->{NAV_HASH}->{'map_start_' .
 1513:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1514:     return $self->getById($firstResource);
 1515: }
 1516: 
 1517: =pod
 1518: 
 1519: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
 1520: 
 1521: =cut
 1522: 
 1523: sub finishResource {
 1524:     my $self = shift;
 1525:     my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
 1526:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1527:     return $self->getById($firstResource);
 1528: }
 1529: 
 1530: # -------------------------------------------- Figure out a cascading parameter
 1531: #
 1532: # For this function to work
 1533: #
 1534: # * parmhash needs to be tied
 1535: # * courseopt and useropt need to be initialized for this user and course
 1536: #
 1537: 
 1538: sub parmval {
 1539:     my $self = shift;
 1540:     my ($what,$symb)=@_;
 1541:     my $cid=$ENV{'request.course.id'};
 1542:     my $csec=$ENV{'request.course.sec'};
 1543:     my $uname=$ENV{'user.name'};
 1544:     my $udom=$ENV{'user.domain'};
 1545: 
 1546:     unless ($symb) { return ''; }
 1547:     my $result='';
 1548: 
 1549:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1550: 
 1551: # ----------------------------------------------------- Cascading lookup scheme
 1552:     my $rwhat=$what;
 1553:     $what=~s/^parameter\_//;
 1554:     $what=~s/\_/\./;
 1555: 
 1556:     my $symbparm=$symb.'.'.$what;
 1557:     my $mapparm=$mapname.'___(all).'.$what;
 1558:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1559: 
 1560:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 1561:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 1562:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 1563: 
 1564:     my $courselevel= $usercourseprefix.'.'.$what;
 1565:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 1566:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 1567: 
 1568:     my $useropt = $self->{USER_OPT};
 1569:     my $courseopt = $self->{COURSE_OPT};
 1570:     my $parmhash = $self->{PARM_HASH};
 1571: 
 1572: # ---------------------------------------------------------- first, check user
 1573:     if ($uname and defined($useropt)) {
 1574:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 1575:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 1576:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 1577:     }
 1578: 
 1579: # ------------------------------------------------------- second, check course
 1580:     if ($csec and defined($courseopt)) {
 1581:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 1582:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 1583:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 1584:     }
 1585: 
 1586:     if (defined($courseopt)) {
 1587:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 1588:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 1589:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 1590:     }
 1591: 
 1592: # ----------------------------------------------------- third, check map parms
 1593: 
 1594:     my $thisparm=$$parmhash{$symbparm};
 1595:     if (defined($thisparm)) { return $thisparm; }
 1596: 
 1597: # ----------------------------------------------------- fourth , check default
 1598: 
 1599:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 1600:     if (defined($default)) { return $default}
 1601: 
 1602: # --------------------------------------------------- fifth , cascade up parts
 1603: 
 1604:     my ($space,@qualifier)=split(/\./,$rwhat);
 1605:     my $qualifier=join('.',@qualifier);
 1606:     unless ($space eq '0') {
 1607:         my ($part,$id)=split(/\_/,$space);
 1608:         if ($id) {
 1609:             my $partgeneral=$self->parmval($part.".$qualifier",$symb);
 1610:             if (defined($partgeneral)) { return $partgeneral; }
 1611:         } else {
 1612:             my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
 1613:             if (defined($resourcegeneral)) { return $resourcegeneral; }
 1614:         }
 1615:     }
 1616:     return '';
 1617: }
 1618: 
 1619: 
 1620: 1;
 1621: 
 1622: package Apache::lonnavmaps::iterator;
 1623: 
 1624: # This package must precede "navmap" because "navmap" uses it. In
 1625: # order to keep the documentation order straight, the iterator is documented
 1626: # after the navmap object.
 1627: 
 1628: =pod
 1629: 
 1630: =back
 1631: 
 1632: =head1 navmap Iterator
 1633: 
 1634: An I<iterator> encapsulates the logic required to traverse a data structure. navmap uses an iterator to traverse the course map according to the criteria you wish to use.
 1635: 
 1636: To obtain an iterator, call the B<getIterator>() function of a B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator directly.) This will return a reference to the iterator:
 1637: 
 1638: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 1639: 
 1640: To get the next thing from the iterator, call B<next>:
 1641: 
 1642: C<my $nextThing = $resourceIterator-E<gt>next()>
 1643: 
 1644: getIterator behaves as follows:
 1645: 
 1646: =over 4
 1647: 
 1648: =item B<getIterator>(nav_map, firstResource, finishResource, filterHash, condition): All parameters are optional. firstResource is a resource reference corresponding to where the iterator should start. It defaults to navmap->firstResource() for the corresponding nav map. finishResource corresponds to where you want the iterator to end, defaulting to navmap->finishResource(). It is your responsibility to ensure that the iterator will actually get there. filterHash is a hash used as a set containing strings representing the resource IDs, defaulting to empty. Condition is a 1 or 0 that sets what to do with the filter hash: If a 0, then only resource that exist IN the filterHash will be recursed on. If it is a 1, only resources NOT in the filterHash will be recursed on. Defaults to 0, which is to say, do not recurse unless explicitly asked to.
 1649: 
 1650: Thus, by default, all resources will be shown. Change the condition to a 1 without changing the hash, and only the top level of the map will be shown. Changing the condition to 1 and including some values in the hash will allow you to selectively examine parts of the navmap, while leaving it on 0 and adding things to the hash will allow you to selectively ignore parts of the nav map. See the handler code for examples.
 1651: 
 1652: The iterator will return either a reference to a resource object, or a token representing something in the map, such as the beginning of a new branch. The possible tokens are:
 1653: 
 1654: =over 4
 1655: 
 1656: =item * some list of tokens here
 1657: 
 1658: =back
 1659: 
 1660: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_NAV_MAP. (Perl will automatically optimize these into constants.
 1661: 
 1662: =cut
 1663: 
 1664: # Here are the tokens for the iterator:
 1665: 
 1666: sub END_NAV_MAP { return 0; }  # Represents end of entire nav map
 1667: sub BEGIN_MAP { return 1; }    # begining of a new map
 1668: sub END_MAP { return 2; }      # end of the map
 1669: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 1670: sub END_BRANCH { return 4; }   # end of a branch
 1671: 
 1672: # Params: nav map, start resource, end resource, filter, condition, 
 1673: # already seen hash ref
 1674: 
 1675: sub new {
 1676:     # magic invocation to create a class instance
 1677:     my $proto = shift;
 1678:     my $class = ref($proto) || $proto;
 1679:     my $self = {};
 1680: 
 1681:     $self->{NAV_MAP} = shift;
 1682:     return undef unless ($self->{NAV_MAP});
 1683: 
 1684:     # Handle the parameters
 1685:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 1686:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 1687: 
 1688:     # If the given resources are just the ID of the resource, get the
 1689:     # objects
 1690:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 1691:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 1692:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 1693:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 1694: 
 1695:     $self->{FILTER} = shift;
 1696: 
 1697:     # A hash, used as a set, of resource already seen
 1698:     $self->{ALREADY_SEEN} = shift;
 1699:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 1700:     $self->{CONDITION} = shift;
 1701: 
 1702:     # Flag: Have we started yet? If not, the first action is to return BEGIN_MAP.
 1703:     $self->{STARTED} = 0;
 1704: 
 1705:     # Should we continue calling the recursive iterator, if any?
 1706:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1707:     # The recursive iterator, if any
 1708:     $self->{RECURSIVE_ITERATOR} = undef;
 1709:     # Are we recursing on a map, or a branch?
 1710:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 1711:     # And the count of how deep it is, so that this iterator can keep track of
 1712:     # when to pick back up again.
 1713:     $self->{RECURSIVE_DEPTH} = 0;
 1714: 
 1715:     # For keeping track of our branches, we maintain our own stack
 1716:     $self->{BRANCH_STACK} = [];
 1717:     # If the size shrinks, we exhausted a branch
 1718:     $self->{BRANCH_STACK_SIZE} = 0;
 1719:     $self->{BRANCH_DEPTH} = 0;
 1720: 
 1721:     # For returning two things in a forced sequence
 1722:     $self->{FORCE_NEXT} = undef;
 1723: 
 1724:     # Start with the first resource
 1725:     push @{$self->{BRANCH_STACK}}, $self->{FIRST_RESOURCE};
 1726:     $self->{BRANCH_STACK_SIZE} = 1;
 1727: 
 1728:     bless($self);
 1729:     return $self;
 1730: }
 1731: 
 1732: # Note... this function is *touchy*. I strongly recommend tracing
 1733: # through it with the debugger a few times on a non-trivial map before
 1734: # modifying it. Order is *everything*.
 1735: sub next {
 1736:     my $self = shift;
 1737:     
 1738:     # Iterator logic goes here
 1739: 
 1740:     # Is this return value pre-determined?
 1741:     if (defined($self->{FORCE_NEXT})) {
 1742:         my $tmp = $self->{FORCE_NEXT};
 1743:         $self->{FORCE_NEXT} = undef;
 1744:         return $tmp;
 1745:     }
 1746: 
 1747:     # Are we using a recursive iterator? If so, pull from that and
 1748:     # watch the depth; we want to resume our level at the correct time.
 1749:     if ($self->{RECURSIVE_ITERATOR_FLAG})
 1750:     {
 1751:         # grab the next from the recursive iterator
 1752:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 1753:         
 1754:         # is it a begin or end map? Update depth if so
 1755:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 1756:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 1757: 
 1758:         # Are we back at depth 0? If so, stop recursing.
 1759:         if ($self->{RECURSIVE_DEPTH} == 0) {
 1760:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1761:         }
 1762:         
 1763:         return $next;
 1764:     }
 1765: 
 1766:     # Is there a current resource to grab? If not, then return
 1767:     # END_BRANCH and END_MAP in succession.
 1768:     if (scalar(@{$self->{BRANCH_STACK}}) == 0) {
 1769:         if ($self->{BRANCH_DEPTH} > 0) {
 1770:             $self->{FORCE_NEXT} = $self->END_MAP();
 1771:             $self->{BRANCH_DEPTH}--;
 1772:             return $self->END_BRANCH();
 1773:         } else {
 1774:             return $self->END_MAP();
 1775:         }
 1776:     }
 1777: 
 1778:     # Have we not yet begun? If not, return BEGIN_MAP and 
 1779:     # remember that we've started.
 1780:     if ( !$self->{STARTED} ) {
 1781:         $self->{STARTED} = 1;
 1782:         return $self->BEGIN_MAP;
 1783:     }
 1784: 
 1785:     # Did the branch stack shrink since last run? If so,
 1786:     # we exhausted a branch last time, therefore, we're about
 1787:     # to start a new one. (We know because we already checked to see
 1788:     # if the stack was empty.)
 1789:     if ( scalar (@{$self->{BRANCH_STACK}}) < $self->{BRANCH_STACK_SIZE}) {
 1790:         $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 1791:         $self->{BRANCH_DEPTH}++;
 1792:         return $self->BEGIN_BRANCH();
 1793:     }
 1794: 
 1795:     # Remember the size for comparision next time.
 1796:     $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 1797: 
 1798:     # If the next resource we mean to return is going to need
 1799:     # a lower branch level, terminate branches until we get 
 1800:     # there.
 1801: 
 1802:     # Get the next resource in the branch
 1803:     $self->{HERE} = pop @{$self->{BRANCH_STACK}};
 1804: 
 1805:     # Are we at the right depth? If not, close a branch and return
 1806:     # the current resource onto the branch stack
 1807:     if (defined($self->{HERE}->{DATA}->{ITERATOR_DEPTH})
 1808:         && $self->{HERE}->{DATA}->{ITERATOR_DEPTH} <
 1809:         $self->{BRANCH_DEPTH} ) {
 1810:         $self->{BRANCH_DEPTH}--;
 1811:         # return it so we can pick it up eventually
 1812:         push @{$self->{BRANCH_STACK}}, $self->{HERE};
 1813:         return $self->END_BRANCH();
 1814:     }
 1815: 
 1816:     # We always return it after this point and never before
 1817:     # (proof: look at just the return statements), so we
 1818:     # remember that we've seen this.
 1819:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 1820:     
 1821:     # Are we at the utter end? If so, return the END_NAV_MAP marker.
 1822:     if ($self->{HERE} == $self->{NAV_MAP}->finishResource() ) {
 1823:         $self->{FORCE_NEXT} = $self->END_NAV_MAP;
 1824:         return $self->{HERE};
 1825:     }
 1826:     
 1827:     # Get the next possible resources
 1828:     my $nextUnfiltered = $self->{HERE}->getNext();
 1829:     my $next = [];
 1830: 
 1831:     # filter the next possibilities to remove things we've 
 1832:     # already seen. Also, remember what branch depth they should
 1833:     # be displayed at, since there's no other reliable way to tell.
 1834:     foreach (@$nextUnfiltered) {
 1835:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 1836:             push @$next, $_;
 1837:             $_->{DATA}->{ITERATOR_DEPTH} = 
 1838:                 $self->{BRANCH_DEPTH} + 1;
 1839:         }
 1840:     }
 1841: 
 1842:     # Handle branch cases:
 1843:     # Nothing is available next: BRANCH_END
 1844:     # 1 thing next: standard non-branch
 1845:     # 2+ things next: have some branches
 1846:     my $nextCount = scalar(@$next);
 1847:     if ($nextCount == 0) {
 1848:         # Return this and on the next run, close the branch up if we're 
 1849:         # in a branch
 1850:         if ($self->{BRANCH_DEPTH} > 0 ) {
 1851:             $self->{FORCE_NEXT} = $self->END_BRANCH();
 1852:             $self->{BRANCH_DEPTH}--;
 1853:         }
 1854:         return $self->{HERE};
 1855:     }
 1856:     
 1857:     while (@$next) {
 1858:         # copy the next possibilities over to the branch stack
 1859:         # in the right order
 1860:         push @{$self->{BRANCH_STACK}}, shift @$next;
 1861:     }
 1862: 
 1863:     if ($nextCount >= 2) {
 1864:         $self->{FORCE_NEXT} = $self->BEGIN_BRANCH();
 1865:         $self->{BRANCH_DEPTH}++;
 1866:         return $self->{HERE}; 
 1867:     }
 1868: 
 1869:     # If this is a map and we want to recurse down it... (not filtered out)
 1870:     if ($self->{HERE}->is_map() && 
 1871:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 1872:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 1873:         my $firstResource = $self->{HERE}->map_start();
 1874:         my $finishResource = $self->{HERE}->map_finish();
 1875: 
 1876:         # Odd perl syntax here; $self->new allows one to create a new iterator
 1877:         # can't figure out how to ref this package directly correctly
 1878:         # isn't MAIN::new, __PACKAGE__::new or Apache::lonnavmaps::iterator->new
 1879:         $self->{RECURSIVE_ITERATOR} =
 1880:           Apache::lonnavmaps::iterator->new ($self->{NAV_MAP}, $firstResource, 
 1881:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 1882: 					     $self->{CONDITION});
 1883:     }
 1884: 
 1885:     return $self->{HERE};
 1886: }
 1887: 
 1888: =pod
 1889: 
 1890: The other method available on the iterator is B<getStack>, which returns an array populated with the current 'stack' of maps, as references to the resource objects. Example: This is useful when making the navigation map, as we need to check whether we are under a page map to see if we need to link directly to the resource, or to the page. The first elements in the array will correspond to the top of the stack (most inclusive map).
 1891: 
 1892: =cut
 1893: 
 1894: sub getStack {
 1895:     my $self=shift;
 1896: 
 1897:     my @stack;
 1898: 
 1899:     $self->populateStack(\@stack);
 1900: 
 1901:     return \@stack;
 1902: }
 1903: 
 1904: # Private method: Calls the iterators recursively to populate the stack.
 1905: sub populateStack {
 1906:     my $self=shift;
 1907:     my $stack = shift;
 1908: 
 1909:     push @$stack, $self->{HERE};
 1910: 
 1911:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 1912:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 1913:     }
 1914: }
 1915: 
 1916: 1;
 1917: 
 1918: package Apache::lonnavmaps::resource;
 1919: 
 1920: use Apache::lonnet;
 1921: 
 1922: =pod
 1923: 
 1924: =head1 Object: resource
 1925: 
 1926: A resource object encapsulates a resource in a resource map, allowing easy manipulation of the resource, querying the properties of the resource (including user properties), and represents a reference that can be used as the canonical representation of the resource by lonnavmap clients like renderers.
 1927: 
 1928: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
 1929: 
 1930: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
 1931: 
 1932: =head2 Public Members
 1933: 
 1934: resource objects have a hash called DATA ($resourceRef->{DATA}) that you can store whatever you want in. This allows you to easily do two-pass algorithms without worrying about managing your own resource->data hash.
 1935: 
 1936: =head2 Methods
 1937: 
 1938: =over 4
 1939: 
 1940: =item * B<new>($navmapRef, $idString): The first arg is a reference to the parent navmap object. The second is the idString of the resource itself. 
 1941: 
 1942: =cut
 1943: 
 1944: sub new {
 1945:     # magic invocation to create a class instance
 1946:     my $proto = shift;
 1947:     my $class = ref($proto) || $proto;
 1948:     my $self = {};
 1949: 
 1950:     $self->{NAV_MAP} = shift;
 1951:     $self->{ID} = shift;
 1952: 
 1953:     # Store this new resource in the parent nav map's cache.
 1954:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 1955: 
 1956:     # A hash that can be used by two-pass algorithms to store data
 1957:     # about this resource in. Not used by the resource object
 1958:     # directly.
 1959:     $self->{DATA} = {};
 1960:    
 1961:     bless($self);
 1962:     
 1963:     return $self;
 1964: }
 1965: 
 1966: =pod
 1967: 
 1968: =item * B<is_map>: Returns true if this is a map, false otherwise.
 1969: 
 1970: =item * B<title>: Returns title.
 1971: 
 1972: =item * B<type>: Returns the type of the resource, "start", "normal", or "finish". 
 1973: 
 1974: =item * B<problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field.)
 1975: 
 1976: =back
 1977: 
 1978: =cut
 1979: 
 1980: # private function: simplify the NAV_HASH lookups we keep doing
 1981: # pass the name, and to automatically append my ID, pass a true val on the
 1982: # second param
 1983: sub navHash {
 1984:     my $self = shift;
 1985:     my $param = shift;
 1986:     my $id = shift;
 1987:     return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
 1988: }
 1989: 
 1990: # These info functions can be used directly, as they don't return
 1991: # resource information.
 1992: sub title { my $self=shift; return $self->navHash("title_", 1); }
 1993: sub type { my $self=shift; return $self->navHash("type_", 1); }
 1994: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 1995: # "to" can return a comma seperated list for branches
 1996: sub to { my $self=shift; return $self->navHash("to_", 1); }
 1997: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 1998: sub src { 
 1999:     my $self=shift;
 2000:     return $self->navHash("src_", 1);
 2001: }
 2002: sub symb {
 2003:     my $self=shift;
 2004:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 2005:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 2006:     return &Apache::lonnet::declutter(
 2007:          $self->navHash('map_id_'.$first)) 
 2008:         . '___' . $second . '___' . $symbSrc;
 2009: }
 2010: sub is_problem {
 2011:     my $self=shift;
 2012:     my $src = $self->src();
 2013:     return ($src =~ /problem$/);
 2014: }
 2015: sub is_html {
 2016:     my $self=shift;
 2017:     my $src = $self->src();
 2018:     return ($src =~ /html$/);
 2019: }
 2020: sub is_sequence {
 2021:     my $self=shift;
 2022:     my $src = $self->src();
 2023:     return ($src =~ /sequence$/);
 2024: }
 2025: sub is_page {
 2026:     my $self=shift;
 2027:     my $src = $self->src();
 2028:     return ($src =~ /page$/);
 2029: }
 2030: 
 2031: 
 2032: 
 2033: 
 2034: # Move this into POD: In order to use these correctly, courseopt
 2035: # and useropt need to be generated
 2036: sub parmval {
 2037:     my $self = shift;
 2038:     my $what = shift;
 2039:     my $part = shift || "0";
 2040:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 2041: }
 2042: 
 2043: #####
 2044: # Map Queries
 2045: #####
 2046: 
 2047: # These methods relate to whether or not the resource is a map, and the 
 2048: # attributes of that map.
 2049: 
 2050: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 2051: sub map_finish {
 2052:     my $self = shift;
 2053:     my $src = $self->src();
 2054:     my $res = $self->navHash("map_finish_$src", 0);
 2055:     $res = $self->{NAV_MAP}->getById($res);
 2056:     return $res;
 2057: }
 2058: sub map_start {
 2059:     my $self = shift;
 2060:     my $src = $self->src();
 2061:     my $res = $self->navHash("map_start_$src", 0);
 2062:     $res = $self->{NAV_MAP}->getById($res);
 2063:     return $res;
 2064: }
 2065: sub map_pc {
 2066:     my $self = shift;
 2067:     my $src = $self->src();
 2068:     return $self->navHash("map_pc_$src", 0);
 2069: }
 2070: sub map_type {
 2071:     my $self = shift;
 2072:     my $pc = $self->map_pc();
 2073:     return $self->navHash("map_type_$pc", 0);
 2074: }
 2075: 
 2076: 
 2077: 
 2078: #####
 2079: # Property queries
 2080: #####
 2081: 
 2082: # These functions will be responsible for returning the CORRECT
 2083: # VALUE for the parameter, no matter what. So while they may look
 2084: # like direct calls to parmval, they can be more then that.
 2085: # So, for instance, the duedate function should use the "duedatetype"
 2086: # information, rather then the resource object user.
 2087: 
 2088: =pod
 2089: 
 2090: =head2 Resource Parameters
 2091: 
 2092: In order to use the resource parameters correctly, the nav map must have been instantiated with genCourseAndUserOptions set to true, so the courseopt and useropt is read correctly. Then, you can call these functions to get the relevant parameters for the resource. Each function defaults to "part 0", but can be directed to another part by passing the part as the second parameter.
 2093: 
 2094: These methods are responsible for getting the parameter correct, not merely reflecting the contents of the GDBM hashes. As we move towards dates relative to other dates, these methods should be updated to reflect that. (Then, anybody using these methods won't have to update their code.)
 2095: 
 2096: =over 4
 2097: 
 2098: =item * B<acc>: Get the Client IP/Name Access Control information.
 2099: 
 2100: =item * B<answerdate>: Get the answer-reveal date for the problem.
 2101: 
 2102: =item * B<duedate>: Get the due date for the problem.
 2103: 
 2104: =item * B<tries>: Get the number of tries the student has used on the problem.
 2105: 
 2106: =item * B<maxtries>: Get the number of max tries allowed.
 2107: 
 2108: =item * B<opendate>: Get the open date for the problem.
 2109: 
 2110: =item * B<sig>: Get the significant figures setting.
 2111: 
 2112: =item * B<tol>: Get the tolerance for the problem.
 2113: 
 2114: =item * B<type>: Get the question type for the problem.
 2115: 
 2116: =item * B<weight>: Get the weight for the problem.
 2117: 
 2118: =back
 2119: 
 2120: =cut
 2121: 
 2122: sub acc {
 2123:     (my $self, my $part) = @_;
 2124:     return $self->parmval("acc", $part);
 2125: }
 2126: sub answerdate {
 2127:     (my $self, my $part) = @_;
 2128:     # Handle intervals
 2129:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 2130:         return $self->duedate($part) + 
 2131:             $self->parmval("answerdate", $part);
 2132:     }
 2133:     return $self->parmval("answerdate", $part);
 2134: }
 2135: sub duedate {
 2136:     (my $self, my $part) = @_;
 2137:     return $self->parmval("duedate", $part);
 2138: }
 2139: sub maxtries {
 2140:     (my $self, my $part) = @_;
 2141:     return $self->parmval("maxtries", $part);
 2142: }
 2143: sub opendate {
 2144:     (my $self, my $part) = @_;
 2145:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 2146:         return $self->duedate($part) -
 2147:             $self->parmval("opendate", $part);
 2148:     }
 2149:     return $self->parmval("opendate");
 2150: }
 2151: sub sig {
 2152:     (my $self, my $part) = @_;
 2153:     return $self->parmval("sig", $part);
 2154: }
 2155: sub tol {
 2156:     (my $self, my $part) = @_;
 2157:     return $self->parmval("tol", $part);
 2158: }
 2159: sub type {
 2160:     (my $self, my $part) = @_;
 2161:     return $self->parmval("type", $part);
 2162: }
 2163: sub weight {
 2164:     (my $self, my $part) = @_;
 2165:     return $self->parmval("weight", $part);
 2166: }
 2167: sub tries {
 2168:     my $self = shift;
 2169:     my $part = shift;
 2170:     $part = '0' if (!defined($part));
 2171: 
 2172:     # Make sure return hash is loaded, should error check
 2173:     $self->getReturnHash();
 2174:     
 2175:     my $tries = $self->{RETURN_HASH}->{'resource.'.$part.'.tries'};
 2176:     if (!defined($tries)) {return '0';}
 2177:     return $tries;
 2178: }
 2179: 
 2180: # Multiple things need this
 2181: sub getReturnHash {
 2182:     my $self = shift;
 2183:     
 2184:     if (!defined($self->{RETURN_HASH})) {
 2185:         my %tmpHash = &Apache::lonnet::restore($self->symb());
 2186:         $self->{RETURN_HASH} = \%tmpHash;
 2187:     }
 2188: }       
 2189: 
 2190: ######
 2191: # Status queries
 2192: ######
 2193: 
 2194: # These methods query the status of problems.
 2195: 
 2196: # If we need to count parts, this function determines the number of
 2197: # parts from the metadata. When called, it returns a reference to a list
 2198: # of strings corresponding to the parts. (Thus, using it in a scalar context
 2199: # tells you how many parts you have in the problem:
 2200: # $partcount = scalar($resource->countParts());
 2201: # Don't use $self->{PARTS} directly because you don't know if it's been
 2202: # computed yet.
 2203: 
 2204: =pod
 2205: 
 2206: =head2 Resource misc
 2207: 
 2208: Misc. functions for the resource.
 2209: 
 2210: =over 4
 2211: 
 2212: =item * B<hasDiscussion>: Returns a false value if there has been discussion since the user last logged in, true if there has. Always returns false if the discussion data was not extracted when the nav map was constructed.
 2213: 
 2214: =item * B<getFeedback>: Gets the feedback for the resource and returns the raw feedback string for the resource, or the null string if there is no feedback or the email data was not extracted when the nav map was constructed. Usually used like this:
 2215: 
 2216:  for (split(/\,/, $res->getFeedback())) {
 2217:     my $link = &Apache::lonnet::escape($_);
 2218:     ...
 2219: 
 2220: and use the link as appropriate.
 2221: 
 2222: =cut
 2223: 
 2224: sub hasDiscussion {
 2225:     my $self = shift;
 2226:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 2227: }
 2228: 
 2229: sub getFeedback {
 2230:     my $self = shift;
 2231:     return $self->{NAV_MAP}->getFeedback($self->symb());
 2232: }
 2233: 
 2234: =pod
 2235: 
 2236: =item * B<parts>(): Returns a list reference containing sorted strings corresponding to each part of the problem. To count the number of parts, use the list in a scalar context, and subtract one if greater then two. (One part problems have a part 0. Multi-parts have a part 0, plus a part for each part. You may or may not wish to filter out part 0.)
 2237: 
 2238: =item * B<countParts>(): Returns the number of parts of the problem a student can answer. Thus, for single part problems, returns 1. For multipart, it returns the number of parts in the problem, not including psuedo-part 0.
 2239: 
 2240: =back
 2241: 
 2242: =cut
 2243: 
 2244: sub parts {
 2245:     my $self = shift;
 2246: 
 2247:     $self->extractParts();
 2248:     return $self->{PARTS};
 2249: }
 2250: 
 2251: sub countParts {
 2252:     my $self = shift;
 2253:     
 2254:     my $parts = $self->parts();
 2255:     
 2256:     if (scalar(@{$parts}) == 1) { return 1;}
 2257: 
 2258:     return scalar(@{$parts}) - 1;
 2259: }
 2260: 
 2261: # Private function: Extracts the parts information and saves it
 2262: sub extractParts { 
 2263:     my $self = shift;
 2264:     
 2265:     return if ($self->{PARTS});
 2266: 
 2267:     $self->{PARTS} = [];
 2268: 
 2269:     # Retrieve part count
 2270:     foreach (split(/\,/,&Apache::lonnet::metadata($self->src(), 
 2271:                                                   'allpossiblekeys'))) {
 2272:         if ($_ =~ /^parameter\_(.*)\_opendate$/) {
 2273:             push @{$self->{PARTS}}, $1;
 2274:         }
 2275:     }
 2276:     
 2277:     # Is this possible to do in one line? - Jeremy
 2278:     my @sortedParts = sort @{$self->{PARTS}};
 2279:     $self->{PARTS} = \@sortedParts;
 2280: 
 2281:     return;
 2282: }
 2283: 
 2284: =pod
 2285: 
 2286: =head2 Resource Status
 2287: 
 2288: Problem resources have status information, reflecting their various dates and completion statuses. You can obtain this information and import symbolic constants to represent the status.
 2289: 
 2290: There are two aspects to the status: the date-related information and the completion information.
 2291: 
 2292: Idiomatic usage of these two methods would probably look something like
 2293: 
 2294:  foreach ($resource->parts()) {
 2295:     my $dateStatus = $resource->getDateStatus($_);
 2296:     my $completionStatus = $resource->getCompletionStatus($_);
 2297: 
 2298:     ... use it here ...
 2299:  }
 2300: 
 2301: =over 4
 2302: 
 2303: =item * B<getDateStatus>($part): ($part defaults to 0). A convenience function that returns a symbolic constant telling you about the date status of the part. You should still check to see if there is a due date at all, if you care about that. The possible return values are:
 2304: 
 2305: =back
 2306: 
 2307: B<Date Codes>
 2308: 
 2309: =over 4
 2310: 
 2311: =item * B<OPEN_LATER>: The problem will be opened later.
 2312: 
 2313: =item * B<OPEN>: Open and not yet due.
 2314: 
 2315: 
 2316: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
 2317: 
 2318: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
 2319: 
 2320: =item * B<ANSWER_OPEN>: The answer date is here.
 2321: 
 2322: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
 2323: 
 2324: =back
 2325: 
 2326: =cut
 2327: 
 2328: # Apparently the compiler optimizes these into constants automatically
 2329: sub OPEN_LATER             { return 0; }
 2330: sub OPEN                   { return 1; }
 2331: sub PAST_DUE_NO_ANSWER     { return 2; }
 2332: sub PAST_DUE_ANSWER_LATER  { return 3; }
 2333: sub ANSWER_OPEN            { return 4; }
 2334: sub NOTHING_SET            { return 5; } 
 2335: sub NETWORK_FAILURE        { return 100; }
 2336: 
 2337: # getDateStatus gets the date status for a given problem part. 
 2338: # Because answer date, due date, and open date are fully independent
 2339: # (i.e., it is perfectly possible to *only* have an answer date), 
 2340: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 2341: # (past, future, none given). This function handles this with a decision
 2342: # tree. Read the comments to follow the decision tree.
 2343: 
 2344: sub getDateStatus {
 2345:     my $self = shift;
 2346:     my $part = shift;
 2347:     $part = "0" if (!defined($part));
 2348: 
 2349:     # Always return network failure if there was one.
 2350:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2351: 
 2352:     my $now = time();
 2353: 
 2354:     my $open = $self->opendate($part);
 2355:     my $due = $self->duedate($part);
 2356:     my $answer = $self->answerdate($part);
 2357: 
 2358:     if (!$open && !$due && !$answer) {
 2359:         # no data on the problem at all
 2360:         # should this be the same as "open later"? think multipart.
 2361:         return $self->NOTHING_SET;
 2362:     }
 2363:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 2364:     if (!$due || $now < $due) {return $self->OPEN}
 2365:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 2366:     if ($answer) { return $self->ANSWER_OPEN; }
 2367:     return PAST_DUE_NO_ANSWER;
 2368: }
 2369: 
 2370: =pod
 2371: 
 2372: B<>
 2373: 
 2374: =over 4
 2375: 
 2376: =item * B<getCompletionStatus>($part): ($part defaults to 0.) A convenience function that returns a symbolic constant telling you about the completion status of the part, with the following possible results:
 2377: 
 2378: =back 
 2379: 
 2380: B<Completion Codes>
 2381: 
 2382: =over 4
 2383: 
 2384: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
 2385: 
 2386: =item * B<INCORRECT>: Attempted, but wrong by student.
 2387: 
 2388: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
 2389: 
 2390: =item * B<CORRECT>: Correct or correct by instructor.
 2391: 
 2392: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
 2393: 
 2394: =item * B<EXCUSED>: Excused. Not yet implemented.
 2395: 
 2396: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
 2397: 
 2398: =back
 2399: 
 2400: =cut
 2401: 
 2402: sub NOT_ATTEMPTED         { return 10; }
 2403: sub INCORRECT             { return 11; }
 2404: sub INCORRECT_BY_OVERRIDE { return 12; }
 2405: sub CORRECT               { return 13; }
 2406: sub CORRECT_BY_OVERRIDE   { return 14; }
 2407: sub EXCUSED               { return 15; }
 2408: 
 2409: sub getCompletionStatus {
 2410:     my $self = shift;
 2411:     my $part = shift;
 2412:     $part = "0" if (!defined($part));
 2413:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2414: 
 2415:     # Make sure return hash exists
 2416:     $self->getReturnHash();
 2417:     
 2418:     my $status = $self->{RETURN_HASH}->{'resource.'.$part.'.solved'};
 2419: 
 2420:     # Left as seperate if statements in case we ever do more with this
 2421:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 2422:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 2423:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 2424:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 2425:     if ($status eq 'excused') {return $self->EXCUSED; }
 2426:     return $self->NOT_ATTEMPTED;
 2427: }
 2428: 
 2429: =pod
 2430: 
 2431: B<Composite Status>
 2432: 
 2433: Along with directly returning the date or completion status, the resource object includes a convenience function B<status>() that will combine the two status tidbits into one composite status that can represent the status of the resource as a whole. The precise logic is documented in the comments of the status method. The following results may be returned, all available as methods on the resource object ($res->NETWORK_FAILURE()):
 2434: 
 2435: =over 4
 2436: 
 2437: =item * NETWORK_FAILURE: The network has failed and the information is not available.
 2438: 
 2439: =item * NOTHING_SET: No dates have been set for this problem (part) at all. (Because only certain parts of a multi-part problem may be assigned, this can not be collapsed into "open later", as we don't know a given part will EVER be opened. For single part, this is the same as "OPEN_LATER".)
 2440: 
 2441: =item * CORRECT: For any reason at all, the part is considered correct.
 2442: 
 2443: =item * EXCUSED: For any reason at all, the problem is excused.
 2444: 
 2445: =item * PAST_DUE_NO_ANSWER: The problem is past due, not considered correct, and no answer date is set.
 2446: 
 2447: =item * PAST_DUE_ANSWER_LATER: The problem is past due, not considered correct, and an answer date in the future is set.
 2448: 
 2449: =item * ANSWER_OPEN: The problem is past due, not correct, and the answer is now available.
 2450: 
 2451: =item * OPEN_LATER: The problem is not yet open.
 2452: 
 2453: =item * TRIES_LEFT: The problem is open, has been tried, is not correct, but there are tries left.
 2454: 
 2455: =item * INCORRECT: The problem is open, and all tries have been used without getting the correct answer.
 2456: 
 2457: =item * OPEN: The item is open and not yet tried.
 2458: 
 2459: =back
 2460: 
 2461: =cut
 2462: 
 2463: sub TRIES_LEFT { return 10; }
 2464: 
 2465: sub status {
 2466:     my $self = shift;
 2467:     my $part = shift;
 2468:     if (!defined($part)) { $part = "0"; }
 2469:     my $completionStatus = $self->getCompletionStatus($part);
 2470:     my $dateStatus = $self->getDateStatus($part);
 2471: 
 2472:     # What we have is a two-dimensional matrix with 4 entries on one
 2473:     # dimension and 5 entries on the other, which we want to colorize,
 2474:     # plus network failure and "no date data at all".
 2475: 
 2476:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 2477: 
 2478:     # There are a few whole rows we can dispose of:
 2479:     if ($completionStatus == CORRECT ||
 2480:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 2481:         return CORRECT(); 
 2482:     }
 2483: 
 2484:     # If it's EXCUSED, then return that no matter what
 2485:     if ($completionStatus == EXCUSED) {
 2486:         return EXCUSED; 
 2487:     }
 2488: 
 2489:     if ($dateStatus == NOTHING_SET) {
 2490:         return NOTHING_SET;
 2491:     }
 2492: 
 2493:     # Now we're down to a 3 (incorrect, incorrect_override, not_attempted)
 2494:     # by 4 matrix (date status).
 2495: 
 2496:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 2497:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 2498:         return $dateStatus; 
 2499:     }
 2500: 
 2501:     if ($dateStatus == ANSWER_OPEN) {
 2502:         return ANSWER_OPEN;
 2503:     }
 2504: 
 2505:     # Now: (incorrect, incorrect_override, not_attempted) x 
 2506:     # (open_later), (open)
 2507:     
 2508:     if ($dateStatus == OPEN_LATER) {
 2509:         return OPEN_LATER;
 2510:     }
 2511: 
 2512:     # If it's WRONG...
 2513:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 2514:         # and there are TRIES LEFT:
 2515:         if ($self->tries() < $self->maxtries()) {
 2516:             return TRIES_LEFT;
 2517:         }
 2518:         return INCORRECT; # otherwise, return orange; student can't fix this
 2519:     }
 2520: 
 2521:     # Otherwise, it's untried and open
 2522:     return OPEN; 
 2523: }
 2524: 
 2525: =pod
 2526: 
 2527: =head2 Resource/Nav Map Navigation
 2528: 
 2529: =over 4
 2530: 
 2531: =item * B<getNext>(): Gets the next resource in the navmap after this one.
 2532: 
 2533: =cut
 2534: 
 2535: # For the simple single-link case, to get from a resource to the next
 2536: # resource, you need to look up the "to_" link in the nav hash, then
 2537: # follow that with the "goesto_" link.
 2538: 
 2539: sub getNext {
 2540:     my $self = shift;
 2541:     my $alreadySeenHash = shift;
 2542:     my @branches;
 2543:     my $to = $self->to();
 2544:     foreach my $branch ( split(/\,/, $to) ) {
 2545:         my $choice = $self->{NAV_MAP}->getById($branch);
 2546:         my $next = $choice->goesto();
 2547:         $next = $self->{NAV_MAP}->getById($next);
 2548: 
 2549:         # Don't remember it if we've already seen it or if
 2550: 	# the student doesn't have browse priviledges
 2551: 	my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 2552:         if (!defined($alreadySeenHash) ||
 2553:             !defined($alreadySeenHash->{$next->{ID}}) ||
 2554: 	    ($browsePriv ne '2' && $browsePriv ne 'F')) {
 2555:                 push @branches, $next;
 2556:             }
 2557:     }
 2558:     return \@branches;
 2559: }
 2560: 
 2561: =pod
 2562: 
 2563: =back
 2564: 
 2565: =cut
 2566: 
 2567: 1;
 2568: 
 2569: __END__
 2570: 
 2571: 

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