File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.69: download - view: text, annotated - select for diffs
Tue Oct 8 18:54:39 2002 UTC (21 years, 8 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
* Added alt tags to the status icons for accessibility.
* Handled "ungraded_attempted" status.
        * If the problem is untried, it shows "open" as usual.
        * If the problem is tried and ungraded, no status icon is
          shown and the text "Not yet graded" shows in the last col.
        # If the problem has been graded, the status of the problem shows
          as it usually does for correct & incorrect.
* Fixed two "ROWS" -> "COLS". (Duh.)
* Corrected (?) status message display to get the composite status.
* Corrected some comments.
* Found a subtle dependency on parts having numeric names: != used
  instead of 'ne'. D'oh! That's why Guy's problem wasn't working
  right.

    1: # The LearningOnline Network with CAPA
    2: # Navigate Maps Handler
    3: #
    4: # $Id: lonnavmaps.pm,v 1.69 2002/10/08 18:54:39 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:     # Initialize the nav map
  823:     my $navmap = Apache::lonnavmaps::navmap->new(
  824:                         $ENV{"request.course.fn"}.".db",
  825:                         $ENV{"request.course.fn"}."_parms.db", 1);
  826: 
  827: 
  828:     if (!defined($navmap)) {
  829:         my $requrl = $r->uri;
  830:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
  831:         return HTTP_NOT_ACCEPTABLE;
  832:     }
  833: 
  834:     # Header
  835:     $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
  836:                                           ''));
  837:     $r->print('<script>window.focus();</script>');
  838:     my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  839:     if (defined($desc)) { $r->print("<h2>$desc</h2>\n"); }
  840:     my $date=localtime;
  841:     $r->print("<h3>$date</h3>\n");
  842:     $r->rflush();
  843:     if ($navmap->{LAST_CHECK}) {
  844:         $r->print('<img src="/adm/lonMisc/chat.gif"> New discussion since '.
  845:                   timeToHumanString($navmap->{LAST_CHECK}).
  846:                   '<br><img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'); 
  847:     } else {
  848:         $r->print('<img src="/adm/lonMisc/chat.gif"> Discussions'.
  849:                   '<br><img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'); 
  850:     }
  851:     #if (($currenturl=~/^\/res/) &&
  852:     #    ($currenturl!~/^\/res\/adm/)) {
  853:     #    $r->print('<a href="#curloc">Current Location</a><p>');
  854:     #}
  855: 
  856:     # Check that it's defined
  857:     if (!($navmap->courseMapDefined())) {
  858:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  859:                   '</body></html>');
  860:         return OK;
  861:     }
  862: 
  863:     # Grab a resource object so we have access to the constants; this
  864:     # is technically not proper, but should be harmless
  865:     my $res = $navmap->firstResource();
  866: 
  867:     # Defines a status->color mapping, null string means don't color
  868:     my %colormap = 
  869:     ( $res->NETWORK_FAILURE        => '',
  870:       $res->CORRECT                => '',
  871:       $res->EXCUSED                => '#BBBBFF',
  872:       $res->PAST_DUE_ANSWER_LATER  => '',
  873:       $res->PAST_DUE_NO_ANSWER     => '',
  874:       $res->ANSWER_OPEN            => '#CCFFCC',
  875:       $res->OPEN_LATER             => '',
  876:       $res->TRIES_LEFT             => '',
  877:       $res->INCORRECT              => '',
  878:       $res->OPEN                   => '',
  879:       $res->NOTHING_SET            => ''        );
  880:     # And a special case in the nav map; what to do when the assignment
  881:     # is not yet done and due in less then 24 hours
  882:     my $hurryUpColor = "#FFCCCC";
  883: 
  884:     my %statusIconMap = 
  885:         ( $res->NETWORK_FAILURE    => '',
  886:           $res->NOTHING_SET        => '',
  887:           $res->CORRECT            => 'navmap.correct.gif',
  888:           $res->EXCUSED            => 'navmap.correct.gif',
  889:           $res->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
  890:           $res->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
  891:           $res->ANSWER_OPEN        => 'navmap.wrong.gif',
  892:           $res->OPEN_LATER         => '',
  893:           $res->TRIES_LEFT         => 'navmap.open.gif',
  894:           $res->INCORRECT          => 'navmap.wrong.gif',
  895:           $res->OPEN               => 'navmap.open.gif',
  896:           $res->ATTEMPTED          => '' );
  897: 
  898:     my %iconAltTags = 
  899:         ( 'navmap.correct.gif' => 'Correct',
  900:           'navmap.wrong.gif'   => 'Incorrect',
  901:           'navmap.open.gif'    => 'Open' );
  902: 
  903:     my %condenseStatuses =
  904:         ( $res->NETWORK_FAILURE    => 1,
  905:           $res->NOTHING_SET        => 1,
  906:           $res->CORRECT            => 1 );
  907: 
  908:     my %filterHash;
  909:     # Figure out what we're not displaying
  910:     foreach (split(/\,/, $ENV{"form.filter"})) {
  911:         if ($_) {
  912:             $filterHash{$_} = "1";
  913:         }
  914:     }
  915: 
  916:     my $currenturl = $ENV{'form.postdata'};
  917:     $currenturl=~s/^http\:\/\///;
  918:     $currenturl=~s/^[^\/]+//;
  919:     my $queryAdd = "postdata=" . &Apache::lonnet::escape($currenturl);
  920: 
  921:     $r->print('<a href="navmaps?condition=1&filter=">Show All Resources</a><br /><br />');
  922: 
  923:     # Begin the HTML table
  924:     # four cols: resource + indent, chat+feedback, icon, text string
  925:     $r->print('<table cellspacing="3" cellpadding="0" bgcolor="#FFFFFF">' ."\n");
  926: 
  927:     my $condition = 0;
  928:     if ($ENV{'form.condition'}) {
  929:         $condition = 1;
  930:     }
  931: 
  932:     my $mapIterator = $navmap->getIterator(undef, undef, \%filterHash, $condition);
  933:     my $curRes = $mapIterator->next();
  934:     undef $res; # so we don't accidentally use it later
  935:     my $indentLevel = -1;
  936:     my $indentString = "<img src=\"/adm/lonIcons/whitespace1.gif\" width=\"25\" height=\"1\" alt=\"\" border=\"0\" />";
  937: 
  938:     my $isNewBranch = 0;
  939:     my $now = time();
  940:     my $in24Hours = $now + 24 * 60 * 60;
  941: 
  942:     while ($curRes != $mapIterator->END_NAV_MAP) {
  943:         if ($curRes == $mapIterator->BEGIN_MAP() ||
  944:             $curRes == $mapIterator->BEGIN_BRANCH()) {
  945:             $indentLevel++;
  946:         }
  947:         if ($curRes == $mapIterator->END_MAP() ||
  948:             $curRes == $mapIterator->END_BRANCH()) {
  949:             $indentLevel--;
  950:         }
  951:         if ($curRes == $mapIterator->BEGIN_BRANCH()) {
  952:             $isNewBranch = 1;
  953:         }
  954: 
  955:         # Is this resource being blotted out?
  956:         if (ref($curRes) && !advancedUser() && $curRes->randomout()) {
  957:             $curRes = $mapIterator->next();
  958:             next; # and totally ignore this resource
  959:         }
  960: 
  961:         if (ref($curRes) && $curRes->src()) {
  962: 
  963:             # Step one: Decide which parts to show
  964:             my @parts = @{$curRes->parts()};
  965:             my $multipart = scalar(@parts) > 1;
  966:             my $condensed = 0;
  967:                 
  968:             if ($curRes->is_problem()) {
  969:                 # Is it multipart?
  970: 
  971:                 if ($multipart) {
  972:                     # If it's multipart, see if part 0 is "open"
  973:                     # if it is, display all parts, if it isn't,
  974:                     # just display first
  975:                     if (!$curRes->opendate("0")) {
  976:                         @parts = ("0"); # just display the zero-th part
  977:                         $condensed = 1;
  978:                     } else {
  979:                         # Otherwise, only display part 0 if we want to 
  980:                         # attach feedback or email information to it
  981:                         if ($curRes->hasDiscussion() || $curRes->getFeedback()) {
  982:                             shift @parts;
  983:                         } else {
  984:                             # If there's discussion or feedback, that counts
  985:                             # as a difference, so display the parts.
  986:                             
  987:                             # Now, we decide whether to condense the
  988:                             # parts due to similarity
  989:                             my $status = $curRes->status($parts[1]);
  990:                             my $due = $curRes->duedate($parts[1]);
  991:                             my $open = $curRes->opendate($parts[1]);
  992:                             my $statusAllSame = 1;
  993:                             my $dueAllSame = 1;
  994:                             my $openAllSame = 1;
  995:                             for (my $i = 2; $i < scalar(@parts); $i++) {
  996:                                 if ($curRes->status($parts[$i]) != $status){
  997:                                     $statusAllSame = 0;
  998:                                 }
  999:                                 if ($curRes->duedate($parts[$i]) != $due ) {
 1000:                                     $dueAllSame = 0;
 1001:                                 }
 1002:                                 if ($curRes->opendate($parts[$i]) != $open) {
 1003:                                     $openAllSame = 0;
 1004:                                 }
 1005:                             }
 1006:                             
 1007:                             # $allSame is true if all the statuses were
 1008:                             # the same. Now, if they are all the same and
 1009:                             # match one of the statuses to condense, or they
 1010:                             # are all open with the same due date, or they are
 1011:                             # all OPEN_LATER with the same open date, display the
 1012:                             # status of the first non-zero part (to get the 'correct'
 1013:                             # status right, since 0 is never 'correct' or 'open').
 1014:                             if (($statusAllSame && defined($condenseStatuses{$status})) ||
 1015:                                 ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
 1016:                                 ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
 1017:                                 @parts = ($parts[1]);
 1018:                                 $condensed = 1;
 1019:                             }
 1020:                         }
 1021:                     }
 1022:                 }
 1023: 
 1024:             } else {
 1025:                 @parts[0] = "0"; # this is to get past foreach loop below
 1026:                  # you can consider a non-problem resource as a resource
 1027:                  # with only one part without loss
 1028:             }
 1029: 
 1030:             # Display one part, in event of network error.
 1031:             # If this is a single part, we can at least show the correct
 1032:             # status, but if it's multipart, we're lost.
 1033:             if ($curRes->{RESOURCE_ERROR}) {
 1034:                 @parts = ("0");
 1035:             }
 1036: 
 1037:             # Step two: Show the parts
 1038:             foreach my $part (@parts) {
 1039: 
 1040:                 my $deltalevel = 0; # for inserting the branch icon
 1041:                 my $nonLinkedText = ""; # unlinked stuff after title
 1042:                 
 1043:                 # For each thing we're displaying...
 1044: 
 1045:                 my $stack = $mapIterator->getStack();
 1046:                 my $src = getLinkForResource($stack);
 1047: 
 1048:                 my $srcHasQuestion = $src =~ /\?/;
 1049:                 my $link = $src.
 1050:                     ($srcHasQuestion?'&':'?') .
 1051:                     'symb='.&Apache::lonnet::escape($curRes->symb()).
 1052:                     '"';
 1053:                 my $title = $curRes->title();
 1054:                 my $partLabel = "";
 1055:                 my $newBranchText = "";
 1056: 
 1057:                 # If this is a new branch, label it so
 1058:                 # (temporary, this should be an icon w/ alt text)
 1059:                 if ($isNewBranch) {
 1060:                     $newBranchText = "<img src=\"/adm/lonIcons/branch.gif\" border=\"0\">";
 1061:                     $isNewBranch = 0;
 1062:                     $deltalevel = 1;
 1063:                 }
 1064: 
 1065:                 # links to open and close the folders
 1066:                 my $linkopen = "<a href=\"$link\">";
 1067:                 my $linkclose = "</a>";
 1068: 
 1069:                 my $icon = "<img src=\"/adm/lonIcons/html.gif\" alt=\"\" border=\"0\" />";
 1070:                 if ($curRes->is_problem()) { 
 1071:                     if ($part eq "0" || $condensed) {
 1072:                         $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border=\"0\" />'; 
 1073:                     } else {
 1074:                         $icon = $indentString;
 1075:                     }
 1076:                 }
 1077: 
 1078:                 # Display the correct icon, link to open or shut map
 1079:                 if ($curRes->is_map()) { 
 1080:                     my $mapId = $curRes->map_pc();
 1081:                     my $nowOpen = !defined($filterHash{$mapId});
 1082:                     $icon = $nowOpen ?
 1083:                         "folder_closed.gif" : "folder_opened.gif";
 1084:                     $icon = "<img src=\"/adm/lonIcons/$icon\" alt=\"\" border=\"0\" />";
 1085:                     $linkopen = "<a href=\"/adm/navmaps?filter=";
 1086:                     $linkopen .= ($nowOpen xor $condition) ? 
 1087:                         addToFilter(\%filterHash, $mapId) :
 1088:                         removeFromFilter(\%filterHash, $mapId);
 1089:                     $linkopen .= "&condition=$condition&$queryAdd\">";
 1090:                     $linkclose = "</a>";
 1091: 
 1092:                 }
 1093:                 
 1094:                 my $colorizer = "";
 1095:                 if ($curRes->is_problem()) {
 1096:                     my $status = $curRes->status($part);
 1097:                     my $color = $colormap{$status};
 1098:                     if ($color ne "") {
 1099:                         $colorizer = "bgcolor=\"$color\"";
 1100:                     }
 1101:                 }
 1102: 
 1103:                 if ($curRes->randomout()) {
 1104:                     $nonLinkedText .= ' <i>(hidden)</i> ';
 1105:                 }
 1106: 
 1107:                 # FIRST COL: The resource indentation, branch icon, and name
 1108:                 $r->print("  <tr><td align=\"left\" valign=\"bottom\">\n");
 1109: 
 1110:                 # print indentation
 1111:                 for (my $i = 0; $i < $indentLevel - $deltalevel; $i++) {
 1112:                     $r->print($indentString);
 1113:                 }
 1114: 
 1115:                 $r->print("  ${newBranchText}${linkopen}$icon${linkclose}\n");
 1116: 
 1117:                 if ($curRes->is_problem() && $part ne "0" && !$condensed) { 
 1118:                     $partLabel = " (Part $part)"; 
 1119:                     $title = "";
 1120:                 }
 1121:                 if ($multipart && $condensed) {
 1122:                     $nonLinkedText .= ' (' . $curRes->countParts() . ' parts)';
 1123:                 }
 1124: 
 1125:                 $r->print("  <a href=\"$link\">$title$partLabel</a> $nonLinkedText");
 1126: 
 1127:                 if ($curRes->{RESOURCE_ERROR}) {
 1128:                     $r->print(&Apache::loncommon::help_open_topic ("Navmap_Host_Down",
 1129:                                                   '<font size="-1">Host down</font>'));
 1130:                     }
 1131: 
 1132:                 my $discussionHTML = ""; my $feedbackHTML = "";
 1133: 
 1134:                 # SECOND COL: Is there text or feedback?
 1135:                 if ($curRes->hasDiscussion()) {
 1136:                     $discussionHTML = $linkopen .
 1137:                         '<img border="0" src="/adm/lonMisc/chat.gif" />' .
 1138:                         $linkclose;
 1139:                 }
 1140: 
 1141:                 if ($curRes->getFeedback()) {
 1142:                     my $feedback = $curRes->getFeedback();
 1143:                     foreach (split(/\,/, $feedback)) {
 1144:                         if ($_) {
 1145:                             $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
 1146:                                 . &Apache::lonnet::escape($_) . '">'
 1147:                                 . '<img src="/adm/lonMisc/feedback.gif" '
 1148:                                 . 'border="0" /></a>';
 1149:                         }
 1150:                     }
 1151:                 }
 1152: 
 1153:                 $r->print("<td align=\"left\" valign=\"bottom\">$discussionHTML$feedbackHTML</td>");
 1154: 
 1155:                 # Is this the first displayed part of a multi-part problem
 1156:                 # that has not been condensed, so we should suppress these two
 1157:                 # columns?
 1158:                 my $firstDisplayed = !$condensed && $multipart && $part eq "0";
 1159: 
 1160:                 # THIRD COL: Problem status icon
 1161:                 if ($curRes->is_problem() &&
 1162:                     !$firstDisplayed) {
 1163:                     my $icon = $statusIconMap{$curRes->status($part)};
 1164:                     my $alt = $iconAltTags{$icon};
 1165:                     if ($icon) {
 1166:                         $r->print("<td valign=\"bottom\" width=\"50\" align=\"right\">$linkopen<img src=\"/adm/lonIcons/$icon\" border=\"0\" alt=\"$alt\" />$linkclose</td>\n");
 1167:                     } else {
 1168:                         $r->print("<td></td>\n");
 1169:                     }
 1170:                 } else { # not problem, no icon
 1171:                     $r->print("<td></td>\n");
 1172:                 }
 1173: 
 1174:                 # FOURTH COL: Text description
 1175:                 $r->print("<td $colorizer align=\"right\" valign=\"bottom\">\n");
 1176:                 
 1177:                 if ($curRes->kind() eq "res" &&
 1178:                     $curRes->is_problem() &&
 1179:                     !$firstDisplayed) {
 1180:                     $r->print (getDescription($curRes, $part));
 1181:                 }
 1182:                 if ($curRes->is_map() && advancedUser() && $curRes->randompick()) {
 1183:                     $r->print('(randomly select ' . $curRes->randompick() .')');
 1184:                 }
 1185: 
 1186:                 $r->print("</td></tr>\n");
 1187:             }
 1188:         }
 1189:         $curRes = $mapIterator->next();
 1190:     }
 1191: 
 1192:     $r->print("</table></body></html>");
 1193: 
 1194:     $navmap->untieHashes();
 1195: 
 1196:     return OK;
 1197: }
 1198: 
 1199: # Convenience functions: Returns a string that adds or subtracts
 1200: # the second argument from the first hash, appropriate for the 
 1201: # query string that determines which folders to recurse on
 1202: sub addToFilter {
 1203:     my $hashIn = shift;
 1204:     my $addition = shift;
 1205:     my %hash = %$hashIn;
 1206:     $hash{$addition} = 1;
 1207: 
 1208:     return join (",", keys(%hash));
 1209: }
 1210: 
 1211: sub removeFromFilter {
 1212:     my $hashIn = shift;
 1213:     my $subtraction = shift;
 1214:     my %hash = %$hashIn;
 1215: 
 1216:     delete $hash{$subtraction};
 1217:     return join(",", keys(%hash));
 1218: }
 1219: 
 1220: # Convenience function: Given a stack returned from getStack on the iterator,
 1221: # return the correct src() value.
 1222: # Later, this should add an anchor when we start putting anchors in pages.
 1223: sub getLinkForResource {
 1224:     my $stack = shift;
 1225:     my $res;
 1226: 
 1227:     # Check to see if there are any pages in the stack
 1228:     foreach $res (@$stack) {
 1229:         if (defined($res) && $res->is_page()) {
 1230:             return $res->src();
 1231:         }
 1232:     }
 1233: 
 1234:     # Failing that, return the src of the last resource that is defined
 1235:     # (when we first recurse on a map, it puts an undefined resource
 1236:     # on the bottom because $self->{HERE} isn't defined yet, and we
 1237:     # want the src for the map anyhow)
 1238:     foreach (@$stack) {
 1239:         if (defined($_)) { $res = $_; }
 1240:     }
 1241: 
 1242:     return $res->src();
 1243: }
 1244: 
 1245: # Convenience function: This seperates the logic of how to create
 1246: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
 1247: # etc.) into a seperate function. It takes a resource object as the
 1248: # first parameter, and the part number of the resource as the second.
 1249: # It's basically a big switch statement on the status of the resource.
 1250: 
 1251: sub getDescription {
 1252:     my $res = shift;
 1253:     my $part = shift;
 1254:     my $status = $res->status($part);
 1255: 
 1256:     if ($status == $res->NETWORK_FAILURE) { return ""; }
 1257:     if ($status == $res->NOTHING_SET) {
 1258:         return "Not currently assigned.";
 1259:     }
 1260:     if ($status == $res->OPEN_LATER) {
 1261:         return "Opens: " . timeToHumanString($res->opendate($part));
 1262:     }
 1263:     if ($status == $res->OPEN) {
 1264:         if ($res->duedate()) {
 1265:             return "Due: $status " . timeToHumanString($res->duedate($part));
 1266:         } else {
 1267:             return "Open, no due date";
 1268:         }
 1269:     }
 1270:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
 1271:         return "Answer opens: " . timeToHumanString($res->answerdate($part));
 1272:     }
 1273:     if ($status == $res->PAST_DUE_NO_ANSWER) {
 1274:         return "Was Due: " . timeToHumanString($res->duedate($part));
 1275:     }
 1276:     if ($status == $res->ANSWER_OPEN) {
 1277:         return "Answer available";
 1278:     }
 1279:     if ($status == $res->EXCUSED) {
 1280:         return "Excused by instructor";
 1281:     }
 1282:     if ($status == $res->ATTEMPTED) {
 1283:         return "Not yet graded.";
 1284:     }
 1285:     if ($status == $res->TRIES_LEFT) {
 1286:         my $tries = $res->tries();
 1287:         my $maxtries = $res->maxtries();
 1288:         my $triesString = "($tries of $maxtries tries used)";
 1289:         if ($res->duedate()) {
 1290:             return "Due: $status " . timeToHumanString($res->duedate($part)) .
 1291:                 " $triesString";
 1292:         } else {
 1293:             return "No due date $triesString";
 1294:         }
 1295:     }
 1296: }
 1297: 
 1298: sub advancedUser {
 1299:     return $ENV{'user.adv'};
 1300: }
 1301: 
 1302: # I want to change this into something more human-friendly. For
 1303: # now, this is a simple call to localtime. The final function
 1304: # probably belongs in loncommon.
 1305: sub timeToHumanString {
 1306:     my ($time) = @_;
 1307:     # zero, '0' and blank are bad times
 1308:     if ($time) {
 1309:         return localtime($time);
 1310:     } else {
 1311:         return 'Never';
 1312:     }
 1313: }
 1314: 
 1315: 1;
 1316: 
 1317: package Apache::lonnavmaps::navmap;
 1318: 
 1319: # LEFT:
 1320: # * Actual handler code (multi-part)
 1321: # * Branches (aieee!) (and conditionals)
 1322: 
 1323: =pod
 1324: 
 1325: 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.
 1326: 
 1327: =head1 navmap object: Encapsulating the compiled nav map
 1328: 
 1329: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
 1330: 
 1331: 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.
 1332: 
 1333: You must obtain resource objects through the navmap object.
 1334: 
 1335: =head2 Methods
 1336: 
 1337: =over 4
 1338: 
 1339: =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.
 1340: 
 1341: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
 1342: 
 1343: =cut
 1344: 
 1345: use strict;
 1346: use GDBM_File;
 1347: 
 1348: sub new {
 1349:     # magic invocation to create a class instance
 1350:     my $proto = shift;
 1351:     my $class = ref($proto) || $proto;
 1352:     my $self = {};
 1353: 
 1354:     $self->{NAV_HASH_FILE} = shift;
 1355:     $self->{PARM_HASH_FILE} = shift;
 1356:     $self->{GENERATE_COURSE_USER_OPT} = shift;
 1357:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
 1358: 
 1359:     # Resource cache stores navmapresource's as we reference them. We generate
 1360:     # them on-demand so we don't pay for creating resources unless we use them.
 1361:     $self->{RESOURCE_CACHE} = {};
 1362: 
 1363:     # Network failure flag, if we accessed the course or user opt and
 1364:     # failed
 1365:     $self->{NETWORK_FAILURE} = 0;
 1366: 
 1367:     # tie the nav hash
 1368:     my %navmaphash;
 1369:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
 1370:               &GDBM_READER(), 0640))) {
 1371:         return undef;
 1372:     }
 1373:     $self->{NAV_HASH} = \%navmaphash;
 1374:     
 1375:     my %parmhash;
 1376:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
 1377:               &GDBM_READER(), 0640)))
 1378:     {
 1379:         untie $self->{PARM_HASH};
 1380:         return undef;
 1381:     }
 1382:     $self->{PARM_HASH} = \%parmhash;
 1383:     $self->{HASH_TIED} = 1;
 1384: 
 1385:     # If the course opt hash and the user opt hash should be generated,
 1386:     # generate them
 1387:     if ($self->{GENERATE_COURSE_USER_OPT}) {
 1388:         my $uname=$ENV{'user.name'};
 1389:         my $udom=$ENV{'user.domain'};
 1390:         my $uhome=$ENV{'user.home'};
 1391:         my $cid=$ENV{'request.course.id'};
 1392:         my $chome=$ENV{'course.'.$cid.'.home'};
 1393:         my ($cdom,$cnum)=split(/\_/,$cid);
 1394:         
 1395:         my $userprefix=$uname.'_'.$udom.'_';
 1396:         
 1397:         my %courserdatas; my %useropt; my %courseopt;
 1398:         unless ($uhome eq 'no_host') { 
 1399: # ------------------------------------------------- Get coursedata (if present)
 1400:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1401:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1402:                                                  ':resourcedata',$chome);
 1403:                 if ($reply!~/^error\:/) {
 1404:                     $courserdatas{$cid}=$reply;
 1405:                     $courserdatas{$cid.'.last_cache'}=time;
 1406:                 }
 1407:                 # check to see if network failed
 1408:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1409:                 {
 1410:                     $self->{NETWORK_FAILURE} = 1;
 1411:                 }
 1412:             }
 1413:             foreach (split(/\&/,$courserdatas{$cid})) {
 1414:                 my ($name,$value)=split(/\=/,$_);
 1415:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1416:                     &Apache::lonnet::unescape($value);
 1417:             }
 1418: # --------------------------------------------------- Get userdata (if present)
 1419:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1420:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1421:                 if ($reply!~/^error\:/) {
 1422:                     $userrdatas{$uname.'___'.$udom}=$reply;
 1423:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1424:                 }
 1425:                 # check to see if network failed
 1426:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1427:                 {
 1428:                     $self->{NETWORK_FAILURE} = 1;
 1429:                 }
 1430:             }
 1431:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 1432:                 my ($name,$value)=split(/\=/,$_);
 1433:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1434:                     &Apache::lonnet::unescape($value);
 1435:             }
 1436:             $self->{COURSE_OPT} = \%courseopt;
 1437:             $self->{USER_OPT} = \%useropt;
 1438:         }
 1439:     }   
 1440: 
 1441:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
 1442:         my $cid=$ENV{'request.course.id'};
 1443:         my ($cdom,$cnum)=split(/\_/,$cid);
 1444:         
 1445:         my %emailstatus = &Apache::lonnet::dump('email_status');
 1446:         my $logoutTime = $emailstatus{'logout'};
 1447:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
 1448:         $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
 1449:                                $courseLeaveTime : $logoutTime);
 1450:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 1451:                                                    $cdom, $cnum);
 1452:         my %feedback=();
 1453:         my %error=();
 1454:         my $keys = &Apache::lonnet::reply('keys:'.
 1455:                                           $ENV{'user.domain'}.':'.
 1456:                                           $ENV{'user.name'}.':nohist_email',
 1457:                                           $ENV{'user.home'});
 1458: 
 1459:         foreach my $msgid (split(/\&/, $keys)) {
 1460:             $msgid=&Apache::lonnet::unescape($msgid);
 1461:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
 1462:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
 1463:                 my ($what,$url)=($1,$2);
 1464:                 my %status=
 1465:                     &Apache::lonnet::get('email_status',[$msgid]);
 1466:                 if ($status{$msgid}=~/^error\:/) { 
 1467:                     $status{$msgid}=''; 
 1468:                 }
 1469:                 
 1470:                 if (($status{$msgid} eq 'new') || 
 1471:                     (!$status{$msgid})) { 
 1472:                     if ($what eq 'Error') {
 1473:                         $error{$url}.=','.$msgid; 
 1474:                     } else {
 1475:                         $feedback{$url}.=','.$msgid;
 1476:                     }
 1477:                 }
 1478:             }
 1479:         }
 1480:         
 1481:         $self->{FEEDBACK} = \%feedback;
 1482:         $self->{ERROR_MSG} = \%error; # what is this? JB
 1483:         $self->{DISCUSSION_TIME} = \%discussiontime;
 1484:         $self->{EMAIL_STATUS} = \%emailstatus;
 1485:         
 1486:     }    
 1487:     
 1488:     bless($self);
 1489:         
 1490:     return $self;
 1491: }
 1492: 
 1493: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1494: sub courseMapDefined {
 1495:     my $self = shift;
 1496:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1497: 
 1498:     my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
 1499:     my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
 1500:     return $firstres && $lastres;
 1501: }
 1502: 
 1503: sub getIterator {
 1504:     my $self = shift;
 1505:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 1506:                                                      shift, undef, shift);
 1507:     return $iterator;
 1508: }
 1509: 
 1510: # unties the hash when done
 1511: sub untieHashes {
 1512:     my $self = shift;
 1513:     untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
 1514:     untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
 1515:     $self->{HASH_TIED} = 0;
 1516: }
 1517: 
 1518: # when the object is destroyed, be sure to untie all the hashes we tied.
 1519: sub DESTROY {
 1520:     my $self = shift;
 1521:     $self->untieHashes();
 1522: }
 1523: 
 1524: # Private function: Does the given resource (as a symb string) have
 1525: # current discussion? Returns 0 if chat/mail data not extracted.
 1526: sub hasDiscussion {
 1527:     my $self = shift;
 1528:     my $symb = shift;
 1529:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1530: 
 1531:     return $self->{DISCUSSION_TIME}->{$symb} >
 1532:            $self->{LAST_CHECK};
 1533: }
 1534: 
 1535: # Private function: Does the given resource (as a symb string) have
 1536: # current feedback? Returns the string in the feedback hash, which
 1537: # will be false if it does not exist.
 1538: sub getFeedback { 
 1539:     my $self = shift;
 1540:     my $symb = shift;
 1541: 
 1542:     if (!defined($self->{FEEDBACK})) { return ""; }
 1543:     
 1544:     return $self->{FEEDBACK}->{$symb};
 1545: }
 1546: 
 1547: =pod
 1548: 
 1549: =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.
 1550: 
 1551: =cut
 1552: 
 1553: # The strategy here is to cache the resource objects, and only construct them
 1554: # as we use them. The real point is to prevent reading any more from the tied
 1555: # hash then we have to, which should hopefully alleviate speed problems.
 1556: # Caching is just an incidental detail I throw in because it makes sense.
 1557: 
 1558: sub getById {
 1559:     my $self = shift;
 1560:     my $id = shift;
 1561: 
 1562:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1563:     {
 1564:         return $self->{RESOURCE_CACHE}->{$id};
 1565:     }
 1566: 
 1567:     # resource handles inserting itself into cache.
 1568:     return Apache::lonnavmaps::resource->new($self, $id);
 1569: }
 1570: 
 1571: =pod
 1572: 
 1573: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
 1574: 
 1575: =cut
 1576: 
 1577: sub firstResource {
 1578:     my $self = shift;
 1579:     my $firstResource = $self->{NAV_HASH}->{'map_start_' .
 1580:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1581:     return $self->getById($firstResource);
 1582: }
 1583: 
 1584: =pod
 1585: 
 1586: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
 1587: 
 1588: =cut
 1589: 
 1590: sub finishResource {
 1591:     my $self = shift;
 1592:     my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
 1593:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1594:     return $self->getById($firstResource);
 1595: }
 1596: 
 1597: # -------------------------------------------- Figure out a cascading parameter
 1598: #
 1599: # For this function to work
 1600: #
 1601: # * parmhash needs to be tied
 1602: # * courseopt and useropt need to be initialized for this user and course
 1603: #
 1604: 
 1605: sub parmval {
 1606:     my $self = shift;
 1607:     my ($what,$symb)=@_;
 1608:     my $cid=$ENV{'request.course.id'};
 1609:     my $csec=$ENV{'request.course.sec'};
 1610:     my $uname=$ENV{'user.name'};
 1611:     my $udom=$ENV{'user.domain'};
 1612: 
 1613:     unless ($symb) { return ''; }
 1614:     my $result='';
 1615: 
 1616:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1617: 
 1618: # ----------------------------------------------------- Cascading lookup scheme
 1619:     my $rwhat=$what;
 1620:     $what=~s/^parameter\_//;
 1621:     $what=~s/\_/\./;
 1622: 
 1623:     my $symbparm=$symb.'.'.$what;
 1624:     my $mapparm=$mapname.'___(all).'.$what;
 1625:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1626: 
 1627:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 1628:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 1629:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 1630: 
 1631:     my $courselevel= $usercourseprefix.'.'.$what;
 1632:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 1633:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 1634: 
 1635:     my $useropt = $self->{USER_OPT};
 1636:     my $courseopt = $self->{COURSE_OPT};
 1637:     my $parmhash = $self->{PARM_HASH};
 1638: 
 1639: # ---------------------------------------------------------- first, check user
 1640:     if ($uname and defined($useropt)) {
 1641:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 1642:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 1643:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 1644:     }
 1645: 
 1646: # ------------------------------------------------------- second, check course
 1647:     if ($csec and defined($courseopt)) {
 1648:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 1649:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 1650:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 1651:     }
 1652: 
 1653:     if (defined($courseopt)) {
 1654:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 1655:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 1656:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 1657:     }
 1658: 
 1659: # ----------------------------------------------------- third, check map parms
 1660: 
 1661:     my $thisparm=$$parmhash{$symbparm};
 1662:     if (defined($thisparm)) { return $thisparm; }
 1663: 
 1664: # ----------------------------------------------------- fourth , check default
 1665: 
 1666:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 1667:     if (defined($default)) { return $default}
 1668: 
 1669: # --------------------------------------------------- fifth , cascade up parts
 1670: 
 1671:     my ($space,@qualifier)=split(/\./,$rwhat);
 1672:     my $qualifier=join('.',@qualifier);
 1673:     unless ($space eq '0') {
 1674:         my ($part,$id)=split(/\_/,$space);
 1675:         if ($id) {
 1676:             my $partgeneral=$self->parmval($part.".$qualifier",$symb);
 1677:             if (defined($partgeneral)) { return $partgeneral; }
 1678:         } else {
 1679:             my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
 1680:             if (defined($resourcegeneral)) { return $resourcegeneral; }
 1681:         }
 1682:     }
 1683:     return '';
 1684: }
 1685: 
 1686: 
 1687: 1;
 1688: 
 1689: package Apache::lonnavmaps::iterator;
 1690: 
 1691: # This package must precede "navmap" because "navmap" uses it. In
 1692: # order to keep the documentation order straight, the iterator is documented
 1693: # after the navmap object.
 1694: 
 1695: =pod
 1696: 
 1697: =back
 1698: 
 1699: =head1 navmap Iterator
 1700: 
 1701: 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.
 1702: 
 1703: 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:
 1704: 
 1705: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 1706: 
 1707: To get the next thing from the iterator, call B<next>:
 1708: 
 1709: C<my $nextThing = $resourceIterator-E<gt>next()>
 1710: 
 1711: getIterator behaves as follows:
 1712: 
 1713: =over 4
 1714: 
 1715: =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.
 1716: 
 1717: 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.
 1718: 
 1719: 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:
 1720: 
 1721: =over 4
 1722: 
 1723: =item * some list of tokens here
 1724: 
 1725: =back
 1726: 
 1727: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_NAV_MAP. (Perl will automatically optimize these into constants.
 1728: 
 1729: =cut
 1730: 
 1731: # Here are the tokens for the iterator:
 1732: 
 1733: sub END_NAV_MAP { return 0; }  # Represents end of entire nav map
 1734: sub BEGIN_MAP { return 1; }    # begining of a new map
 1735: sub END_MAP { return 2; }      # end of the map
 1736: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 1737: sub END_BRANCH { return 4; }   # end of a branch
 1738: 
 1739: # Params: nav map, start resource, end resource, filter, condition, 
 1740: # already seen hash ref
 1741: 
 1742: sub new {
 1743:     # magic invocation to create a class instance
 1744:     my $proto = shift;
 1745:     my $class = ref($proto) || $proto;
 1746:     my $self = {};
 1747: 
 1748:     $self->{NAV_MAP} = shift;
 1749:     return undef unless ($self->{NAV_MAP});
 1750: 
 1751:     # Handle the parameters
 1752:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 1753:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 1754: 
 1755:     # If the given resources are just the ID of the resource, get the
 1756:     # objects
 1757:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 1758:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 1759:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 1760:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 1761: 
 1762:     $self->{FILTER} = shift;
 1763: 
 1764:     # A hash, used as a set, of resource already seen
 1765:     $self->{ALREADY_SEEN} = shift;
 1766:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 1767:     $self->{CONDITION} = shift;
 1768: 
 1769:     # Flag: Have we started yet? If not, the first action is to return BEGIN_MAP.
 1770:     $self->{STARTED} = 0;
 1771: 
 1772:     # Should we continue calling the recursive iterator, if any?
 1773:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1774:     # The recursive iterator, if any
 1775:     $self->{RECURSIVE_ITERATOR} = undef;
 1776:     # Are we recursing on a map, or a branch?
 1777:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 1778:     # And the count of how deep it is, so that this iterator can keep track of
 1779:     # when to pick back up again.
 1780:     $self->{RECURSIVE_DEPTH} = 0;
 1781: 
 1782:     # For keeping track of our branches, we maintain our own stack
 1783:     $self->{BRANCH_STACK} = [];
 1784:     # If the size shrinks, we exhausted a branch
 1785:     $self->{BRANCH_STACK_SIZE} = 0;
 1786:     $self->{BRANCH_DEPTH} = 0;
 1787: 
 1788:     # For returning two things in a forced sequence
 1789:     $self->{FORCE_NEXT} = undef;
 1790: 
 1791:     # Start with the first resource
 1792:     push @{$self->{BRANCH_STACK}}, $self->{FIRST_RESOURCE};
 1793:     $self->{BRANCH_STACK_SIZE} = 1;
 1794: 
 1795:     bless($self);
 1796:     return $self;
 1797: }
 1798: 
 1799: # FIXME: Document this.
 1800: sub cancelTopRecursion {
 1801:     my $self = shift;
 1802:     
 1803:     if (!$self->{RECURSIVE_ITERATOR_FLAG}) {return;}
 1804: 
 1805:     # is this the iterator we want to kill?
 1806:     if ($self->{RECURSIVE_ITERATOR_FLAG} && 
 1807:         !$self->{RECURSIVE_ITERATOR}->{RECURSIVE_ITERATOR_FLAG}) {
 1808:         $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1809:         undef $self->{RECURSIVE_ITERATOR};
 1810:         return;
 1811:     }
 1812:     
 1813:     $self->{RECURSIVE_ITERATOR}->cancelTopRecursion();
 1814: }
 1815: 
 1816: # Note... this function is *touchy*. I strongly recommend tracing
 1817: # through it with the debugger a few times on a non-trivial map before
 1818: # modifying it. Order is *everything*.
 1819: # FIXME: Doc that skipMap will prevent the recursion, if any.
 1820: sub next {
 1821:     my $self = shift;
 1822:     my $skipMap = shift;
 1823:     
 1824:     # Iterator logic goes here
 1825: 
 1826:     # Are we using a recursive iterator? If so, pull from that and
 1827:     # watch the depth; we want to resume our level at the correct time.
 1828:     if ($self->{RECURSIVE_ITERATOR_FLAG})
 1829:     {
 1830:         # grab the next from the recursive iterator
 1831:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 1832:         
 1833:         # is it a begin or end map? Update depth if so
 1834:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 1835:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 1836: 
 1837:         # Are we back at depth 0? If so, stop recursing.
 1838:         if ($self->{RECURSIVE_DEPTH} == 0) {
 1839:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1840:         }
 1841:         
 1842:         return $next;
 1843:     }
 1844: 
 1845:     # Is this return value pre-determined?
 1846:     if (defined($self->{FORCE_NEXT})) {
 1847:         my $tmp = $self->{FORCE_NEXT};
 1848:         $self->{FORCE_NEXT} = undef;
 1849:         return $tmp;
 1850:     }
 1851: 
 1852:     # Is there a current resource to grab? If not, then return
 1853:     # END_BRANCH and END_MAP in succession.
 1854:     if (scalar(@{$self->{BRANCH_STACK}}) == 0) {
 1855:         if ($self->{BRANCH_DEPTH} > 0) {
 1856:             $self->{FORCE_NEXT} = $self->END_MAP();
 1857:             $self->{BRANCH_DEPTH}--;
 1858:             return $self->END_BRANCH();
 1859:         } else {
 1860:             return $self->END_MAP();
 1861:         }
 1862:     }
 1863: 
 1864:     # Have we not yet begun? If not, return BEGIN_MAP and 
 1865:     # remember that we've started.
 1866:     if ( !$self->{STARTED} ) {
 1867:         $self->{STARTED} = 1;
 1868:         return $self->BEGIN_MAP;
 1869:     }
 1870: 
 1871:     # Did the branch stack shrink since last run? If so,
 1872:     # we exhausted a branch last time, therefore, we're about
 1873:     # to start a new one. (We know because we already checked to see
 1874:     # if the stack was empty.)
 1875:     if ( scalar (@{$self->{BRANCH_STACK}}) < $self->{BRANCH_STACK_SIZE}) {
 1876:         $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 1877:         $self->{BRANCH_DEPTH}++;
 1878:         return $self->BEGIN_BRANCH();
 1879:     }
 1880: 
 1881:     # Remember the size for comparision next time.
 1882:     $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 1883: 
 1884:     # If the next resource we mean to return is going to need
 1885:     # a lower branch level, terminate branches until we get 
 1886:     # there.
 1887: 
 1888:     # Get the next resource in the branch
 1889:     $self->{HERE} = pop @{$self->{BRANCH_STACK}};
 1890: 
 1891:     # Are we at the right depth? If not, close a branch and return
 1892:     # the current resource onto the branch stack
 1893:     if (defined($self->{HERE}->{DATA}->{ITERATOR_DEPTH})
 1894:         && $self->{HERE}->{DATA}->{ITERATOR_DEPTH} <
 1895:         $self->{BRANCH_DEPTH} ) {
 1896:         $self->{BRANCH_DEPTH}--;
 1897:         # return it so we can pick it up eventually
 1898:         push @{$self->{BRANCH_STACK}}, $self->{HERE};
 1899:         return $self->END_BRANCH();
 1900:     }
 1901: 
 1902:     # We always return it after this point and never before
 1903:     # (proof: look at just the return statements), so we
 1904:     # remember that we've seen this.
 1905:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 1906:     
 1907:     # Are we at the utter end? If so, return the END_NAV_MAP marker.
 1908:     if ($self->{HERE} == $self->{NAV_MAP}->finishResource() ) {
 1909:         $self->{FORCE_NEXT} = $self->END_NAV_MAP;
 1910:         return $self->{HERE};
 1911:     }
 1912:     
 1913:     # Get the next possible resources
 1914:     my $nextUnfiltered = $self->{HERE}->getNext();
 1915:     my $next = [];
 1916: 
 1917:     # filter the next possibilities to remove things we've 
 1918:     # already seen. Also, remember what branch depth they should
 1919:     # be displayed at, since there's no other reliable way to tell.
 1920:     foreach (@$nextUnfiltered) {
 1921:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 1922:             push @$next, $_;
 1923:             $_->{DATA}->{ITERATOR_DEPTH} = 
 1924:                 $self->{BRANCH_DEPTH} + 1;
 1925:         }
 1926:     }
 1927: 
 1928:     # Handle branch cases:
 1929:     # Nothing is available next: BRANCH_END
 1930:     # 1 thing next: standard non-branch
 1931:     # 2+ things next: have some branches
 1932:     my $nextCount = scalar(@$next);
 1933:     if ($nextCount == 0) {
 1934:         # Return this and on the next run, close the branch up if we're 
 1935:         # in a branch
 1936:         if ($self->{BRANCH_DEPTH} > 0 ) {
 1937:             $self->{FORCE_NEXT} = $self->END_BRANCH();
 1938:             $self->{BRANCH_DEPTH}--;
 1939:         }
 1940:     }
 1941:     
 1942:     while (@$next) {
 1943:         # copy the next possibilities over to the branch stack
 1944:         # in the right order
 1945:         push @{$self->{BRANCH_STACK}}, shift @$next;
 1946:     }
 1947: 
 1948:     if ($nextCount >= 2) {
 1949:         $self->{FORCE_NEXT} = $self->BEGIN_BRANCH();
 1950:         $self->{BRANCH_DEPTH}++;
 1951:         return $self->{HERE}; 
 1952:     }
 1953: 
 1954:     # If this is a map and we want to recurse down it... (not filtered out)
 1955:     if ($self->{HERE}->is_map() && !$skipMap && 
 1956:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 1957:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 1958:         my $firstResource = $self->{HERE}->map_start();
 1959:         my $finishResource = $self->{HERE}->map_finish();
 1960: 
 1961:         $self->{RECURSIVE_ITERATOR} =
 1962:           Apache::lonnavmaps::iterator->new ($self->{NAV_MAP}, $firstResource, 
 1963:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 1964:                                              $self->{CONDITION});
 1965:     }
 1966: 
 1967:     return $self->{HERE};
 1968: }
 1969: 
 1970: =pod
 1971: 
 1972: 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).
 1973: 
 1974: =cut
 1975: 
 1976: sub getStack {
 1977:     my $self=shift;
 1978: 
 1979:     my @stack;
 1980: 
 1981:     $self->populateStack(\@stack);
 1982: 
 1983:     return \@stack;
 1984: }
 1985: 
 1986: # Private method: Calls the iterators recursively to populate the stack.
 1987: sub populateStack {
 1988:     my $self=shift;
 1989:     my $stack = shift;
 1990: 
 1991:     push @$stack, $self->{HERE};
 1992: 
 1993:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 1994:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 1995:     }
 1996: }
 1997: 
 1998: 1;
 1999: 
 2000: package Apache::lonnavmaps::resource;
 2001: 
 2002: use Apache::lonnet;
 2003: 
 2004: =pod
 2005: 
 2006: =head1 Object: resource
 2007: 
 2008: 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.
 2009: 
 2010: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
 2011: 
 2012: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
 2013: 
 2014: =head2 Public Members
 2015: 
 2016: 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.
 2017: 
 2018: =head2 Methods
 2019: 
 2020: =over 4
 2021: 
 2022: =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. 
 2023: 
 2024: =cut
 2025: 
 2026: sub new {
 2027:     # magic invocation to create a class instance
 2028:     my $proto = shift;
 2029:     my $class = ref($proto) || $proto;
 2030:     my $self = {};
 2031: 
 2032:     $self->{NAV_MAP} = shift;
 2033:     $self->{ID} = shift;
 2034: 
 2035:     # Store this new resource in the parent nav map's cache.
 2036:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 2037:     $self->{RESOURCE_ERROR} = 0;
 2038: 
 2039:     # A hash that can be used by two-pass algorithms to store data
 2040:     # about this resource in. Not used by the resource object
 2041:     # directly.
 2042:     $self->{DATA} = {};
 2043:    
 2044:     bless($self);
 2045:     
 2046:     return $self;
 2047: }
 2048: 
 2049: =pod
 2050: 
 2051: =item * B<is_map>: Returns true if this is a map, false otherwise.
 2052: 
 2053: =item * B<title>: Returns title.
 2054: 
 2055: =item * B<type>: Returns the type of the resource, "start", "normal", or "finish". 
 2056: 
 2057: =item * B<problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field.)
 2058: 
 2059: =back
 2060: 
 2061: =cut
 2062: 
 2063: # private function: simplify the NAV_HASH lookups we keep doing
 2064: # pass the name, and to automatically append my ID, pass a true val on the
 2065: # second param
 2066: sub navHash {
 2067:     my $self = shift;
 2068:     my $param = shift;
 2069:     my $id = shift;
 2070:     return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
 2071: }
 2072: 
 2073: # These info functions can be used directly, as they don't return
 2074: # resource information.
 2075: sub title { my $self=shift; return $self->navHash("title_", 1); }
 2076: sub type { my $self=shift; return $self->navHash("type_", 1); }
 2077: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 2078: # "to" can return a comma seperated list for branches
 2079: sub to { my $self=shift; return $self->navHash("to_", 1); }
 2080: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 2081: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 2082: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 2083: sub randompick { 
 2084:     my $self = shift;
 2085:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
 2086:                                                '.0.parameter_randompick'};
 2087: }
 2088: sub src { 
 2089:     my $self=shift;
 2090:     return $self->navHash("src_", 1);
 2091: }
 2092: sub symb {
 2093:     my $self=shift;
 2094:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 2095:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 2096:     return &Apache::lonnet::declutter(
 2097:          $self->navHash('map_id_'.$first)) 
 2098:         . '___' . $second . '___' . $symbSrc;
 2099: }
 2100: sub is_problem {
 2101:     my $self=shift;
 2102:     my $src = $self->src();
 2103:     return ($src =~ /problem$/);
 2104: }
 2105: sub is_html {
 2106:     my $self=shift;
 2107:     my $src = $self->src();
 2108:     return ($src =~ /html$/);
 2109: }
 2110: sub is_sequence {
 2111:     my $self=shift;
 2112:     my $src = $self->src();
 2113:     return ($src =~ /sequence$/);
 2114: }
 2115: sub is_page {
 2116:     my $self=shift;
 2117:     my $src = $self->src();
 2118:     return ($src =~ /page$/);
 2119: }
 2120: 
 2121: 
 2122: 
 2123: 
 2124: # Move this into POD: In order to use these correctly, courseopt
 2125: # and useropt need to be generated
 2126: sub parmval {
 2127:     my $self = shift;
 2128:     my $what = shift;
 2129:     my $part = shift || "0";
 2130:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 2131: }
 2132: 
 2133: #####
 2134: # Map Queries
 2135: #####
 2136: 
 2137: # These methods relate to whether or not the resource is a map, and the 
 2138: # attributes of that map.
 2139: 
 2140: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 2141: sub map_finish {
 2142:     my $self = shift;
 2143:     my $src = $self->src();
 2144:     my $res = $self->navHash("map_finish_$src", 0);
 2145:     $res = $self->{NAV_MAP}->getById($res);
 2146:     return $res;
 2147: }
 2148: sub map_start {
 2149:     my $self = shift;
 2150:     my $src = $self->src();
 2151:     my $res = $self->navHash("map_start_$src", 0);
 2152:     $res = $self->{NAV_MAP}->getById($res);
 2153:     return $res;
 2154: }
 2155: sub map_pc {
 2156:     my $self = shift;
 2157:     my $src = $self->src();
 2158:     return $self->navHash("map_pc_$src", 0);
 2159: }
 2160: sub map_type {
 2161:     my $self = shift;
 2162:     my $pc = $self->map_pc();
 2163:     return $self->navHash("map_type_$pc", 0);
 2164: }
 2165: 
 2166: 
 2167: 
 2168: #####
 2169: # Property queries
 2170: #####
 2171: 
 2172: # These functions will be responsible for returning the CORRECT
 2173: # VALUE for the parameter, no matter what. So while they may look
 2174: # like direct calls to parmval, they can be more then that.
 2175: # So, for instance, the duedate function should use the "duedatetype"
 2176: # information, rather then the resource object user.
 2177: 
 2178: =pod
 2179: 
 2180: =head2 Resource Parameters
 2181: 
 2182: 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.
 2183: 
 2184: 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.)
 2185: 
 2186: =over 4
 2187: 
 2188: =item * B<acc>: Get the Client IP/Name Access Control information.
 2189: 
 2190: =item * B<answerdate>: Get the answer-reveal date for the problem.
 2191: 
 2192: =item * B<duedate>: Get the due date for the problem.
 2193: 
 2194: =item * B<tries>: Get the number of tries the student has used on the problem.
 2195: 
 2196: =item * B<maxtries>: Get the number of max tries allowed.
 2197: 
 2198: =item * B<opendate>: Get the open date for the problem.
 2199: 
 2200: =item * B<sig>: Get the significant figures setting.
 2201: 
 2202: =item * B<tol>: Get the tolerance for the problem.
 2203: 
 2204: =item * B<type>: Get the question type for the problem.
 2205: 
 2206: =item * B<weight>: Get the weight for the problem.
 2207: 
 2208: =back
 2209: 
 2210: =cut
 2211: 
 2212: sub acc {
 2213:     (my $self, my $part) = @_;
 2214:     return $self->parmval("acc", $part);
 2215: }
 2216: sub answerdate {
 2217:     (my $self, my $part) = @_;
 2218:     # Handle intervals
 2219:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 2220:         return $self->duedate($part) + 
 2221:             $self->parmval("answerdate", $part);
 2222:     }
 2223:     return $self->parmval("answerdate", $part);
 2224: }
 2225: sub duedate {
 2226:     (my $self, my $part) = @_;
 2227:     return $self->parmval("duedate", $part);
 2228: }
 2229: sub maxtries {
 2230:     (my $self, my $part) = @_;
 2231:     return $self->parmval("maxtries", $part);
 2232: }
 2233: sub opendate {
 2234:     (my $self, my $part) = @_;
 2235:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 2236:         return $self->duedate($part) -
 2237:             $self->parmval("opendate", $part);
 2238:     }
 2239:     return $self->parmval("opendate");
 2240: }
 2241: sub sig {
 2242:     (my $self, my $part) = @_;
 2243:     return $self->parmval("sig", $part);
 2244: }
 2245: sub tol {
 2246:     (my $self, my $part) = @_;
 2247:     return $self->parmval("tol", $part);
 2248: }
 2249: sub type {
 2250:     (my $self, my $part) = @_;
 2251:     return $self->parmval("type", $part);
 2252: }
 2253: sub weight {
 2254:     (my $self, my $part) = @_;
 2255:     return $self->parmval("weight", $part);
 2256: }
 2257: sub tries {
 2258:     my $self = shift;
 2259:     my $part = shift;
 2260:     $part = '0' if (!defined($part));
 2261: 
 2262:     # Make sure return hash is loaded, should error check
 2263:     $self->getReturnHash();
 2264:     
 2265:     my $tries = $self->{RETURN_HASH}->{'resource.'.$part.'.tries'};
 2266:     if (!defined($tries)) {return '0';}
 2267:     return $tries;
 2268: }
 2269: 
 2270: # Multiple things need this
 2271: sub getReturnHash {
 2272:     my $self = shift;
 2273:     
 2274:     if (!defined($self->{RETURN_HASH})) {
 2275:         my %tmpHash = &Apache::lonnet::restore($self->symb());
 2276:         $self->{RETURN_HASH} = \%tmpHash;
 2277:     }
 2278: }       
 2279: 
 2280: ######
 2281: # Status queries
 2282: ######
 2283: 
 2284: # These methods query the status of problems.
 2285: 
 2286: # If we need to count parts, this function determines the number of
 2287: # parts from the metadata. When called, it returns a reference to a list
 2288: # of strings corresponding to the parts. (Thus, using it in a scalar context
 2289: # tells you how many parts you have in the problem:
 2290: # $partcount = scalar($resource->countParts());
 2291: # Don't use $self->{PARTS} directly because you don't know if it's been
 2292: # computed yet.
 2293: 
 2294: =pod
 2295: 
 2296: =head2 Resource misc
 2297: 
 2298: Misc. functions for the resource.
 2299: 
 2300: =over 4
 2301: 
 2302: =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.
 2303: 
 2304: =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:
 2305: 
 2306:  for (split(/\,/, $res->getFeedback())) {
 2307:     my $link = &Apache::lonnet::escape($_);
 2308:     ...
 2309: 
 2310: and use the link as appropriate.
 2311: 
 2312: =cut
 2313: 
 2314: sub hasDiscussion {
 2315:     my $self = shift;
 2316:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 2317: }
 2318: 
 2319: sub getFeedback {
 2320:     my $self = shift;
 2321:     return $self->{NAV_MAP}->getFeedback($self->symb());
 2322: }
 2323: 
 2324: =pod
 2325: 
 2326: =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.)
 2327: 
 2328: =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.
 2329: 
 2330: =back
 2331: 
 2332: =cut
 2333: 
 2334: sub parts {
 2335:     my $self = shift;
 2336: 
 2337:     if ($self->ext) { return ['0']; }
 2338: 
 2339:     $self->extractParts();
 2340:     return $self->{PARTS};
 2341: }
 2342: 
 2343: sub countParts {
 2344:     my $self = shift;
 2345:     
 2346:     my $parts = $self->parts();
 2347: 
 2348:     if ($self->{RESOURCE_ERROR}) {
 2349:         return 0;
 2350:     }
 2351: 
 2352:     if (scalar(@{$parts}) < 2) { return 1;}
 2353: 
 2354:     return scalar(@{$parts}) - 1;
 2355: }
 2356: 
 2357: # Private function: Extracts the parts information and saves it
 2358: sub extractParts { 
 2359:     my $self = shift;
 2360:     
 2361:     return if ($self->{PARTS});
 2362:     return if ($self->ext);
 2363: 
 2364:     $self->{PARTS} = [];
 2365: 
 2366:     # Retrieve part count
 2367:     my $metadata = &Apache::lonnet::metadata($self->src(), 'allpossiblekeys');
 2368:     if (!$metadata) {
 2369:         $self->{RESOURCE_ERROR} = 1;
 2370:         $self->{PARTS} = [];
 2371:         return;
 2372:     }
 2373: 
 2374:     foreach (split(/\,/,$metadata)) {
 2375:         if ($_ =~ /^parameter\_(.*)\_opendate$/) {
 2376:             push @{$self->{PARTS}}, $1;
 2377:         }
 2378:     }
 2379: 
 2380:     
 2381:     # Is this possible to do in one line? - Jeremy
 2382:     my @sortedParts = sort @{$self->{PARTS}};
 2383:     $self->{PARTS} = \@sortedParts;
 2384: 
 2385:     return;
 2386: }
 2387: 
 2388: =pod
 2389: 
 2390: =head2 Resource Status
 2391: 
 2392: 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.
 2393: 
 2394: There are two aspects to the status: the date-related information and the completion information.
 2395: 
 2396: Idiomatic usage of these two methods would probably look something like
 2397: 
 2398:  foreach ($resource->parts()) {
 2399:     my $dateStatus = $resource->getDateStatus($_);
 2400:     my $completionStatus = $resource->getCompletionStatus($_);
 2401: 
 2402:     ... use it here ...
 2403:  }
 2404: 
 2405: =over 4
 2406: 
 2407: =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:
 2408: 
 2409: =back
 2410: 
 2411: B<Date Codes>
 2412: 
 2413: =over 4
 2414: 
 2415: =item * B<OPEN_LATER>: The problem will be opened later.
 2416: 
 2417: =item * B<OPEN>: Open and not yet due.
 2418: 
 2419: 
 2420: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
 2421: 
 2422: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
 2423: 
 2424: =item * B<ANSWER_OPEN>: The answer date is here.
 2425: 
 2426: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
 2427: 
 2428: =back
 2429: 
 2430: =cut
 2431: 
 2432: # Apparently the compiler optimizes these into constants automatically
 2433: sub OPEN_LATER             { return 0; }
 2434: sub OPEN                   { return 1; }
 2435: sub PAST_DUE_NO_ANSWER     { return 2; }
 2436: sub PAST_DUE_ANSWER_LATER  { return 3; }
 2437: sub ANSWER_OPEN            { return 4; }
 2438: sub NOTHING_SET            { return 5; } 
 2439: sub NETWORK_FAILURE        { return 100; }
 2440: 
 2441: # getDateStatus gets the date status for a given problem part. 
 2442: # Because answer date, due date, and open date are fully independent
 2443: # (i.e., it is perfectly possible to *only* have an answer date), 
 2444: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 2445: # (past, future, none given). This function handles this with a decision
 2446: # tree. Read the comments to follow the decision tree.
 2447: 
 2448: sub getDateStatus {
 2449:     my $self = shift;
 2450:     my $part = shift;
 2451:     $part = "0" if (!defined($part));
 2452: 
 2453:     # Always return network failure if there was one.
 2454:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2455: 
 2456:     my $now = time();
 2457: 
 2458:     my $open = $self->opendate($part);
 2459:     my $due = $self->duedate($part);
 2460:     my $answer = $self->answerdate($part);
 2461: 
 2462:     if (!$open && !$due && !$answer) {
 2463:         # no data on the problem at all
 2464:         # should this be the same as "open later"? think multipart.
 2465:         return $self->NOTHING_SET;
 2466:     }
 2467:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 2468:     if (!$due || $now < $due) {return $self->OPEN}
 2469:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 2470:     if ($answer) { return $self->ANSWER_OPEN; }
 2471:     return PAST_DUE_NO_ANSWER;
 2472: }
 2473: 
 2474: =pod
 2475: 
 2476: B<>
 2477: 
 2478: =over 4
 2479: 
 2480: =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:
 2481: 
 2482: =back 
 2483: 
 2484: B<Completion Codes>
 2485: 
 2486: =over 4
 2487: 
 2488: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
 2489: 
 2490: =item * B<INCORRECT>: Attempted, but wrong by student.
 2491: 
 2492: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
 2493: 
 2494: =item * B<CORRECT>: Correct or correct by instructor.
 2495: 
 2496: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
 2497: 
 2498: =item * B<EXCUSED>: Excused. Not yet implemented.
 2499: 
 2500: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
 2501: 
 2502: =item * B<ATTEMPTED>: Attempted, and not yet graded.
 2503: 
 2504: =back
 2505: 
 2506: =cut
 2507: 
 2508: sub NOT_ATTEMPTED         { return 10; }
 2509: sub INCORRECT             { return 11; }
 2510: sub INCORRECT_BY_OVERRIDE { return 12; }
 2511: sub CORRECT               { return 13; }
 2512: sub CORRECT_BY_OVERRIDE   { return 14; }
 2513: sub EXCUSED               { return 15; }
 2514: sub ATTEMPTED             { return 16; }
 2515: 
 2516: sub getCompletionStatus {
 2517:     my $self = shift;
 2518:     my $part = shift;
 2519:     $part = "0" if (!defined($part));
 2520:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2521: 
 2522:     # Make sure return hash exists
 2523:     $self->getReturnHash();
 2524:     
 2525:     my $status = $self->{RETURN_HASH}->{'resource.'.$part.'.solved'};
 2526: 
 2527:     # Left as seperate if statements in case we ever do more with this
 2528:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 2529:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 2530:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 2531:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 2532:     if ($status eq 'excused') {return $self->EXCUSED; }
 2533:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 2534:     return $self->NOT_ATTEMPTED;
 2535: }
 2536: 
 2537: =pod
 2538: 
 2539: B<Composite Status>
 2540: 
 2541: 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()):
 2542: 
 2543: =over 4
 2544: 
 2545: =item * NETWORK_FAILURE: The network has failed and the information is not available.
 2546: 
 2547: =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".)
 2548: 
 2549: =item * CORRECT: For any reason at all, the part is considered correct.
 2550: 
 2551: =item * EXCUSED: For any reason at all, the problem is excused.
 2552: 
 2553: =item * PAST_DUE_NO_ANSWER: The problem is past due, not considered correct, and no answer date is set.
 2554: 
 2555: =item * PAST_DUE_ANSWER_LATER: The problem is past due, not considered correct, and an answer date in the future is set.
 2556: 
 2557: =item * ANSWER_OPEN: The problem is past due, not correct, and the answer is now available.
 2558: 
 2559: =item * OPEN_LATER: The problem is not yet open.
 2560: 
 2561: =item * TRIES_LEFT: The problem is open, has been tried, is not correct, but there are tries left.
 2562: 
 2563: =item * INCORRECT: The problem is open, and all tries have been used without getting the correct answer.
 2564: 
 2565: =item * OPEN: The item is open and not yet tried.
 2566: 
 2567: =item * ATTEMPTED: The problem has been attempted.
 2568: 
 2569: =back
 2570: 
 2571: =cut
 2572: 
 2573: sub TRIES_LEFT { return 10; }
 2574: 
 2575: sub status {
 2576:     my $self = shift;
 2577:     my $part = shift;
 2578:     if (!defined($part)) { $part = "0"; }
 2579:     my $completionStatus = $self->getCompletionStatus($part);
 2580:     my $dateStatus = $self->getDateStatus($part);
 2581: 
 2582:     # What we have is a two-dimensional matrix with 4 entries on one
 2583:     # dimension and 5 entries on the other, which we want to colorize,
 2584:     # plus network failure and "no date data at all".
 2585: 
 2586:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 2587: 
 2588:     # There are a few whole rows we can dispose of:
 2589:     if ($completionStatus == CORRECT ||
 2590:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 2591:         return CORRECT; 
 2592:     }
 2593: 
 2594:     if ($completionStatus == ATTEMPTED) {
 2595:         return ATTEMPTED;
 2596:     }
 2597: 
 2598:     # If it's EXCUSED, then return that no matter what
 2599:     if ($completionStatus == EXCUSED) {
 2600:         return EXCUSED; 
 2601:     }
 2602: 
 2603:     if ($dateStatus == NOTHING_SET) {
 2604:         return NOTHING_SET;
 2605:     }
 2606: 
 2607:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 2608:     # by 4 matrix (date statuses).
 2609: 
 2610:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 2611:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 2612:         return $dateStatus; 
 2613:     }
 2614: 
 2615:     if ($dateStatus == ANSWER_OPEN) {
 2616:         return ANSWER_OPEN;
 2617:     }
 2618: 
 2619:     # Now: (incorrect, incorrect_override, not_attempted) x 
 2620:     # (open_later), (open)
 2621:     
 2622:     if ($dateStatus == OPEN_LATER) {
 2623:         return OPEN_LATER;
 2624:     }
 2625: 
 2626:     # If it's WRONG...
 2627:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 2628:         # and there are TRIES LEFT:
 2629:         if ($self->tries() < $self->maxtries()) {
 2630:             return TRIES_LEFT;
 2631:         }
 2632:         return INCORRECT; # otherwise, return orange; student can't fix this
 2633:     }
 2634: 
 2635:     # Otherwise, it's untried and open
 2636:     return OPEN; 
 2637: }
 2638: 
 2639: =pod
 2640: 
 2641: =head2 Resource/Nav Map Navigation
 2642: 
 2643: =over 4
 2644: 
 2645: =item * B<getNext>(): Gets the next resource in the navmap after this one.
 2646: 
 2647: =cut
 2648: 
 2649: # For the simple single-link case, to get from a resource to the next
 2650: # resource, you need to look up the "to_" link in the nav hash, then
 2651: # follow that with the "goesto_" link.
 2652: 
 2653: sub getNext {
 2654:     my $self = shift;
 2655:     my $alreadySeenHash = shift;
 2656:     my @branches;
 2657:     my $to = $self->to();
 2658:     foreach my $branch ( split(/\,/, $to) ) {
 2659:         my $choice = $self->{NAV_MAP}->getById($branch);
 2660:         my $next = $choice->goesto();
 2661:         $next = $self->{NAV_MAP}->getById($next);
 2662: 
 2663:         # Don't remember it if we've already seen it or if
 2664:         # the student doesn't have browse priviledges
 2665:         my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 2666:         if (!defined($alreadySeenHash) ||
 2667:             !defined($alreadySeenHash->{$next->{ID}}) ||
 2668:             ($browsePriv ne '2' && $browsePriv ne 'F')) {
 2669:                 push @branches, $next;
 2670:             }
 2671:     }
 2672:     return \@branches;
 2673: }
 2674: 
 2675: =pod
 2676: 
 2677: =back
 2678: 
 2679: =cut
 2680: 
 2681: 1;
 2682: 
 2683: __END__
 2684: 
 2685: 

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