File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.95: download - view: text, annotated - select for diffs
Fri Nov 1 18:47:26 2002 UTC (21 years, 7 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Be less inefficient with screen real estate.

Using nav maps with a 1024x768 window showed me that about 3/4 of that
screen is used before the nav maps even appear. That's too much. This
drops that down to about 1/3 of the screen used for head information.

    1: 
    2: # The LearningOnline Network with CAPA
    3: # Navigate Maps Handler
    4: #
    5: # $Id: lonnavmaps.pm,v 1.95 2002/11/01 18:47:26 bowersj2 Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: # (Page Handler
   30: #
   31: # (TeX Content Handler
   32: #
   33: # 05/29/00,05/30 Gerd Kortemeyer)
   34: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
   35: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
   36: #
   37: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
   38: # YEAR=2002
   39: # 1/1 Gerd Kortemeyer
   40: #
   41: 
   42: package Apache::lonnavmaps;
   43: 
   44: use strict;
   45: use Apache::Constants qw(:common :http);
   46: use Apache::lonnet();
   47: use Apache::loncommon();
   48: use GDBM_File;
   49: use POSIX qw (floor strftime);
   50: 
   51: # -------------------------------------------------------------- Module Globals
   52: my %hash;
   53: my @rows;
   54: 
   55: #
   56: # These cache hashes need to be independent of user, resource and course
   57: # (user and course can/should be in the keys)
   58: #
   59: 
   60: my %courserdatas;
   61: my %userrdatas;
   62: 
   63: #
   64: # These global hashes are dependent on user, course and resource, 
   65: # and need to be initialized every time when a sheet is calculated
   66: #
   67: my %courseopt;
   68: my %useropt;
   69: my %parmhash;
   70: 
   71: # This parameter keeps track of whether obtaining the user's information
   72: # failed, which the colorizer in astatus can use
   73: my $networkFailedFlag = 0;
   74: 
   75: # ------------------------------------------------------------------ Euclid gcd
   76: 
   77: sub euclid {
   78:     my ($e,$f)=@_;
   79:     my $a; my $b; my $r;
   80:     if ($e>$f) { $b=$e; $r=$f; } else { $r=$e; $b=$f; }
   81:     while ($r!=0) {
   82:         $a=$b; $b=$r;
   83:         $r=$a%$b;
   84:     }
   85:     return $b;
   86: }
   87: 
   88: # --------------------------------------------------------------------- Parmval
   89: 
   90: # -------------------------------------------- Figure out a cascading parameter
   91: #
   92: # For this function to work
   93: #
   94: # * parmhash needs to be tied
   95: # * courseopt and useropt need to be initialized for this user and course
   96: #
   97: 
   98: sub parmval {
   99:     my ($what,$symb)=@_;
  100:     my $cid=$ENV{'request.course.id'};
  101:     my $csec=$ENV{'request.course.sec'};
  102:     my $uname=$ENV{'user.name'};
  103:     my $udom=$ENV{'user.domain'};
  104: 
  105:     unless ($symb) { return ''; }
  106:     my $result='';
  107: 
  108:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
  109: 
  110: # ----------------------------------------------------- Cascading lookup scheme
  111:     my $rwhat=$what;
  112:     $what=~s/^parameter\_//;
  113:     $what=~s/\_/\./;
  114: 
  115:     my $symbparm=$symb.'.'.$what;
  116:     my $mapparm=$mapname.'___(all).'.$what;
  117:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
  118: 
  119:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
  120:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
  121:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
  122: 
  123:     my $courselevel= $usercourseprefix.'.'.$what;
  124:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
  125:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
  126: 
  127: # ---------------------------------------------------------- first, check user
  128:     if (defined($uname)) {
  129:         if (defined($useropt{$courselevelr})) { return $useropt{$courselevelr}; }
  130:         if (defined($useropt{$courselevelm})) { return $useropt{$courselevelm}; }
  131:         if (defined($useropt{$courselevel})) { return $useropt{$courselevel}; }
  132:     }
  133: 
  134: # ------------------------------------------------------- second, check course
  135:     if (defined($csec)) {
  136:         if (defined($courseopt{$seclevelr})) { return $courseopt{$seclevelr}; }
  137:         if (defined($courseopt{$seclevelm})) { return $courseopt{$seclevelm}; }
  138:         if (defined($courseopt{$seclevel})) { return $courseopt{$seclevel}; }
  139:     }
  140: 
  141:     if (defined($courseopt{$courselevelr})) { return $courseopt{$courselevelr}; }
  142:     if (defined($courseopt{$courselevelm})) { return $courseopt{$courselevelm}; }
  143:     if (defined($courseopt{$courselevel})) { return $courseopt{$courselevel}; }
  144: 
  145: # ----------------------------------------------------- third, check map parms
  146: 
  147:     my $thisparm=$parmhash{$symbparm};
  148:     if (defined($thisparm)) { return $thisparm; }
  149: 
  150: # ----------------------------------------------------- fourth , check default
  151: 
  152:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
  153:     if (defined($default)) { return $default}
  154: 
  155: # --------------------------------------------------- fifth , cascade up parts
  156: 
  157:     my ($space,@qualifier)=split(/\./,$rwhat);
  158:     my $qualifier=join('.',@qualifier);
  159:     unless ($space eq '0') {
  160:         my ($part,$id)=split(/\_/,$space);
  161:         if ($id) {
  162:             my $partgeneral=&parmval($part.".$qualifier",$symb);
  163:             if (defined($partgeneral)) { return $partgeneral; }
  164:         } else {
  165:             my $resourcegeneral=&parmval("0.$qualifier",$symb);
  166:             if (defined($resourcegeneral)) { return $resourcegeneral; }
  167:         }
  168:     }
  169:     return '';
  170: }
  171: 
  172: 
  173: 
  174: # ------------------------------------------------------------- Find out status
  175: # return codes
  176: # tcode (timecode)
  177: # 1: will open later
  178: # 2: is open and not past due yet
  179: # 3: is past due date
  180: # 4: due in the next 24 hours
  181: #
  182: # code (curent solved status)
  183: # 1: not attempted
  184: # 2: attempted but wrong, or incorrect by instructor
  185: # 3: solved or correct by instructor
  186: # 4: partially correct (one or more parts correct)
  187: # "excused" needs to be supported, but is not yet.
  188: sub astatus {
  189:     my $rid=shift;
  190:     my $code=0;
  191:     my $ctext='';
  192:     $rid=~/(\d+)\.(\d+)/;
  193:     my $symb=&Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.
  194:         &Apache::lonnet::declutter($hash{'src_'.$rid});
  195:     my %duedate=();
  196:     my %opendate=();
  197:     my %answerdate=();
  198:     # need to always check part 0's open/due/answer status
  199:     foreach (sort(split(/\,/,&Apache::lonnet::metadata($hash{'src_'.$rid},'allpo\ssiblekeys')))) {
  200:         if ($_=~/^parameter\_(.*)\_opendate$/) {
  201:             my $part=$1;
  202:             $duedate{$part}=&parmval($part.'.duedate',$symb);
  203:             $opendate{$part}=&parmval($part.'.opendate',$symb);
  204:             $answerdate{$part}=&parmval($part.'.answerdate',$symb);
  205:             if (&parmval($part.'.opendate.type',$symb) eq 'date_interval') {
  206:                 $opendate{$part}=$duedate{$part}-$opendate{$part};
  207:             }
  208:             if (&parmval($part.'.answerdate.type',$symb) eq 'date_interval') {
  209:                 $answerdate{$part}=$duedate{$part}+$answerdate{$part};
  210:             }
  211:         }
  212:     }
  213:     my $now=time;
  214:     my $tcode=0;
  215: 
  216:     my %returnhash=&Apache::lonnet::restore($symb);
  217: 
  218:     foreach (sort(keys(%opendate))) {
  219:         my $duedate=$duedate{$_};
  220:         my $opendate=$opendate{$_};
  221:         my $answerdate=$answerdate{$_};
  222:         my $preface='';
  223:         unless ($_ eq '0') { $preface=' Part: '.$_.' '; }
  224:         if ($opendate) {
  225:             if ($now<$duedate || (!$duedate)) {
  226:                 unless ($tcode==4) { $tcode=2; }
  227:                 if ($duedate) {
  228:                     $ctext.=$preface.'Due: '.localtime($duedate);
  229:                 } else {
  230:                     $ctext.=$preface.'No Due Date';
  231:                 }
  232:                 if ($now<$opendate) {
  233:                     unless ($tcode) { $tcode=1; }
  234:                     $ctext.=$preface.'Open: '.localtime($opendate);
  235:                 }
  236:                 if ($duedate && $duedate-$now<86400) {
  237:                     $tcode=4;
  238:                     $ctext.=$preface.'Due: '.localtime($duedate);
  239:                 }
  240:             } else {
  241:                 unless (($tcode==4) || ($tcode eq 2)) { $tcode=3; }
  242:                 if ($now<$answerdate) {
  243:                     $ctext.='Answer: '.localtime($duedate);
  244:                 }
  245:             }
  246:         } else {
  247:             unless (($tcode==2) || ($tcode==4)) { $tcode=1; }
  248:         }
  249:         
  250:         my $status=$returnhash{'resource.'.$_.'.solved'};
  251:         
  252:         if ($status eq 'correct_by_student') {
  253:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  254:             $ctext.=' solved';
  255:         } elsif ($status eq 'correct_by_override') {
  256:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  257:             $ctext.=' override';
  258:         } elsif ($status eq 'incorrect_attempted') {
  259:             if ($code!=4 && $code!=3) { $code=2; }
  260:             if ($code==3) { $code=4; }
  261:             $ctext.=' ('.
  262:                 ($returnhash{'resource.'.$_.'.tries'}?
  263:                  $returnhash{'resource.'.$_.'.tries'}:'0');
  264:             my $numtries = &parmval($_.'.maxtries',$symb);
  265:             if ($numtries) { $ctext.='/'.$numtries.' tries'; }
  266:             $ctext.=')';
  267:         } elsif ($status eq 'incorrect_by_override') {
  268:             if ($code!=4 && $code!=3) { $code=2; }
  269:             if ($code==3) { $code=4; }
  270:             $ctext.=' override';
  271:         } elsif ($status eq 'excused') {
  272:             if ($code==0||$code==3) { $code=3; } else { $code=4; }
  273:             $ctext.=' excused';
  274:         } else {
  275:             if ($code==0) { $code=1; }
  276:         }
  277:     }
  278: 
  279:     return 'p'.$code.$tcode.'"'.$ctext.'"';
  280: }
  281: 
  282: 
  283: sub addresource {
  284:     my ($resource,$sofar,$rid,$showtypes,$indent,$linkid)=@_;
  285:     if ($showtypes eq 'problems') {
  286:         if ($resource!~/\.(problem|exam|quiz|assess|survey|form)$/) {
  287:             return;
  288:         }
  289:     }
  290:     my $brepriv=&Apache::lonnet::allowed('bre',$resource);
  291:     if ($hash{'src_'.$rid}) {
  292:         if (($brepriv eq '2') || ($brepriv eq 'F')) {
  293:             my $pprefix='';
  294:             if ($resource=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  295:                 $pprefix=&astatus($rid);
  296:             }
  297:             $$sofar++;
  298:             if ($indent) { $pprefix='i'.$indent.','.$pprefix; }
  299:             if ($linkid) { $pprefix='l'.$linkid.','.$pprefix; }
  300:             if (defined($rows[$$sofar])) {
  301:                 $rows[$$sofar].='&'.$pprefix.$rid;
  302:             } else {
  303:                 $rows[$$sofar]=$pprefix.$rid;
  304:             }
  305:         }
  306:     }
  307: }
  308: 
  309: sub followlinks () {
  310:     my ($rid,$sofar,$beenhere,$further,$showtypes,$indent,$linkid)=@_;
  311:     my $mincond=1;
  312:     my $next='';
  313:     foreach (split(/\,/,$hash{'to_'.$rid})) {
  314:         my $thiscond=
  315:             &Apache::lonnet::directcondval($hash{'condid_'.$hash{'undercond_'.$_}});
  316:         if ($thiscond>=$mincond) {
  317:             if ($next) {
  318:                 $next.=','.$_.':'.$thiscond;
  319:             } else {
  320:                 $next=$_.':'.$thiscond;
  321:             }
  322:             if ($thiscond>$mincond) { $mincond=$thiscond; }
  323:         }
  324:     }
  325:     my $col=0;
  326:     &Apache::lonxml::debug("following links -$next-");
  327:     foreach (split(/\,/,$next)) {
  328:         my ($nextlinkid,$condval)=split(/\:/,$_);
  329:         if ($condval>=$mincond) {
  330:             my $now=&tracetable($sofar,$hash{'goesto_'.$nextlinkid},
  331:                                 $beenhere,$showtypes,$indent,$linkid);
  332:             if ($now>$further) {                
  333:                 if ($col>0) {
  334:                     my $string;
  335:                     for(my $i=0;$i<$col;$i++) { $string.='&'; }
  336:                     for(my $i=$further+1;$now-1>$i;$i++) {
  337:                         $rows[$i]=$string.$rows[$i];
  338:                     }
  339:                 }
  340:                 $further=$now;
  341:             }
  342:         }
  343:         $col++;
  344:     }
  345:     return $further;
  346: }
  347: # ------------------------------------------------------------ Build page table
  348: 
  349: sub tracetable {
  350:     my ($sofar,$rid,$beenhere,$showtypes,$indent,$linkid)=@_;
  351:     my $newshowtypes=$showtypes;
  352:     my $further=$sofar;
  353: # $Apache::lonxml::debug=1;
  354:     &Apache::lonxml::debug("$rid ; $linkid ; $sofar ; $beenhere ; ".$hash{'src_'.$rid});
  355:     if ($beenhere=~/\&$rid\&/) { return $further; }
  356:     $beenhere.=$rid.'&';
  357: 
  358:     if (defined($hash{'is_map_'.$rid})) {
  359:         $sofar++;
  360:         my $tprefix='';
  361:         if ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
  362:             eq 'sequence') {
  363:             $tprefix='h';
  364:         } elsif ($hash{'map_type_'.$hash{'map_pc_'.$hash{'src_'.$rid}}}
  365:                  eq 'page') {
  366:             $tprefix='j';
  367:             if ($indent) { $tprefix='i'.$indent.','.$tprefix; }
  368:             if ($linkid) { $tprefix='l'.$linkid.','.$tprefix; }
  369:             $newshowtypes='problems';
  370:             $indent++;
  371:             #if in a .page continue to link the encompising .page
  372:             if (!$linkid) { $linkid=$rid; }
  373:         }
  374:         if (defined($rows[$sofar])) {
  375:             $rows[$sofar].='&'.$tprefix.$rid;
  376:         } else {
  377:             $rows[$sofar]=$tprefix.$rid;
  378:         }
  379:         if ((defined($hash{'map_start_'.$hash{'src_'.$rid}})) &&
  380:             (defined($hash{'map_finish_'.$hash{'src_'.$rid}}))) {
  381:             my $frid=$hash{'map_finish_'.$hash{'src_'.$rid}};
  382:             $sofar=&tracetable($sofar,$hash{'map_start_'.$hash{'src_'.$rid}},
  383:                                '&'.$frid.'&',$newshowtypes,$indent,$linkid);
  384:             &addresource($hash{'src_'.$frid},\$sofar,$frid,$newshowtypes,
  385:                          $indent,$linkid);
  386:             if ($tprefix =~ /j$/) { $indent--; $linkid=''; }
  387:         }
  388:     } else {
  389:         &addresource($hash{'src_'.$rid},\$sofar,$rid,$showtypes,
  390:                      $indent,$linkid);
  391:     }
  392: 
  393:     if (defined($hash{'to_'.$rid})) {
  394:         $further=&followlinks($rid,$sofar,$beenhere,$further,$showtypes,
  395:                               $indent,$linkid);
  396:     }
  397: 
  398:     return $further;
  399: }
  400: 
  401: # ================================================================ Main Handler
  402: 
  403: sub handler {
  404:     my $r=shift;
  405: 
  406:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
  407: 
  408:     if ($ENV{'form.jtest'} ne "1")
  409:     {
  410:         return new_handle($r);
  411:     }
  412: 
  413: # ------------------------------------------- Set document type for header only
  414: 
  415:     if ($r->header_only) {
  416:         if ($ENV{'browser.mathml'}) {
  417:             $r->content_type('text/xml');
  418:         } else {
  419:             $r->content_type('text/html');
  420:         }
  421:         $r->send_http_header;
  422:         return OK;
  423:     }
  424:     my $requrl=$r->uri;
  425:     my $hashtied;
  426: # ----------------------------------------------------------------- Tie db file
  427:     my $fn;
  428:     if ($ENV{'request.course.fn'}) {
  429:         $fn=$ENV{'request.course.fn'};
  430:         if (-e "$fn.db") {
  431:             if ((tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) &&
  432:                 (tie(%parmhash,'GDBM_File',
  433:                      $ENV{'request.course.fn'}.'_parms.db',
  434:                      &GDBM_READER(),0640))) {
  435:                 $hashtied=1;
  436:             }
  437:         }
  438:     }
  439:     if (!$hashtied) {
  440:         $ENV{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
  441:         return HTTP_NOT_ACCEPTABLE; 
  442:     }
  443: 
  444: # ------------------------------------------------------------------- Hash tied
  445: 
  446:     if ($ENV{'browser.mathml'}) {
  447:         $r->content_type('text/xml');
  448:     } else {
  449:         $r->content_type('text/html');
  450:     }
  451:     &Apache::loncommon::no_cache($r);
  452:     $r->send_http_header;
  453: 
  454:     my $firstres=$hash{'map_start_'.
  455:            &Apache::lonnet::clutter($ENV{'request.course.uri'})};
  456:     my $lastres=$hash{'map_finish_'.
  457:            &Apache::lonnet::clutter($ENV{'request.course.uri'})};
  458:     if (!(($firstres) && ($lastres))) {
  459:         $r->print('<html><body>Coursemap undefined.</body></html>');
  460:     } else {
  461: 
  462: # ----------------------------------------------------------------- Render page
  463: # -------------------------------------------------------------- Set parameters
  464: 
  465: 
  466: # ---------------------------- initialize coursedata and userdata for this user
  467:         undef %courseopt;
  468:         undef %useropt;
  469: 
  470:         my $uname=$ENV{'user.name'};
  471:         my $udom=$ENV{'user.domain'};
  472:         my $uhome=$ENV{'user.home'};
  473:         my $cid=$ENV{'request.course.id'};
  474:         my $chome=$ENV{'course.'.$cid.'.home'};
  475:         my ($cdom,$cnum)=split(/\_/,$cid);
  476: 
  477:         my $userprefix=$uname.'_'.$udom.'_';
  478:         
  479:         unless ($uhome eq 'no_host') { 
  480: # ------------------------------------------------- Get coursedata (if present)
  481:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
  482:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
  483:                                                  ':resourcedata',$chome);
  484:                 if ($reply!~/^error\:/) {
  485:                     $courserdatas{$cid}=$reply;
  486:                     $courserdatas{$cid.'.last_cache'}=time;
  487:                 }
  488:                 # check to see if network failed
  489:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
  490:                 {
  491:                     $networkFailedFlag = 1;
  492:                 }
  493:             }
  494:             foreach (split(/\&/,$courserdatas{$cid})) {
  495:                 my ($name,$value)=split(/\=/,$_);
  496:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
  497:                     &Apache::lonnet::unescape($value);
  498:             }
  499: # --------------------------------------------------- Get userdata (if present)
  500:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
  501:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
  502:                 if ($reply!~/^error\:/) {
  503:                     $userrdatas{$uname.'___'.$udom}=$reply;
  504:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
  505:                 }
  506:             }
  507:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
  508:                 my ($name,$value)=split(/\=/,$_);
  509:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
  510:                     &Apache::lonnet::unescape($value);
  511:             }
  512:         }
  513: 
  514:         @rows=();
  515: 
  516:         &tracetable(0,$firstres,'&','',0);
  517: 
  518: # ------------------------------------------------------------------ Page parms
  519: 
  520:         my $j;
  521:         my $i;
  522:         my $lcm=1;
  523:         my $contents=0;
  524: 
  525: # ---------------------------------------------- Go through table to get layout
  526: 
  527:         for ($i=0;$i<=$#rows;$i++) {
  528:             if ($rows[$i]) {
  529:                 &Apache::lonxml::debug("Row $i is:".$rows[$i]);
  530:                 $contents++;
  531:                 my @colcont=split(/\&/,$rows[$i]);
  532:                 $lcm*=($#colcont+1)/euclid($lcm,($#colcont+1));
  533:             } 
  534:         }
  535: 
  536: 
  537:         unless ($contents) {
  538:             $r->print('<html><body>Empty Map.</body></html>');
  539:         } else {
  540: 
  541: # ------------------------------------------------------------------ Build page
  542: 
  543:             my $currenturl=$ENV{'form.postdata'};
  544:             $currenturl=~s/^http\:\/\///;
  545:             $currenturl=~s/^[^\/]+//;
  546: 
  547: # ---------------------------------------------------------------- Send headers
  548: 
  549:             my $date=localtime;
  550:             my $now=time;
  551: # ----------------------------------------- Get email status and discussiontime
  552: 
  553:             my %emailstatus=&Apache::lonnet::dump('email_status');
  554:             my $logouttime=$emailstatus{'logout'};
  555:             my $courseleave=$emailstatus{'logout_'.$ENV{'request.course.id'}};
  556:             my $lastcheck=($courseleave>$logouttime?$courseleave:$logouttime);
  557: 
  558:             my %discussiontimes=&Apache::lonnet::dump('discussiontimes',
  559:                                                           $cdom,$cnum);
  560: 
  561:             my %feedback=();
  562:             my %error=();
  563:             foreach my $msgid (split(/\&/,&Apache::lonnet::reply('keys:'.
  564:                                                                  $ENV{'user.domain'}.':'.
  565:                                                                  $ENV{'user.name'}.':nohist_email',
  566:                                                                  $ENV{'user.home'}))) {
  567:                 $msgid=&Apache::lonnet::unescape($msgid);
  568:                 my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
  569:                 if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
  570:                     my ($what,$url)=($1,$2);
  571:                     my %status=
  572:                         &Apache::lonnet::get('email_status',[$msgid]);
  573:                     if ($status{$msgid}=~/^error\:/) { 
  574:                         $status{$msgid}=''; 
  575:                     }
  576:                         
  577:                     if (($status{$msgid} eq 'new') || 
  578:                         (!$status{$msgid})) { 
  579:                         if ($what eq 'Error') {
  580:                             $error{$url}.=','.$msgid; 
  581:                         } else {
  582:                             $feedback{$url}.=','.$msgid;
  583:                         }
  584:                     }
  585:                 }
  586:             }
  587: # ----------------------------------------------------------- Start Page Output
  588:             my $bodytagadd='';
  589:             $r->print(
  590:                    '<html><head><title>Navigate Course Map</title></head>');
  591:             if (($currenturl=~/^\/res/) &&
  592:                 ($currenturl!~/^\/res\/adm/)) {
  593:                 $bodytagadd='onLoad="window.location.hash='."'curloc'".'"';
  594:             }
  595:             $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
  596:                                                   $bodytagadd));
  597:             $r->print('<script>window.focus();</script>');
  598:             my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  599:             if (defined($desc)) { $r->print("<h2>$desc</h2>\n"); }
  600:             $r->print("<h3>$date</h3>\n");
  601:             $r->rflush();
  602:             $r->print('<img src="/adm/lonMisc/chat.gif"> New discussion since '.
  603:                       localtime($lastcheck).
  604:                       '<br><img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'); 
  605:             if (($currenturl=~/^\/res/) &&
  606:                 ($currenturl!~/^\/res\/adm/)) {
  607:                 $r->print('<a href="#curloc">Current Location</a><p>');
  608:             }
  609: 
  610:             # Handle a network error
  611: 
  612:             if ($networkFailedFlag)
  613:             {
  614:                 $r->print('<H2>LON-CAPA network failure.</H2>'."\n");
  615:                 $r->print("<p>LON-CAPA's network is having difficulties, some problem" .
  616:                           " information, such as due dates, will not be available.");
  617:             }
  618: # ----------------------------------------------------- The little content list
  619:             for ($i=0;$i<=$#rows;$i++) {
  620:                 if ($rows[$i]) {
  621:                     my @colcont=split(/\&/,$rows[$i]);
  622:                     my $avespan=$lcm/($#colcont+1);
  623:                     for ($j=0;$j<=$#colcont;$j++) {
  624:                         my $rid=$colcont[$j];
  625:                         if ($rid=~/^h(.+)/) {
  626:                             $rid=$1;
  627:                             $r->print('&nbsp;&nbsp;&nbsp;<a href="#'.
  628:                                       $rid.'">'.$hash{'title_'.$rid}.
  629:                                       '</a><br>');
  630:                         }
  631:                     }
  632:                 }
  633:             }
  634: # ----------------------------------------------------------------- Start table
  635:             $r->print('<hr><table cols="'.$lcm.'" border="0">');
  636:             for ($i=0;$i<=$#rows;$i++) {
  637:                 if ($rows[$i]) {
  638:                     $r->print("\n<tr>");
  639:                     my @colcont=split(/\&/,$rows[$i]);
  640:                     my $avespan=$lcm/($#colcont+1);
  641: 
  642:                     # for each item I wish to print on this row...
  643:                     for ($j=0;$j<=$#colcont;$j++) {
  644:                         my $indent;my $indentstr;
  645:                         my $linkid;
  646:                         my $rid=$colcont[$j];
  647:                         $rid=~/(\d+)\.(\d+)$/;
  648:                         my $src=
  649:                            &Apache::lonnet::declutter($hash{'src_'.$1.'.'.$2});
  650:                         my $symb=
  651:           &Apache::lonnet::declutter($hash{'map_id_'.$1}).'___'.$2.'___'.$src;
  652:                         my $add='<td>';
  653:                         my $adde='</td>';
  654:                         my $hwk='<font color="#223322">';
  655:                         my $hwke='</font>';
  656:                         if ($rid=~/^l(\d+\.\d+),(.+)/) { $linkid=$1; $rid=$2; }
  657:                         if ($rid=~/^i(\d+),(.+)/) { $indent=$1; $rid=$2; }
  658:                         if ($rid=~/^h(.+)/) {
  659:                             $rid=$1;
  660:                             $add='<th bgcolor="#AAFF55"><a name="'.$rid.'">';
  661:                             $adde='</th>';
  662:                             if (($ENV{'user.adv'}) && 
  663:                                 ($parmhash{$symb.'.0.parameter_randompick'})) {
  664:                                $adde=' (randomly select '.
  665:                                    $parmhash{$symb.'.0.parameter_randompick'}.
  666:                                    ')</th>';
  667:                             }
  668:                         }
  669:                         if ($rid=~/^j(.+)/) { $rid=$1; }
  670:                         if ($rid=~/^p(\d)(\d)\"([\w\: \(\)\/\,]*)\"(.+)/) {
  671:                             # sub astatus describes what code/tcode mean
  672:                             my $code=$1;
  673:                             my $tcode=$2;
  674:                             my $ctext=$3;
  675:                             $rid=$4;
  676:                             
  677:                             # will open later
  678:                             if ($tcode eq '1') { 
  679:                                 $add='<td bgcolor="#AAAAAA">';
  680:                             }
  681: 
  682:                             # solved/correct
  683:                             if ($code eq '3') {
  684:                                 $add='<td bgcolor="#AAFFAA">';
  685:                             } elsif ($code eq '4') { # partially correct
  686:                                 $add='<td bgcolor="#E0FFAA">';
  687:                             } else {
  688:                                 # not attempted
  689:                                 
  690:                                 # we end up here on network failure, so pick a neutral
  691:                                 # color if the network failed instead of bright red.
  692:                                 if ( $networkFailedFlag )
  693:                                 {
  694:                                     $add = '<td bgcolor="#AAAAAA">';
  695:                                 }
  696:                                 else
  697:                                 {
  698:                                     $add='<td bgcolor="#FFAAAA">';
  699:                                 }
  700: 
  701:                                 if ($tcode eq '2') { # open, not past due
  702:                                     $add='<td bgcolor="#FFFFAA">';
  703:                                 }
  704: 
  705:                                 if ($tcode eq '4') { # due in next 24 hours
  706:                                     $add='<td bgcolor="#FFFF33">';
  707:                                     $adde='</td>';
  708:                                 }
  709:                             }
  710:                             $hwk='<font color="#888811"><b>';
  711:                             $hwke='</b></font>';
  712:                             if ($code eq '1') {
  713:                                 $hwke='</b> ('.$ctext.')</font>';
  714:                             }
  715:                             if ($code eq '2' || $code eq '4') {
  716:                                 $hwk='<font color="#992222"><b>';
  717:                                 $hwke='</b> ('.$ctext.')</font>';
  718:                             }
  719:                             if ($code eq '3') {
  720:                                 $hwk='<font color="#229922"><b>';
  721:                                 $hwke='</b> ('.$ctext.')</font>';
  722:                             }
  723:                             if ($networkFailedFlag) 
  724:                             {
  725:                                 $hwke='</b> (status unavailable)</font>';
  726:                             }
  727:                         }
  728:                         if ($rid && $hash{'src_'.$rid} eq $currenturl) {
  729:                             $add=$add.'<a name="curloc"></a>'.
  730:                                 '<font color=red size=+2><b>&gt; </b></font>';
  731:                             $adde=
  732:                                 '<font color=red size=+2><b> &lt;</b></font>'.$adde;
  733:                         }
  734:                         if ($discussiontimes{$symb}>$lastcheck) {
  735:                             $adde=
  736:                                 '<img border=0 src="/adm/lonMisc/chat.gif">'.
  737:                                     $adde;
  738:                         }
  739:                         if ($error{$src}) {
  740:                             foreach (split(/\,/,$error{$src})) {
  741:                                 if ($_) {
  742:                                     $adde=
  743:                                         '&nbsp;<a href="/adm/email?display='.
  744:                                             &Apache::lonnet::escape($_).
  745:                                                 '"><img src="/adm/lonMisc/bomb.gif" border=0></a>'
  746:                                                     .$adde;
  747:                                 }
  748:                             }
  749:                         }
  750:                         if ($feedback{$src}) {
  751:                             foreach (split(/\,/,$feedback{$src})) {
  752:                                 if ($_) {
  753:                                     $adde=
  754:                                         '&nbsp;<a href="/adm/email?display='.
  755:                                             &Apache::lonnet::escape($_).
  756:                                                 '"><img src="/adm/lonMisc/feedback.gif" border=0></a>'
  757:                                                     .$adde;
  758:                                 }
  759:                             }
  760:                         }
  761:                         if ($indent) {
  762:                             my $is="&nbsp;&nbsp;";
  763:                             for(my $i=-1;$i<$indent;$i++) { $indentstr.=$is; }
  764:                         }
  765:                         if (!$linkid) { $linkid=$rid; }
  766:                         if ($hash{'randomout_'.$rid}) {
  767:                             $adde=' <i>(hidden)</i>'.$adde;
  768:                         }
  769:                         $r->print($add.$indentstr);
  770:                         if ($rid) {
  771:                             $r->print('<a href="'.$hash{'src_'.$linkid}.
  772:                                       (($hash{'src_'.$linkid}=~/\?/)?'&':'?').
  773:                                       'symb='.&Apache::lonnet::escape($symb)
  774:                                        .'">'.
  775:                                       $hwk.$hash{'title_'.$rid}.$hwke.'</a>');
  776:                         }
  777:                         $r->print($adde);
  778:                     }
  779:                     $r->print('</tr>');
  780:                 }
  781:             }
  782:             $r->print("\n</table>");
  783:             $r->print('</body></html>');
  784: # -------------------------------------------------------------------- End page
  785:         }                  
  786: # ------------------------------------------------------------- End render page
  787:     }
  788: # ------------------------------------------------------------------ Untie hash
  789:     unless (untie(%hash)) {
  790:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  791:                                  "Could not untie coursemap $fn (browse).</font>"); 
  792:     }
  793:     unless (untie(%parmhash)) {
  794:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  795:                                  "Could not untie parmhash (browse).</font>"); 
  796:     }
  797:     return OK;
  798: }
  799: 
  800: sub new_handle {
  801:     my $r = shift;
  802: 
  803:     # Handle header-only request
  804:     if ($r->header_only) {
  805:         if ($ENV{'browser.mathml'}) {
  806:             $r->content_type('text/xml');
  807:         } else {
  808:             $r->content_type('text/html');
  809:         }
  810:         $r->send_http_header;
  811:         return OK;
  812:     }
  813: 
  814:     # Send header, don't cache this page
  815:     if ($ENV{'browser.mathml'}) {
  816:         $r->content_type('text/xml');
  817:     } else {
  818:         $r->content_type('text/html');
  819:     }
  820:     &Apache::loncommon::no_cache($r);
  821:     $r->send_http_header;
  822: 
  823:     # Create the nav map the nav map
  824:     my $navmap = Apache::lonnavmaps::navmap->new(
  825:                         $ENV{"request.course.fn"}.".db",
  826:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
  827: 
  828: 
  829:     if (!defined($navmap)) {
  830:         my $requrl = $r->uri;
  831:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
  832:         return HTTP_NOT_ACCEPTABLE;
  833:     }
  834: 
  835:     # Header
  836:     $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
  837:                                           ''));
  838:     $r->print('<script>window.focus();</script>');
  839:     my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  840:     $r->print('<table border="0" cellpadding="2" cellspacing="0">');
  841:     my $date=localtime;
  842:     $r->print('<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>');
  843:     if ($navmap->{LAST_CHECK}) {
  844:         $r->print('<td align="center" valign="bottom">&nbsp;&nbsp;'.
  845:                   '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
  846:                   strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
  847:                   '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
  848:                   '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
  849:                   '</td>'); 
  850:     } else {
  851:         $r->print('<td align="center" valign="bottom">&nbsp;&nbsp;'.
  852:                   '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
  853:                   '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
  854:                   '</td>'); 
  855:     }
  856:     $r->print('</tr></table>');
  857:     my $condition = 0;
  858:     if ($ENV{'form.condition'}) {
  859:         $condition = 1;
  860:     }
  861: 
  862:     if ($condition) {
  863:         $r->print('<a href="navmaps?condition=0&filter=">Close All Folders</a>');
  864:     } else {
  865:         $r->print('<a href="navmaps?condition=1&filter=">Open All Folders</a>');
  866:     }
  867: 
  868:     $r->print('<br>&nbsp;');
  869:     $r->rflush();
  870: 
  871:     # Now that we've displayed some stuff to the user, init the navmap
  872:     $navmap->init();
  873: 
  874:     # Check that it's defined
  875:     if (!($navmap->courseMapDefined())) {
  876:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  877:                   '</body></html>');
  878:         return OK;
  879:     }
  880: 
  881:     # Grab a resource object so we have access to the constants; this
  882:     # is technically not proper, but should be harmless
  883:     my $res = $navmap->firstResource();
  884: 
  885:     # Defines a status->color mapping, null string means don't color
  886:     my %colormap = 
  887:     ( $res->NETWORK_FAILURE        => '',
  888:       $res->CORRECT                => '',
  889:       $res->EXCUSED                => '#BBBBFF',
  890:       $res->PAST_DUE_ANSWER_LATER  => '',
  891:       $res->PAST_DUE_NO_ANSWER     => '',
  892:       $res->ANSWER_OPEN            => '#CCFFCC',
  893:       $res->OPEN_LATER             => '',
  894:       $res->TRIES_LEFT             => '',
  895:       $res->INCORRECT              => '',
  896:       $res->OPEN                   => '',
  897:       $res->NOTHING_SET            => ''        );
  898:     # And a special case in the nav map; what to do when the assignment
  899:     # is not yet done and due in less then 24 hours
  900:     my $hurryUpColor = "#FF0000";
  901: 
  902:     my %statusIconMap = 
  903:         ( $res->NETWORK_FAILURE    => '',
  904:           $res->NOTHING_SET        => '',
  905:           $res->CORRECT            => 'navmap.correct.gif',
  906:           $res->EXCUSED            => 'navmap.correct.gif',
  907:           $res->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
  908:           $res->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
  909:           $res->ANSWER_OPEN        => 'navmap.wrong.gif',
  910:           $res->OPEN_LATER         => '',
  911:           $res->TRIES_LEFT         => 'navmap.open.gif',
  912:           $res->INCORRECT          => 'navmap.wrong.gif',
  913:           $res->OPEN               => 'navmap.open.gif',
  914:           $res->ATTEMPTED          => 'navmap.open.gif' );
  915: 
  916:     my %iconAltTags = 
  917:         ( 'navmap.correct.gif' => 'Correct',
  918:           'navmap.wrong.gif'   => 'Incorrect',
  919:           'navmap.open.gif'    => 'Open' );
  920: 
  921:     my %condenseStatuses =
  922:         ( $res->NETWORK_FAILURE    => 1,
  923:           $res->NOTHING_SET        => 1,
  924:           $res->CORRECT            => 1 );
  925: 
  926:     my %filterHash;
  927:     # Figure out what we're not displaying
  928:     foreach (split(/\,/, $ENV{"form.filter"})) {
  929:         if ($_) {
  930:             $filterHash{$_} = "1";
  931:         }
  932:     }
  933: 
  934:     # Is this a new-style course? If so, we want to suppress showing the top-level
  935:     # maps in their own folders, in favor of "inlining" them.
  936:     my $topResource = $navmap->getById("0.0");
  937:     my $inlineTopLevelMaps = $topResource->src() =~ m|^/uploaded/.*default\.sequence$|;
  938: 
  939:     my $currenturl = $ENV{'form.postdata'};
  940:     $currenturl=~s/^http\:\/\///;
  941:     $currenturl=~s/^[^\/]+//;
  942:     # alreadyHere allows us to only open the maps necessary to view
  943:     # the current location once, while at the same time remembering
  944:     # the current location. Without that check, the user would never
  945:     # be able to close those maps; the user would close it, and the
  946:     # currenturl scan would re-open it.
  947:     my $queryAdd = "postdata=" . &Apache::lonnet::escape($currenturl) .
  948:         "&alreadyHere=1";
  949: 
  950:     # Begin the HTML table
  951:     # four cols: resource + indent, chat+feedback, icon, text string
  952:     $r->print('<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n");
  953: 
  954:     # This needs to be updated to use symbs from the remote, 
  955:     # instead of uris. The changes to this and the main rendering
  956:     # loop should be obvious.
  957:     # Here's a simple example of the iterator.
  958:     # Preprocess the map: Look for current URL, force inlined maps to display
  959: 
  960:     my $mapIterator = $navmap->getIterator(undef, undef, {}, 1);
  961:     my $found = 0;
  962:     my $depth = 1;
  963:     my $currentUrlIndex = 0; # keeps track of when the current resource is found,
  964:                              # so we can back up a few and put the anchor above the
  965:                              # current resource
  966:     $mapIterator->next(); # discard the first BEGIN_MAP
  967:     my $curRes = $mapIterator->next();
  968:     my $counter = 0;
  969:     
  970:     while ($depth > 0) {
  971:         if ($curRes == $mapIterator->BEGIN_MAP()) {
  972:             $depth++;
  973:         }
  974:         if ($curRes == $mapIterator->END_MAP()) {
  975:             $depth--;
  976:         }
  977: 
  978:         if (ref($curRes)) { $counter++; }
  979: 
  980:         my $mapStack = $mapIterator->getStack();
  981:         if ($currenturl && !$ENV{'form.alreadyHere'} && ref($curRes) && 
  982:             $curRes->src() eq $currenturl) {
  983:             # If this is the correct resource, be sure to 
  984:             # show it by making sure the containing maps
  985:             # are open.
  986: 
  987:             $currentUrlIndex = $counter;
  988:             
  989:             for my $map (@{$mapStack}) {
  990:                 if ($condition) {
  991:                     undef $filterHash{$map->map_pc()};
  992:                 } else {
  993:                     $filterHash{$map->map_pc()} = 1;
  994:                 }
  995:             }
  996:             $ENV{'form.alreadyHere'} = 1;
  997:         }
  998:             
  999:         # Preprocessing: If we're inlining nav maps into the top-level display,
 1000:         # make sure we show this map!
 1001:         if ($inlineTopLevelMaps && ref($curRes) && $curRes->is_map && 
 1002:             scalar(@{$mapStack}) == 1) {
 1003:             if ($condition) {
 1004:                 undef $filterHash{$curRes->map_pc()};
 1005:             } else {
 1006:                 $filterHash{$curRes->map_pc()} = 1;
 1007:             }
 1008:         }
 1009: 
 1010:         $curRes = $mapIterator->next();
 1011:     }
 1012:     
 1013:     undef $res; # so we don't accidentally use it later
 1014:     my $indentLevel = 0;
 1015:     my $indentString = "<img src=\"/adm/lonIcons/whitespace1.gif\" width=\"25\" height=\"1\" alt=\"\" border=\"0\" />";
 1016: 
 1017:     my $isNewBranch = 0;
 1018:     my $now = time();
 1019:     my $in24Hours = $now + 24 * 60 * 60;
 1020:     my $displayedHereMarker = 0;
 1021:     
 1022:     # We know the first thing is a BEGIN_MAP (see "$self->{STARTED}"
 1023:     # code in iterator->next), so ignore the first one
 1024:     $mapIterator = $navmap->getIterator(undef, undef, \%filterHash,
 1025:                                            $condition);
 1026:     $mapIterator->next();
 1027:     $curRes = $mapIterator->next();
 1028:     my $deltadepth = 0;
 1029:     $depth = 1;
 1030: 
 1031:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
 1032:     my $rowNum = 0;
 1033: 
 1034:     $counter = 0;
 1035: 
 1036:     while ($depth > 0) {
 1037:         # If we're in a new style course, and this is a BEGIN_MAP, END_MAP, or
 1038:         # map resource and the stack depth is only one, just plain ignore this resource
 1039:         # entirely. (This has the effect of inlining the resources in that map
 1040:         # in the nav map.)
 1041:         if ($inlineTopLevelMaps && scalar(@{$mapIterator->getStack()}) == 1 &&
 1042:             ref($curRes) && $curRes->is_map()) {
 1043:             # We let the normal depth stuff occur, but we need to shift everything
 1044:             # over by one to the left to make it look right.
 1045:             $deltadepth = -1;
 1046:             $curRes = $mapIterator->next();
 1047:             next;
 1048:         }
 1049: 
 1050:         if ($curRes == $mapIterator->BEGIN_MAP() ||
 1051:             $curRes == $mapIterator->BEGIN_BRANCH()) {
 1052:             $indentLevel++;
 1053:         }
 1054:         if ($curRes == $mapIterator->END_MAP() ||
 1055:             $curRes == $mapIterator->END_BRANCH()) {
 1056:             $indentLevel--;
 1057:         }
 1058:         if ($curRes == $mapIterator->BEGIN_BRANCH()) {
 1059:             $isNewBranch = 1;
 1060:         }
 1061:         if ($curRes == $mapIterator->BEGIN_MAP()) {
 1062:             $depth++;
 1063:         }
 1064:         if ($curRes == $mapIterator->END_MAP()) {
 1065:             $depth--;
 1066:         }
 1067: 
 1068:         if (ref($curRes)) { $counter++; }
 1069: 
 1070:         if ($depth == 1) { $deltadepth = 0; } # we're done shifting, because we're
 1071:                                               # out of the inlined map
 1072: 
 1073:         # Is this resource being blotted out?
 1074:         if (ref($curRes) && !advancedUser() && $curRes->randomout()) {
 1075:             $curRes = $mapIterator->next();
 1076:             next; # and totally ignore this resource
 1077:         }
 1078: 
 1079:         if (ref($curRes) && $curRes->src()) {
 1080: 
 1081:             # Step one: Decide which parts to show
 1082:             my @parts = @{$curRes->parts()};
 1083:             my $multipart = scalar(@parts) > 1;
 1084:             my $condensed = 0;
 1085:                 
 1086:             if ($curRes->is_problem()) {
 1087:                 # Is it multipart?
 1088: 
 1089:                 if ($multipart) {
 1090:                     # If it's multipart, see if part 0 is "open"
 1091:                     # if it is, display all parts, if it isn't,
 1092:                     # just display first
 1093:                     if (!$curRes->opendate("0")) {
 1094:                         @parts = ("0"); # just display the zero-th part
 1095:                         $condensed = 1;
 1096:                     } else {
 1097:                         # Otherwise, only display part 0 if we want to 
 1098:                         # attach feedback or email information to it
 1099:                         if ($curRes->hasDiscussion() || $curRes->getFeedback()) {
 1100:                             shift @parts;
 1101:                         } else {
 1102:                             # If there's discussion or feedback, that counts
 1103:                             # as a difference, so display the parts.
 1104:                             
 1105:                             # Now, we decide whether to condense the
 1106:                             # parts due to similarity
 1107:                             my $status = $curRes->status($parts[1]);
 1108:                             my $due = $curRes->duedate($parts[1]);
 1109:                             my $open = $curRes->opendate($parts[1]);
 1110:                             my $statusAllSame = 1;
 1111:                             my $dueAllSame = 1;
 1112:                             my $openAllSame = 1;
 1113:                             for (my $i = 2; $i < scalar(@parts); $i++) {
 1114:                                 if ($curRes->status($parts[$i]) != $status){
 1115:                                     $statusAllSame = 0;
 1116:                                 }
 1117:                                 if ($curRes->duedate($parts[$i]) != $due ) {
 1118:                                     $dueAllSame = 0;
 1119:                                 }
 1120:                                 if ($curRes->opendate($parts[$i]) != $open) {
 1121:                                     $openAllSame = 0;
 1122:                                 }
 1123:                             }
 1124:                             
 1125:                             # $allSame is true if all the statuses were
 1126:                             # the same. Now, if they are all the same and
 1127:                             # match one of the statuses to condense, or they
 1128:                             # are all open with the same due date, or they are
 1129:                             # all OPEN_LATER with the same open date, display the
 1130:                             # status of the first non-zero part (to get the 'correct'
 1131:                             # status right, since 0 is never 'correct' or 'open').
 1132:                             if (($statusAllSame && defined($condenseStatuses{$status})) ||
 1133:                                 ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
 1134:                                 ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
 1135:                                 @parts = ($parts[1]);
 1136:                                 $condensed = 1;
 1137:                             }
 1138:                         }
 1139:                     }
 1140:                 }
 1141: 
 1142:             } else {
 1143:                 $parts[0] = "0"; # this is to get past foreach loop below
 1144:                  # you can consider a non-problem resource as a resource
 1145:                   # with only one part without loss
 1146:             }
 1147: 
 1148:             # Is it a multipart problem with a single part, now in 
 1149:             # @parts with "0" filtered out? If so, forget it's a multi-part
 1150:             # problem and treat it like a single-part problem.
 1151:             if ( scalar(@parts) == 1 ) {
 1152:                 $multipart = 0;
 1153:             }
 1154: 
 1155:             # Display one part, in event of network error.
 1156:             # If this is a single part, we can at least show the correct
 1157:             # status, but if it's multipart, we're lost.
 1158:             if ($curRes->{RESOURCE_ERROR}) {
 1159:                 @parts = ("0");
 1160:             }
 1161: 
 1162:             # Step two: Show the parts
 1163:             foreach my $part (@parts) {
 1164: 
 1165:                 my $deltalevel = 0; # for inserting the branch icon
 1166:                 my $nonLinkedText = ""; # unlinked stuff after title
 1167:                 
 1168:                 # For each thing we're displaying...
 1169: 
 1170:                 my $stack = $mapIterator->getStack();
 1171:                 my $src = getLinkForResource($stack);
 1172: 
 1173:                 my $srcHasQuestion = $src =~ /\?/;
 1174:                 my $link = $src.
 1175:                     ($srcHasQuestion?'&':'?') .
 1176:                     'symb='.&Apache::lonnet::escape($curRes->symb()).
 1177:                     '"';
 1178:                 my $title = $curRes->title();
 1179:                 if (!$title) {
 1180:                     $title = $curRes->src();
 1181:                     $title = substr ($title, rindex($title, "/") + 1);
 1182:                 }
 1183:                 my $partLabel = "";
 1184:                 my $newBranchText = "";
 1185: 
 1186:                 # If this is a new branch, label it so
 1187:                 # (temporary, this should be an icon w/ alt text)
 1188:                 if ($isNewBranch) {
 1189:                     $newBranchText = "<img src=\"/adm/lonIcons/branch.gif\" border=\"0\">";
 1190:                     $isNewBranch = 0;
 1191:                     $deltalevel = 1;
 1192:                 }
 1193: 
 1194:                 # links to open and close the folders
 1195:                 my $linkopen = "<a href=\"$link\">";
 1196:                 my $linkclose = "</a>";
 1197: 
 1198:                 my $icon = "<img src=\"/adm/lonIcons/html.gif\" alt=\"\" border=\"0\" />";
 1199:                 if ($curRes->is_problem()) { 
 1200:                     if ($part eq "0" || $condensed) {
 1201:                         $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border=\"0\" />'; 
 1202:                     } else {
 1203:                         $icon = $indentString;
 1204:                     }
 1205:                 }
 1206: 
 1207:                 # Display the correct icon, link to open or shut map
 1208:                 if ($curRes->is_map()) { 
 1209:                     my $mapId = $curRes->map_pc();
 1210:                     my $nowOpen = (!defined($filterHash{$mapId}));
 1211:                     if ($condition) {$nowOpen = !$nowOpen;}
 1212:                     $icon = $nowOpen ?
 1213:                         "navmap.folder.closed.gif" : "navmap.folder.open.gif";
 1214:                     $icon = "<img src=\"/adm/lonIcons/$icon\" alt=\"\" border=\"0\" />";
 1215:                     $linkopen = "<a href=\"/adm/navmaps?filter=";
 1216:                     $linkopen .= ($nowOpen xor $condition) ? 
 1217:                         addToFilter(\%filterHash, $mapId) :
 1218:                         removeFromFilter(\%filterHash, $mapId);
 1219:                     $linkopen .= "&condition=$condition&$queryAdd\">";
 1220:                     $linkclose = "</a>";
 1221: 
 1222:                 }
 1223:                 
 1224:                 my $colorizer = "";
 1225:                 my $color;
 1226:                 if ($curRes->is_problem()) {
 1227:                     my $status = $curRes->status($part);
 1228:                     $color = $colormap{$status};
 1229: 
 1230:                     # Special case in the navmaps: If in less then
 1231:                     # 24 hours, give it a bit of urgency
 1232:                     if (($status == $curRes->OPEN() || $status == $curRes->ATTEMPTED() ||
 1233:                          $status == $curRes->TRIES_LEFT())
 1234:                         && $curRes->duedate() &&
 1235:                         $curRes->duedate() < time()+(24*60*60) && 
 1236:                         $curRes->duedate() > time()) {
 1237:                         $color = $hurryUpColor;
 1238:                     }
 1239:                     # Special case: If this is the last try, and there is
 1240:                     # more then one available, and it's not due yet, give a bit of urgency
 1241:                     my $tries = $curRes->tries($part);
 1242:                     my $maxtries = $curRes->maxtries($part);
 1243:                     if ($tries && $maxtries && $maxtries > 1 &&
 1244:                         $maxtries - $tries == 1 && $curRes->duedate() &&
 1245:                         $curRes->duedate() > time()) {
 1246:                         $color = $hurryUpColor;
 1247:                     }
 1248:                     if ($color ne "") {
 1249:                         $colorizer = "bgcolor=\"$color\"";
 1250:                     }
 1251:                 }
 1252: 
 1253:                 if ($curRes->randomout()) {
 1254:                     $nonLinkedText .= ' <i>(hidden)</i> ';
 1255:                 }
 1256: 
 1257:                 $rowNum++;
 1258:                 my $backgroundColor = $backgroundColors[$rowNum % scalar(@backgroundColors)];
 1259: 
 1260:                 # FIRST COL: The resource indentation, branch icon, name, and anchor
 1261:                 $r->print("  <tr bgcolor=\"$backgroundColor\"><td align=\"left\" valign=\"center\" width=\"60%\">\n");
 1262: 
 1263:                 # anchor for current resource... - 5 is deliberate: If it's that
 1264:                 # high on the screen, don't bother focusing on it. Also this will
 1265:                 # print multiple anchors if this is an expanded multi-part problem...
 1266:                 # who cares?
 1267:                 if ($counter == $currentUrlIndex - 5) {
 1268:                     $r->print('<a name="current" />');
 1269:                 }
 1270: 
 1271:                 # print indentation
 1272:                 for (my $i = 0; $i < $indentLevel - $deltalevel + $deltadepth; $i++) {
 1273:                     $r->print($indentString);
 1274:                 }
 1275: 
 1276:                 $r->print("  ${newBranchText}${linkopen}$icon${linkclose}\n");
 1277: 
 1278:                 my $curMarkerBegin = "";
 1279:                 my $curMarkerEnd = "";
 1280: 
 1281:                 # Is this the current resource?
 1282:                 if ($curRes->src() eq $currenturl && !$displayedHereMarker) {
 1283:                     $curMarkerBegin = '<a name="curloc" /><font color="red" size="+2">&gt; </font>';
 1284:                     $curMarkerEnd = '<font color="red" size="+2"> &lt;</font>';
 1285:                     $displayedHereMarker = 1;
 1286:                 }
 1287: 
 1288:                 if ($curRes->is_problem() && $part ne "0" && !$condensed) { 
 1289:                     $partLabel = " (Part $part)"; 
 1290:                     $title = "";
 1291:                 }
 1292:                 if ($multipart && $condensed) {
 1293:                     $nonLinkedText .= ' (' . $curRes->countParts() . ' parts)';
 1294:                 }
 1295: 
 1296:                 $r->print("  $curMarkerBegin<a href=\"$link\">$title$partLabel</a> $curMarkerEnd $nonLinkedText");
 1297: 
 1298:                 if ($curRes->{RESOURCE_ERROR}) {
 1299:                     $r->print(&Apache::loncommon::help_open_topic ("Navmap_Host_Down",
 1300:                                               '<font size="-1">Host down</font>'));
 1301:                     }
 1302: 
 1303:                 my $discussionHTML = ""; my $feedbackHTML = "";
 1304: 
 1305:                 # SECOND COL: Is there text, feedback, errors??
 1306:                 if ($curRes->hasDiscussion()) {
 1307:                     $discussionHTML = $linkopen .
 1308:                         '<img border="0" src="/adm/lonMisc/chat.gif" />' .
 1309:                         $linkclose;
 1310:                 }
 1311: 
 1312:                 if ($curRes->getFeedback()) {
 1313:                     my $feedback = $curRes->getFeedback();
 1314:                     foreach (split(/\,/, $feedback)) {
 1315:                         if ($_) {
 1316:                             $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
 1317:                                 . &Apache::lonnet::escape($_) . '">'
 1318:                                 . '<img src="/adm/lonMisc/feedback.gif" '
 1319:                                 . 'border="0" /></a>';
 1320:                         }
 1321:                     }
 1322:                 }
 1323: 
 1324:                 $r->print("<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML&nbsp;</td>");
 1325: 
 1326:                 # Is this the first displayed part of a multi-part problem
 1327:                 # that has not been condensed, so we should suppress these two
 1328:                 # columns?
 1329:                 my $firstDisplayed = !$condensed && $multipart && $part eq "0";
 1330: 
 1331:                 # THIRD COL: Problem status icon
 1332:                 if ($curRes->is_problem() &&
 1333:                     !$firstDisplayed) {
 1334:                     my $icon = $statusIconMap{$curRes->status($part)};
 1335:                     my $alt = $iconAltTags{$icon};
 1336:                     if ($icon) {
 1337:                         $r->print("<td width=\"30\" valign=\"center\" width=\"50\" align=\"right\">$linkopen<img width=\"25\" height=\"25\" src=\"/adm/lonIcons/$icon\" border=\"0\" alt=\"$alt\" />$linkclose</td>\n");
 1338:                     } else {
 1339:                         $r->print("<td width=\"30\">&nbsp;</td>\n");
 1340:                     }
 1341:                 } else { # not problem, no icon
 1342:                     $r->print("<td width=\"30\">&nbsp;</td>\n");
 1343:                 }
 1344: 
 1345:                 # FOURTH COL: Text description
 1346:                 #$r->print("<td $colorizer align=\"right\" valign=\"center\">\n");
 1347:                 $r->print("<td align=\"right\" valign=\"center\">\n");
 1348:                 
 1349:                 if ($curRes->kind() eq "res" &&
 1350:                     $curRes->is_problem() &&
 1351:                     !$firstDisplayed) {
 1352:                     $r->print ("<font color=\"$color\"><b>") if ($color);
 1353:                     $r->print (getDescription($curRes, $part));
 1354:                     $r->print ("</b></font>") if ($color);
 1355:                 }
 1356:                 if ($curRes->is_map() && advancedUser() && $curRes->randompick()) {
 1357:                     $r->print('(randomly select ' . $curRes->randompick() .')');
 1358:                 }
 1359: 
 1360:                 $r->print("&nbsp;</td></tr>\n");
 1361:             }
 1362:         }
 1363:         $curRes = $mapIterator->next();
 1364:     }
 1365: 
 1366:     $r->print("</table></body></html>");
 1367: 
 1368:     $navmap->untieHashes();
 1369: 
 1370:     return OK;
 1371: }
 1372: 
 1373: # Convenience functions: Returns a string that adds or subtracts
 1374: # the second argument from the first hash, appropriate for the 
 1375: # query string that determines which folders to recurse on
 1376: sub addToFilter {
 1377:     my $hashIn = shift;
 1378:     my $addition = shift;
 1379:     my %hash = %$hashIn;
 1380:     $hash{$addition} = 1;
 1381: 
 1382:     return join (",", keys(%hash));
 1383: }
 1384: 
 1385: sub removeFromFilter {
 1386:     my $hashIn = shift;
 1387:     my $subtraction = shift;
 1388:     my %hash = %$hashIn;
 1389: 
 1390:     delete $hash{$subtraction};
 1391:     return join(",", keys(%hash));
 1392: }
 1393: 
 1394: # Convenience function: Given a stack returned from getStack on the iterator,
 1395: # return the correct src() value.
 1396: # Later, this should add an anchor when we start putting anchors in pages.
 1397: sub getLinkForResource {
 1398:     my $stack = shift;
 1399:     my $res;
 1400: 
 1401:     # Check to see if there are any pages in the stack
 1402:     foreach $res (@$stack) {
 1403:         if (defined($res) && $res->is_page()) {
 1404:             return $res->src();
 1405:         }
 1406:     }
 1407: 
 1408:     # Failing that, return the src of the last resource that is defined
 1409:     # (when we first recurse on a map, it puts an undefined resource
 1410:     # on the bottom because $self->{HERE} isn't defined yet, and we
 1411:     # want the src for the map anyhow)
 1412:     foreach (@$stack) {
 1413:         if (defined($_)) { $res = $_; }
 1414:     }
 1415: 
 1416:     return $res->src();
 1417: }
 1418: 
 1419: # Convenience function: This seperates the logic of how to create
 1420: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
 1421: # etc.) into a seperate function. It takes a resource object as the
 1422: # first parameter, and the part number of the resource as the second.
 1423: # It's basically a big switch statement on the status of the resource.
 1424: 
 1425: sub getDescription {
 1426:     my $res = shift;
 1427:     my $part = shift;
 1428:     my $status = $res->status($part);
 1429: 
 1430:     if ($status == $res->NETWORK_FAILURE) { return ""; }
 1431:     if ($status == $res->NOTHING_SET) {
 1432:         return "Not currently assigned.";
 1433:     }
 1434:     if ($status == $res->OPEN_LATER) {
 1435:         return "Open " . timeToHumanString($res->opendate($part));
 1436:     }
 1437:     if ($status == $res->OPEN) {
 1438:         if ($res->duedate($part)) {
 1439:             return "Due " . timeToHumanString($res->duedate($part));
 1440:         } else {
 1441:             return "Open, no due date";
 1442:         }
 1443:     }
 1444:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
 1445:         return "Answer open " . timeToHumanString($res->answerdate($part));
 1446:     }
 1447:     if ($status == $res->PAST_DUE_NO_ANSWER) {
 1448:         return "Was due " . timeToHumanString($res->duedate($part));
 1449:     }
 1450:     if ($status == $res->ANSWER_OPEN) {
 1451:         return "Answer available";
 1452:     }
 1453:     if ($status == $res->EXCUSED) {
 1454:         return "Excused by instructor";
 1455:     }
 1456:     if ($status == $res->ATTEMPTED) {
 1457:         return "Not yet graded.";
 1458:     }
 1459:     if ($status == $res->TRIES_LEFT) {
 1460:         my $tries = $res->tries($part);
 1461:         my $maxtries = $res->maxtries($part);
 1462:         my $triesString = "";
 1463:         if ($tries && $maxtries) {
 1464:             $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
 1465:             if ($maxtries > 1 && $maxtries - $tries == 1) {
 1466:                 $triesString = "<b>$triesString</b>";
 1467:             }
 1468:         }
 1469:         if ($res->duedate()) {
 1470:             return "Due " . timeToHumanString($res->duedate($part)) .
 1471:                 " $triesString";
 1472:         } else {
 1473:             return "No due date $triesString";
 1474:         }
 1475:     }
 1476: }
 1477: 
 1478: sub advancedUser {
 1479:     return $ENV{'user.adv'};
 1480: }
 1481: 
 1482: 
 1483: # timeToHumanString takes a time number and converts it to a
 1484: # human-readable representation, meant to be used in the following
 1485: # manner:
 1486: # print "Due $timestring"
 1487: # print "Open $timestring"
 1488: # print "Answer available $timestring"
 1489: # Very, very, very, VERY English-only... goodness help a localizer on
 1490: # this func...
 1491: sub timeToHumanString {
 1492:     my ($time) = @_;
 1493:     # zero, '0' and blank are bad times
 1494:     if (!$time) {
 1495:         return 'never';
 1496:     }
 1497: 
 1498:     my $now = time();
 1499: 
 1500:     my @time = localtime($time);
 1501:     my @now = localtime($now);
 1502: 
 1503:     # Positive = future
 1504:     my $delta = $time - $now;
 1505: 
 1506:     my $minute = 60;
 1507:     my $hour = 60 * $minute;
 1508:     my $day = 24 * $hour;
 1509:     my $week = 7 * $day;
 1510:     my $inPast = 0;
 1511: 
 1512:     # Logic in comments:
 1513:     # Is it now? (extremely unlikely)
 1514:     if ( $delta == 0 ) {
 1515:         return "this instant";
 1516:     }
 1517: 
 1518:     if ($delta < 0) {
 1519:         $inPast = 1;
 1520:         $delta = -$delta;
 1521:     }
 1522: 
 1523:     # Is it in the future?
 1524:     if ( $delta > 0 ) {
 1525:         # Is it less then a minute away?
 1526:         my $tense = $inPast ? " ago" : "";
 1527:         my $prefix = $inPast ? "" : "in ";
 1528:         if ( $delta < $minute ) {
 1529:             if ($delta == 1) { return "${prefix}1 second$tense"; }
 1530:             return "$prefix$delta seconds$tense";
 1531:         }
 1532: 
 1533:         # Is it less then an hour away?
 1534:         if ( $delta < $hour ) {
 1535:             # If so, use minutes
 1536:             my $minutes = floor($delta / 60);
 1537:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
 1538:             return "$prefix$minutes minutes$tense";
 1539:         }
 1540:         
 1541:         # Is it less then 24 hours away? If so,
 1542:         # display hours + minutes
 1543:         if ( $delta < $hour * 24) {
 1544:             my $hours = floor($delta / $hour);
 1545:             my $minutes = floor(($delta % $hour) / $minute);
 1546:             my $hourString = "$hours hours";
 1547:             my $minuteString = ", $minutes minutes";
 1548:             if ($hours == 1) {
 1549:                 $hourString = "1 hour";
 1550:             }
 1551:             if ($minutes == 1) {
 1552:                 $minuteString = ", 1 minute";
 1553:             }
 1554:             if ($minutes == 0) {
 1555:                 $minuteString = "";
 1556:             }
 1557:             return "$prefix$hourString$minuteString$tense";
 1558:         }
 1559: 
 1560:         # Less then 5 days away, display day of the week and
 1561:         # HH:MM
 1562:         if ( $delta < $day * 5 ) {
 1563:             my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
 1564:             $timeStr =~ s/12:00 am/midnight/;
 1565:             $timeStr =~ s/12:00 pm/noon/;
 1566:             return ($inPast ? "last " : "next ") .
 1567:                 $timeStr;
 1568:         }
 1569:         
 1570:         # Is it this year?
 1571:         if ( $time[5] == $now[5]) {
 1572:             # Return on Month Day, HH:MM meridian
 1573:             my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
 1574:             $timeStr =~ s/12:00 am/midnight/;
 1575:             $timeStr =~ s/12:00 pm/noon/;
 1576:             return $timeStr;
 1577:         }
 1578: 
 1579:         # Not this year, so show the year
 1580:         my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
 1581:         $timeStr =~ s/12:00 am/midnight/;
 1582:         $timeStr =~ s/12:00 pm/noon/;
 1583:         return $timeStr;
 1584:     }
 1585: }
 1586: 
 1587: 1;
 1588: 
 1589: package Apache::lonnavmaps::navmap;
 1590: 
 1591: =pod
 1592: 
 1593: 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.
 1594: 
 1595: =head1 navmap object: Encapsulating the compiled nav map
 1596: 
 1597: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
 1598: 
 1599: 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.
 1600: 
 1601: You must obtain resource objects through the navmap object.
 1602: 
 1603: =head2 Methods
 1604: 
 1605: =over 4
 1606: 
 1607: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions, genMailDiscussStatus): Binds a new navmap object to the compiled nav map hash and parm hash given as filenames. 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.
 1608: 
 1609: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
 1610: 
 1611: =cut
 1612: 
 1613: use strict;
 1614: use GDBM_File;
 1615: 
 1616: sub new {
 1617:     # magic invocation to create a class instance
 1618:     my $proto = shift;
 1619:     my $class = ref($proto) || $proto;
 1620:     my $self = {};
 1621: 
 1622:     $self->{NAV_HASH_FILE} = shift;
 1623:     $self->{PARM_HASH_FILE} = shift;
 1624:     $self->{GENERATE_COURSE_USER_OPT} = shift;
 1625:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
 1626: 
 1627:     # Resource cache stores navmapresource's as we reference them. We generate
 1628:     # them on-demand so we don't pay for creating resources unless we use them.
 1629:     $self->{RESOURCE_CACHE} = {};
 1630: 
 1631:     # Network failure flag, if we accessed the course or user opt and
 1632:     # failed
 1633:     $self->{NETWORK_FAILURE} = 0;
 1634: 
 1635:     # tie the nav hash
 1636:     my %navmaphash;
 1637:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
 1638:               &GDBM_READER(), 0640))) {
 1639:         return undef;
 1640:     }
 1641:     $self->{NAV_HASH} = \%navmaphash;
 1642:     
 1643:     my %parmhash;
 1644:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
 1645:               &GDBM_READER(), 0640)))
 1646:     {
 1647:         untie $self->{PARM_HASH};
 1648:         return undef;
 1649:     }
 1650:     $self->{PARM_HASH} = \%parmhash;
 1651:     $self->{HASH_TIED} = 1;
 1652: 
 1653:     bless($self);
 1654:         
 1655:     return $self;
 1656: }
 1657: 
 1658: sub init {
 1659:     my $self = shift;
 1660: 
 1661:     # If the course opt hash and the user opt hash should be generated,
 1662:     # generate them
 1663:     if ($self->{GENERATE_COURSE_USER_OPT}) {
 1664:         my $uname=$ENV{'user.name'};
 1665:         my $udom=$ENV{'user.domain'};
 1666:         my $uhome=$ENV{'user.home'};
 1667:         my $cid=$ENV{'request.course.id'};
 1668:         my $chome=$ENV{'course.'.$cid.'.home'};
 1669:         my ($cdom,$cnum)=split(/\_/,$cid);
 1670:         
 1671:         my $userprefix=$uname.'_'.$udom.'_';
 1672:         
 1673:         my %courserdatas; my %useropt; my %courseopt;
 1674:         unless ($uhome eq 'no_host') { 
 1675: # ------------------------------------------------- Get coursedata (if present)
 1676:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1677:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1678:                                                  ':resourcedata',$chome);
 1679:                 if ($reply!~/^error\:/) {
 1680:                     $courserdatas{$cid}=$reply;
 1681:                     $courserdatas{$cid.'.last_cache'}=time;
 1682:                 }
 1683:                 # check to see if network failed
 1684:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1685:                 {
 1686:                     $self->{NETWORK_FAILURE} = 1;
 1687:                 }
 1688:             }
 1689:             foreach (split(/\&/,$courserdatas{$cid})) {
 1690:                 my ($name,$value)=split(/\=/,$_);
 1691:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1692:                     &Apache::lonnet::unescape($value);
 1693:             }
 1694: # --------------------------------------------------- Get userdata (if present)
 1695:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1696:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1697:                 if ($reply!~/^error\:/) {
 1698:                     $userrdatas{$uname.'___'.$udom}=$reply;
 1699:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1700:                 }
 1701:                 # check to see if network failed
 1702:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1703:                 {
 1704:                     $self->{NETWORK_FAILURE} = 1;
 1705:                 }
 1706:             }
 1707:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 1708:                 my ($name,$value)=split(/\=/,$_);
 1709:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1710:                     &Apache::lonnet::unescape($value);
 1711:             }
 1712:             $self->{COURSE_OPT} = \%courseopt;
 1713:             $self->{USER_OPT} = \%useropt;
 1714:         }
 1715:     }   
 1716: 
 1717:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
 1718:         my $cid=$ENV{'request.course.id'};
 1719:         my ($cdom,$cnum)=split(/\_/,$cid);
 1720:         
 1721:         my %emailstatus = &Apache::lonnet::dump('email_status');
 1722:         my $logoutTime = $emailstatus{'logout'};
 1723:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
 1724:         $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
 1725:                                $courseLeaveTime : $logoutTime);
 1726:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 1727:                                                    $cdom, $cnum);
 1728:         my %feedback=();
 1729:         my %error=();
 1730:         my $keys = &Apache::lonnet::reply('keys:'.
 1731:                                           $ENV{'user.domain'}.':'.
 1732:                                           $ENV{'user.name'}.':nohist_email',
 1733:                                           $ENV{'user.home'});
 1734: 
 1735:         foreach my $msgid (split(/\&/, $keys)) {
 1736:             $msgid=&Apache::lonnet::unescape($msgid);
 1737:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
 1738:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
 1739:                 my ($what,$url)=($1,$2);
 1740:                 my %status=
 1741:                     &Apache::lonnet::get('email_status',[$msgid]);
 1742:                 if ($status{$msgid}=~/^error\:/) { 
 1743:                     $status{$msgid}=''; 
 1744:                 }
 1745:                 
 1746:                 if (($status{$msgid} eq 'new') || 
 1747:                     (!$status{$msgid})) { 
 1748:                     if ($what eq 'Error') {
 1749:                         $error{$url}.=','.$msgid; 
 1750:                     } else {
 1751:                         $feedback{$url}.=','.$msgid;
 1752:                     }
 1753:                 }
 1754:             }
 1755:         }
 1756:         
 1757:         $self->{FEEDBACK} = \%feedback;
 1758:         $self->{ERROR_MSG} = \%error; # what is this? JB
 1759:         $self->{DISCUSSION_TIME} = \%discussiontime;
 1760:         $self->{EMAIL_STATUS} = \%emailstatus;
 1761:         
 1762:     }    
 1763: 
 1764:     $self->{PARM_CACHE} = {};
 1765: }
 1766: 
 1767: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1768: sub courseMapDefined {
 1769:     my $self = shift;
 1770:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1771: 
 1772:     my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
 1773:     my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
 1774:     return $firstres && $lastres;
 1775: }
 1776: 
 1777: sub getIterator {
 1778:     my $self = shift;
 1779:     my $iterator = Apache::lonnavmaps::DFSiterator->new($self, shift, shift,
 1780:                                                      shift, undef, shift, 
 1781:                                                      $ENV{'form.direction'});
 1782:     return $iterator;
 1783: }
 1784: 
 1785: # unties the hash when done
 1786: sub untieHashes {
 1787:     my $self = shift;
 1788:     untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
 1789:     untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
 1790:     $self->{HASH_TIED} = 0;
 1791: }
 1792: 
 1793: # when the object is destroyed, be sure to untie all the hashes we tied.
 1794: sub DESTROY {
 1795:     my $self = shift;
 1796:     $self->untieHashes();
 1797: }
 1798: 
 1799: # Private function: Does the given resource (as a symb string) have
 1800: # current discussion? Returns 0 if chat/mail data not extracted.
 1801: sub hasDiscussion {
 1802:     my $self = shift;
 1803:     my $symb = shift;
 1804:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1805: 
 1806:     return $self->{DISCUSSION_TIME}->{$symb} >
 1807:            $self->{LAST_CHECK};
 1808: }
 1809: 
 1810: # Private function: Does the given resource (as a symb string) have
 1811: # current feedback? Returns the string in the feedback hash, which
 1812: # will be false if it does not exist.
 1813: sub getFeedback { 
 1814:     my $self = shift;
 1815:     my $symb = shift;
 1816: 
 1817:     if (!defined($self->{FEEDBACK})) { return ""; }
 1818:     
 1819:     return $self->{FEEDBACK}->{$symb};
 1820: }
 1821: 
 1822: =pod
 1823: 
 1824: =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.
 1825: 
 1826: =cut
 1827: 
 1828: # The strategy here is to cache the resource objects, and only construct them
 1829: # as we use them. The real point is to prevent reading any more from the tied
 1830: # hash then we have to, which should hopefully alleviate speed problems.
 1831: # Caching is just an incidental detail I throw in because it makes sense.
 1832: 
 1833: sub getById {
 1834:     my $self = shift;
 1835:     my $id = shift;
 1836: 
 1837:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1838:     {
 1839:         return $self->{RESOURCE_CACHE}->{$id};
 1840:     }
 1841: 
 1842:     # resource handles inserting itself into cache.
 1843:     return Apache::lonnavmaps::resource->new($self, $id);
 1844: }
 1845: 
 1846: =pod
 1847: 
 1848: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
 1849: 
 1850: =cut
 1851: 
 1852: sub firstResource {
 1853:     my $self = shift;
 1854:     my $firstResource = $self->{NAV_HASH}->{'map_start_' .
 1855:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1856:     return $self->getById($firstResource);
 1857: }
 1858: 
 1859: =pod
 1860: 
 1861: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
 1862: 
 1863: =cut
 1864: 
 1865: sub finishResource {
 1866:     my $self = shift;
 1867:     my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
 1868:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1869:     return $self->getById($firstResource);
 1870: }
 1871: 
 1872: # -------------------------------------------- Figure out a cascading parameter
 1873: #
 1874: # For this function to work
 1875: #
 1876: # * parmhash needs to be tied
 1877: # * courseopt and useropt need to be initialized for this user and course
 1878: #
 1879: 
 1880: sub parmval {
 1881:     my $self = shift;
 1882:     my ($what,$symb)=@_;
 1883:     my $hashkey = $what."|||".$symb;
 1884: 
 1885:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
 1886:         return $self->{PARM_CACHE}->{$hashkey};
 1887:     }
 1888: 
 1889:     my $result = $self->parmval_real($what, $symb);
 1890:     $self->{PARM_CACHE}->{$hashkey} = $result;
 1891:     return $result;
 1892: }
 1893: 
 1894: sub parmval_real {
 1895:     my $self = shift;
 1896:     my ($what,$symb) = @_;
 1897: 
 1898:     my $cid=$ENV{'request.course.id'};
 1899:     my $csec=$ENV{'request.course.sec'};
 1900:     my $uname=$ENV{'user.name'};
 1901:     my $udom=$ENV{'user.domain'};
 1902: 
 1903:     unless ($symb) { return ''; }
 1904:     my $result='';
 1905: 
 1906:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1907: 
 1908: # ----------------------------------------------------- Cascading lookup scheme
 1909:     my $rwhat=$what;
 1910:     $what=~s/^parameter\_//;
 1911:     $what=~s/\_/\./;
 1912: 
 1913:     my $symbparm=$symb.'.'.$what;
 1914:     my $mapparm=$mapname.'___(all).'.$what;
 1915:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1916: 
 1917:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 1918:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 1919:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 1920: 
 1921:     my $courselevel= $usercourseprefix.'.'.$what;
 1922:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 1923:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 1924: 
 1925:     my $useropt = $self->{USER_OPT};
 1926:     my $courseopt = $self->{COURSE_OPT};
 1927:     my $parmhash = $self->{PARM_HASH};
 1928: 
 1929: # ---------------------------------------------------------- first, check user
 1930:     if ($uname and defined($useropt)) {
 1931:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 1932:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 1933:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 1934:     }
 1935: 
 1936: # ------------------------------------------------------- second, check course
 1937:     if ($csec and defined($courseopt)) {
 1938:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 1939:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 1940:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 1941:     }
 1942: 
 1943:     if (defined($courseopt)) {
 1944:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 1945:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 1946:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 1947:     }
 1948: 
 1949: # ----------------------------------------------------- third, check map parms
 1950: 
 1951:     my $thisparm=$$parmhash{$symbparm};
 1952:     if (defined($thisparm)) { return $thisparm; }
 1953: 
 1954: # ----------------------------------------------------- fourth , check default
 1955: 
 1956:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 1957:     if (defined($default)) { return $default}
 1958: 
 1959: # --------------------------------------------------- fifth , cascade up parts
 1960: 
 1961:     my ($space,@qualifier)=split(/\./,$rwhat);
 1962:     my $qualifier=join('.',@qualifier);
 1963:     unless ($space eq '0') {
 1964:         my ($part,$id)=split(/\_/,$space);
 1965:         if ($id) {
 1966:             my $partgeneral=$self->parmval($part.".$qualifier",$symb);
 1967:             if (defined($partgeneral)) { return $partgeneral; }
 1968:         } else {
 1969:             my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
 1970:             if (defined($resourcegeneral)) { return $resourcegeneral; }
 1971:         }
 1972:     }
 1973:     return '';
 1974: }
 1975: 
 1976: 
 1977: 1;
 1978: 
 1979: package Apache::lonnavmaps::iterator;
 1980: 
 1981: # This package must precede "navmap" because "navmap" uses it. In
 1982: # order to keep the documentation order straight, the iterator is documented
 1983: # after the navmap object.
 1984: 
 1985: =pod
 1986: 
 1987: =back
 1988: 
 1989: =head1 navmap Iterator
 1990: 
 1991: 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.
 1992: 
 1993: 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:
 1994: 
 1995: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 1996: 
 1997: To get the next thing from the iterator, call B<next>:
 1998: 
 1999: C<my $nextThing = $resourceIterator-E<gt>next()>
 2000: 
 2001: getIterator behaves as follows:
 2002: 
 2003: =over 4
 2004: 
 2005: =item B<getIterator>(firstResource, finishResource, filterHash, condition, direction): 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(). 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. Direction specifies which direction to recurse, either FORWARD or BACKWARD, with FORWARD being default.
 2006: 
 2007: 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: By default, the condition is 0 and all folders are closed unless explicitly opened. Clicking "Show All Resources" will use a condition of 1 and an empty filterHash, resulting in all resources being shown.
 2008: 
 2009: 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:
 2010: 
 2011: =over 4
 2012: 
 2013: =item * BEGIN_MAP: A new map is being recursed into. This is returned I<after> the map resource itself is returned.
 2014: 
 2015: =item * END_MAP: The map is now done.
 2016: 
 2017: =item * BEGIN_BRANCH: A branch is now starting. The next resource returned will be the first in that branch.
 2018: 
 2019: =item * END_BRANCH: The branch is now done.
 2020: 
 2021: =back
 2022: 
 2023: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_MAP.
 2024: 
 2025: =back
 2026: 
 2027: =cut
 2028: 
 2029: # Here are the tokens for the iterator:
 2030: 
 2031: sub BEGIN_MAP { return 1; }    # begining of a new map
 2032: sub END_MAP { return 2; }      # end of the map
 2033: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 2034: sub END_BRANCH { return 4; }   # end of a branch
 2035: sub FORWARD { return 1; }      # go forward
 2036: sub BACKWARD { return 2; }
 2037: 
 2038: sub new {
 2039:     # magic invocation to create a class instance
 2040:     my $proto = shift;
 2041:     my $class = ref($proto) || $proto;
 2042:     my $self = {};
 2043: 
 2044:     $self->{NAV_MAP} = shift;
 2045:     return undef unless ($self->{NAV_MAP});
 2046: 
 2047:     # Handle the parameters
 2048:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2049:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2050: 
 2051:     # If the given resources are just the ID of the resource, get the
 2052:     # objects
 2053:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2054:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2055:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2056:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2057: 
 2058:     $self->{FILTER} = shift;
 2059: 
 2060:     # A hash, used as a set, of resource already seen
 2061:     $self->{ALREADY_SEEN} = shift;
 2062:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2063:     $self->{CONDITION} = shift;
 2064: 
 2065:     # Now, we need to pre-process the map, by walking forward and backward
 2066:     # over the parts of the map we're going to look at.
 2067: 
 2068:     # Now we're ready to start iterating.
 2069: }
 2070: 
 2071: 1;
 2072: 
 2073: package Apache::lonnavmaps::DFSiterator;
 2074: 
 2075: # UNDOCUMENTED: This is a private library, it should not generally be used
 2076: # by the outside world. What it does is walk through the nav map in a 
 2077: # depth-first fashion. This is not appropriate for most uses, but it is
 2078: # used by the main iterator for pre-processing. It also is able to isolate
 2079: # much of the complexity of the main iterator, so the main iterator is much
 2080: # simpler.
 2081: 
 2082: # Here are the tokens for the iterator, replicated from iterator for convenience:
 2083: 
 2084: sub BEGIN_MAP { return 1; }    # begining of a new map
 2085: sub END_MAP { return 2; }      # end of the map
 2086: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 2087: sub END_BRANCH { return 4; }   # end of a branch
 2088: sub FORWARD { return 1; }      # go forward
 2089: sub BACKWARD { return 2; }
 2090: 
 2091: # Params: nav map, start resource, end resource, filter, condition, 
 2092: # already seen hash ref
 2093: 
 2094: sub new {
 2095:     # magic invocation to create a class instance
 2096:     my $proto = shift;
 2097:     my $class = ref($proto) || $proto;
 2098:     my $self = {};
 2099: 
 2100:     $self->{NAV_MAP} = shift;
 2101:     return undef unless ($self->{NAV_MAP});
 2102: 
 2103:     # Handle the parameters
 2104:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2105:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2106: 
 2107:     # If the given resources are just the ID of the resource, get the
 2108:     # objects
 2109:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2110:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2111:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2112:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2113: 
 2114:     $self->{FILTER} = shift;
 2115: 
 2116:     # A hash, used as a set, of resource already seen
 2117:     $self->{ALREADY_SEEN} = shift;
 2118:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2119:     $self->{CONDITION} = shift;
 2120:     $self->{DIRECTION} = shift || FORWARD();
 2121: 
 2122:     # Flag: Have we started yet? If not, the first action is to return BEGIN_MAP.
 2123:     $self->{STARTED} = 0;
 2124: 
 2125:     # Should we continue calling the recursive iterator, if any?
 2126:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2127:     # The recursive iterator, if any
 2128:     $self->{RECURSIVE_ITERATOR} = undef;
 2129:     # Are we recursing on a map, or a branch?
 2130:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 2131:     # And the count of how deep it is, so that this iterator can keep track of
 2132:     # when to pick back up again.
 2133:     $self->{RECURSIVE_DEPTH} = 0;
 2134: 
 2135:     # For keeping track of our branches, we maintain our own stack
 2136:     $self->{BRANCH_STACK} = [];
 2137:     # If the size shrinks, we exhausted a branch
 2138:     $self->{BRANCH_STACK_SIZE} = 0;
 2139:     $self->{BRANCH_DEPTH} = 0;
 2140: 
 2141:     # For returning two things in a forced sequence
 2142:     $self->{FORCE_NEXT} = undef;
 2143: 
 2144:     # Start with the first resource
 2145:     if ($self->{DIRECTION} == FORWARD) {
 2146:         push @{$self->{BRANCH_STACK}}, $self->{FIRST_RESOURCE};
 2147:     } else {
 2148:         push @{$self->{BRANCH_STACK}}, $self->{FINISH_RESOURCE};
 2149:     }
 2150:     $self->{BRANCH_STACK_SIZE} = 1;
 2151: 
 2152:     bless($self);
 2153:     return $self;
 2154: }
 2155: 
 2156: # Note... this function is *touchy*. I strongly recommend tracing
 2157: # through it with the debugger a few times on a non-trivial map before
 2158: # modifying it. Order is *everything*.
 2159: sub next {
 2160:     my $self = shift;
 2161:     
 2162:     # Iterator logic goes here
 2163: 
 2164:     # Are we using a recursive iterator? If so, pull from that and
 2165:     # watch the depth; we want to resume our level at the correct time.
 2166:     if ($self->{RECURSIVE_ITERATOR_FLAG})
 2167:     {
 2168:         # grab the next from the recursive iterator
 2169:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 2170:         
 2171:         # is it a begin or end map? Update depth if so
 2172:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 2173:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 2174: 
 2175:         # Are we back at depth 0? If so, stop recursing.
 2176:         if ($self->{RECURSIVE_DEPTH} == 0) {
 2177:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2178:         }
 2179:         
 2180:         return $next;
 2181:     }
 2182: 
 2183:     # Is this return value pre-determined?
 2184:     if (defined($self->{FORCE_NEXT})) {
 2185:         my $tmp = $self->{FORCE_NEXT};
 2186:         $self->{FORCE_NEXT} = undef;
 2187:         return $tmp;
 2188:     }
 2189: 
 2190:     # Is there a current resource to grab? If not, then return
 2191:     # END_BRANCH and END_MAP in succession.
 2192:     if (scalar(@{$self->{BRANCH_STACK}}) == 0) {
 2193:         if ($self->{BRANCH_DEPTH} > 0) {
 2194:             $self->{FORCE_NEXT} = $self->END_MAP();
 2195:             $self->{BRANCH_DEPTH}--;
 2196:             return $self->END_BRANCH();
 2197:         } else {
 2198:             return $self->END_MAP();
 2199:         }
 2200:     }
 2201: 
 2202:     # Have we not yet begun? If not, return BEGIN_MAP and 
 2203:     # remember that we've started.
 2204:     if ( !$self->{STARTED} ) {
 2205:         $self->{STARTED} = 1;
 2206:         return $self->BEGIN_MAP;
 2207:     }
 2208: 
 2209:     # Did the branch stack shrink since last run? If so,
 2210:     # we exhausted a branch last time, therefore, we're about
 2211:     # to start a new one. (We know because we already checked to see
 2212:     # if the stack was empty.)
 2213:     if ( scalar (@{$self->{BRANCH_STACK}}) < $self->{BRANCH_STACK_SIZE}) {
 2214:         $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 2215:         $self->{BRANCH_DEPTH}++;
 2216:         return $self->BEGIN_BRANCH();
 2217:     }
 2218: 
 2219:     # Remember the size for comparision next time.
 2220:     $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
 2221: 
 2222:     # If the next resource we mean to return is going to need
 2223:     # a lower branch level, terminate branches until we get 
 2224:     # there.
 2225: 
 2226:     # Get the next resource in the branch
 2227:     $self->{HERE} = pop @{$self->{BRANCH_STACK}};
 2228: 
 2229:     # Are we at the right depth? If not, close a branch and return
 2230:     # the current resource onto the branch stack
 2231:     if (defined($self->{HERE}->{DATA}->{ITERATOR_DEPTH})
 2232:         && $self->{HERE}->{DATA}->{ITERATOR_DEPTH} <
 2233:         $self->{BRANCH_DEPTH} ) {
 2234:         $self->{BRANCH_DEPTH}--;
 2235:         # return it so we can pick it up eventually
 2236:         push @{$self->{BRANCH_STACK}}, $self->{HERE};
 2237:         return $self->END_BRANCH();
 2238:     }
 2239: 
 2240:     # We always return it after this point and never before
 2241:     # (proof: look at just the return statements), so we
 2242:     # remember that we've seen this.
 2243:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 2244:     
 2245:     # Get the next possible resources
 2246:     my $nextUnfiltered;
 2247:     if ($self->{DIRECTION} == FORWARD()) {
 2248:         $nextUnfiltered = $self->{HERE}->getNext();
 2249:     } else {
 2250:         $nextUnfiltered = $self->{HERE}->getPrevious();
 2251:     }
 2252:     my $next = [];
 2253: 
 2254:     # filter the next possibilities to remove things we've 
 2255:     # already seen. Also, remember what branch depth they should
 2256:     # be displayed at, since there's no other reliable way to tell.
 2257:     foreach (@$nextUnfiltered) {
 2258:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 2259:             push @$next, $_;
 2260:             $_->{DATA}->{ITERATOR_DEPTH} = 
 2261:                 $self->{BRANCH_DEPTH} + 1;
 2262:         }
 2263:     }
 2264: 
 2265:     # Handle branch cases:
 2266:     # Nothing is available next: BRANCH_END
 2267:     # 1 thing next: standard non-branch
 2268:     # 2+ things next: have some branches
 2269:     my $nextCount = scalar(@$next);
 2270:     if ($nextCount == 0) {
 2271:         # Return this and on the next run, close the branch up if we're 
 2272:         # in a branch
 2273:         if ($self->{BRANCH_DEPTH} > 0 ) {
 2274:             $self->{FORCE_NEXT} = $self->END_BRANCH();
 2275:             $self->{BRANCH_DEPTH}--;
 2276:         }
 2277:     }
 2278:     
 2279:     while (@$next) {
 2280:         # copy the next possibilities over to the branch stack
 2281:         # in the right order
 2282:         push @{$self->{BRANCH_STACK}}, shift @$next;
 2283:     }
 2284: 
 2285:     if ($nextCount >= 2) {
 2286:         $self->{FORCE_NEXT} = $self->BEGIN_BRANCH();
 2287:         $self->{BRANCH_DEPTH}++;
 2288:         return $self->{HERE}; 
 2289:     }
 2290: 
 2291:     # If this is a map and we want to recurse down it... (not filtered out)
 2292:     if ($self->{HERE}->is_map() && 
 2293:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 2294:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 2295:         my $firstResource = $self->{HERE}->map_start();
 2296:         my $finishResource = $self->{HERE}->map_finish();
 2297: 
 2298:         $self->{RECURSIVE_ITERATOR} =
 2299:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
 2300:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 2301:                                              $self->{CONDITION}, $self->{DIRECTION});
 2302:     }
 2303: 
 2304:     return $self->{HERE};
 2305: }
 2306: 
 2307: =pod
 2308: 
 2309: 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).
 2310: 
 2311: =cut
 2312: 
 2313: sub getStack {
 2314:     my $self=shift;
 2315: 
 2316:     my @stack;
 2317: 
 2318:     $self->populateStack(\@stack);
 2319: 
 2320:     return \@stack;
 2321: }
 2322: 
 2323: # Private method: Calls the iterators recursively to populate the stack.
 2324: sub populateStack {
 2325:     my $self=shift;
 2326:     my $stack = shift;
 2327: 
 2328:     push @$stack, $self->{HERE} if ($self->{HERE});
 2329: 
 2330:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2331:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 2332:     }
 2333: }
 2334: 
 2335: 1;
 2336: 
 2337: package Apache::lonnavmaps::resource;
 2338: 
 2339: use Apache::lonnet;
 2340: 
 2341: =pod
 2342: 
 2343: =head1 Object: resource
 2344: 
 2345: 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.
 2346: 
 2347: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
 2348: 
 2349: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
 2350: 
 2351: =head2 Public Members
 2352: 
 2353: 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.
 2354: 
 2355: =head2 Methods
 2356: 
 2357: =over 4
 2358: 
 2359: =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. Very rarely, if ever, called directly. Use the nav map->getByID() method.
 2360: 
 2361: =back
 2362: 
 2363: =cut
 2364: 
 2365: sub new {
 2366:     # magic invocation to create a class instance
 2367:     my $proto = shift;
 2368:     my $class = ref($proto) || $proto;
 2369:     my $self = {};
 2370: 
 2371:     $self->{NAV_MAP} = shift;
 2372:     $self->{ID} = shift;
 2373: 
 2374:     # Store this new resource in the parent nav map's cache.
 2375:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 2376:     $self->{RESOURCE_ERROR} = 0;
 2377: 
 2378:     # A hash that can be used by two-pass algorithms to store data
 2379:     # about this resource in. Not used by the resource object
 2380:     # directly.
 2381:     $self->{DATA} = {};
 2382:    
 2383:     bless($self);
 2384:     
 2385:     return $self;
 2386: }
 2387: 
 2388: # private function: simplify the NAV_HASH lookups we keep doing
 2389: # pass the name, and to automatically append my ID, pass a true val on the
 2390: # second param
 2391: sub navHash {
 2392:     my $self = shift;
 2393:     my $param = shift;
 2394:     my $id = shift;
 2395:     return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
 2396: }
 2397: 
 2398: =pod
 2399: 
 2400: B<Metadata Retreival>
 2401: 
 2402: These are methods that help you retrieve metadata about the resource:
 2403: 
 2404: =over 4
 2405: 
 2406: =item * B<ext>: Returns true if the resource is external.
 2407: 
 2408: =item * B<goesto>: Returns the "goesto" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
 2409: 
 2410: =item * B<kind>: Returns the kind of the resource from the compiled nav map.
 2411: 
 2412: =item * B<randomout>: Returns true if this resource was chosen to NOT be shown to the user by the random map selection feature.
 2413: 
 2414: =item * B<randompick>: Returns true for a map if the randompick feature is being used on the map. (?)
 2415: 
 2416: =item * B<src>: Returns the source for the resource.
 2417: 
 2418: =item * B<symb>: Returns the symb for the resource.
 2419: 
 2420: =item * B<title>: Returns the title of the resource.
 2421: 
 2422: =item * B<to>: Returns the "to" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
 2423: 
 2424: =back
 2425: 
 2426: =cut
 2427: 
 2428: # These info functions can be used directly, as they don't return
 2429: # resource information.
 2430: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
 2431: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 2432: sub from { my $self=shift; return $self->navHash("from_", 1); }
 2433: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 2434: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 2435: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 2436: sub randompick { 
 2437:     my $self = shift;
 2438:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
 2439:                                                '.0.parameter_randompick'};
 2440: }
 2441: sub src { 
 2442:     my $self=shift;
 2443:     return $self->navHash("src_", 1);
 2444: }
 2445: sub symb {
 2446:     my $self=shift;
 2447:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 2448:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 2449:     return &Apache::lonnet::declutter(
 2450:          $self->navHash('map_id_'.$first)) 
 2451:         . '___' . $second . '___' . $symbSrc;
 2452: }
 2453: sub title { my $self=shift; return $self->navHash("title_", 1); }
 2454: sub to { my $self=shift; return $self->navHash("to_", 1); }
 2455: 
 2456: =pod
 2457: 
 2458: B<Predicate Testing the Resource>
 2459: 
 2460: These methods are shortcuts to deciding if a given resource has a given property.
 2461: 
 2462: =over 4
 2463: 
 2464: =item * B<is_map>: Returns true if the resource is a map type.
 2465: 
 2466: =item * B<is_problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field; might need more to work correctly.)
 2467: 
 2468: =item * B<is_page>: Returns true if the resource is a page.
 2469: 
 2470: =item * B<is_problem>: Returns true if the resource is a problem.
 2471: 
 2472: =item * B<is_sequence>: Returns true if the resource sequence.
 2473: 
 2474: =back
 2475: 
 2476: =cut
 2477: 
 2478: 
 2479: sub is_html {
 2480:     my $self=shift;
 2481:     my $src = $self->src();
 2482:     return ($src =~ /html$/);
 2483: }
 2484: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 2485: sub is_page {
 2486:     my $self=shift;
 2487:     my $src = $self->src();
 2488:     return ($src =~ /page$/);
 2489: }
 2490: sub is_problem {
 2491:     my $self=shift;
 2492:     my $src = $self->src();
 2493:     return ($src =~ /problem$/);
 2494: }
 2495: sub is_sequence {
 2496:     my $self=shift;
 2497:     my $src = $self->src();
 2498:     return ($src =~ /sequence$/);
 2499: }
 2500: 
 2501: 
 2502: 
 2503: 
 2504: 
 2505: # Move this into POD: In order to use these correctly, courseopt
 2506: # and useropt need to be generated
 2507: sub parmval {
 2508:     my $self = shift;
 2509:     my $what = shift;
 2510:     my $part = shift || "0";
 2511:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 2512: }
 2513: 
 2514: =pod
 2515: 
 2516: B<Map Methods>
 2517: 
 2518: These methods are useful for getting information about the map properties of the resource, if the resource is a map (B<is_map>).
 2519: 
 2520: =over 4
 2521: 
 2522: =item * B<map_finish>: Returns a reference to a resource object corresponding to the finish resource of the map.
 2523: 
 2524: =item * B<map_pc>: Returns the pc value of the map, which is the first number that appears in the resource ID of the resources in the map, and is the number that appears around the middle of the symbs of the resources in that map.
 2525: 
 2526: =item * B<map_start>: Returns a reference to a resource object corresponding to the start resource of the map.
 2527: 
 2528: =item * B<map_type>: Returns a string with the type of the map in it.
 2529: 
 2530: =back
 2531: 
 2532: =cut
 2533: 
 2534: sub map_finish {
 2535:     my $self = shift;
 2536:     my $src = $self->src();
 2537:     my $res = $self->navHash("map_finish_$src", 0);
 2538:     $res = $self->{NAV_MAP}->getById($res);
 2539:     return $res;
 2540: }
 2541: sub map_pc {
 2542:     my $self = shift;
 2543:     my $src = $self->src();
 2544:     return $self->navHash("map_pc_$src", 0);
 2545: }
 2546: sub map_start {
 2547:     my $self = shift;
 2548:     my $src = $self->src();
 2549:     my $res = $self->navHash("map_start_$src", 0);
 2550:     $res = $self->{NAV_MAP}->getById($res);
 2551:     return $res;
 2552: }
 2553: sub map_type {
 2554:     my $self = shift;
 2555:     my $pc = $self->map_pc();
 2556:     return $self->navHash("map_type_$pc", 0);
 2557: }
 2558: 
 2559: 
 2560: 
 2561: #####
 2562: # Property queries
 2563: #####
 2564: 
 2565: # These functions will be responsible for returning the CORRECT
 2566: # VALUE for the parameter, no matter what. So while they may look
 2567: # like direct calls to parmval, they can be more then that.
 2568: # So, for instance, the duedate function should use the "duedatetype"
 2569: # information, rather then the resource object user.
 2570: 
 2571: =pod
 2572: 
 2573: =head2 Resource Parameters
 2574: 
 2575: 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 parameter.
 2576: 
 2577: 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.)
 2578: 
 2579: =over 4
 2580: 
 2581: =item * B<acc>: Get the Client IP/Name Access Control information.
 2582: 
 2583: =item * B<answerdate>: Get the answer-reveal date for the problem.
 2584: 
 2585: =item * B<duedate>: Get the due date for the problem.
 2586: 
 2587: =item * B<tries>: Get the number of tries the student has used on the problem.
 2588: 
 2589: =item * B<maxtries>: Get the number of max tries allowed.
 2590: 
 2591: =item * B<opendate>: Get the open date for the problem.
 2592: 
 2593: =item * B<sig>: Get the significant figures setting.
 2594: 
 2595: =item * B<tol>: Get the tolerance for the problem.
 2596: 
 2597: =item * B<tries>: Get the number of tries the user has already used on the problem.
 2598: 
 2599: =item * B<type>: Get the question type for the problem.
 2600: 
 2601: =item * B<weight>: Get the weight for the problem.
 2602: 
 2603: =back
 2604: 
 2605: =cut
 2606: 
 2607: sub acc {
 2608:     (my $self, my $part) = @_;
 2609:     return $self->parmval("acc", $part);
 2610: }
 2611: sub answerdate {
 2612:     (my $self, my $part) = @_;
 2613:     # Handle intervals
 2614:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 2615:         return $self->duedate($part) + 
 2616:             $self->parmval("answerdate", $part);
 2617:     }
 2618:     return $self->parmval("answerdate", $part);
 2619: }
 2620: sub duedate {
 2621:     (my $self, my $part) = @_;
 2622:     return $self->parmval("duedate", $part);
 2623: }
 2624: sub maxtries {
 2625:     (my $self, my $part) = @_;
 2626:     return $self->parmval("maxtries", $part);
 2627: }
 2628: sub opendate {
 2629:     (my $self, my $part) = @_;
 2630:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 2631:         return $self->duedate($part) -
 2632:             $self->parmval("opendate", $part);
 2633:     }
 2634:     return $self->parmval("opendate");
 2635: }
 2636: sub sig {
 2637:     (my $self, my $part) = @_;
 2638:     return $self->parmval("sig", $part);
 2639: }
 2640: sub tol {
 2641:     (my $self, my $part) = @_;
 2642:     return $self->parmval("tol", $part);
 2643: }
 2644: sub tries {
 2645:     my $self = shift;
 2646:     my $part = shift;
 2647:     $part = '0' if (!defined($part));
 2648: 
 2649:     # Make sure return hash is loaded, should error check
 2650:     $self->getReturnHash();
 2651:     
 2652:     my $tries = $self->{RETURN_HASH}->{'resource.'.$part.'.tries'};
 2653:     if (!defined($tries)) {return '0';}
 2654:     return $tries;
 2655: }
 2656: sub type {
 2657:     (my $self, my $part) = @_;
 2658:     return $self->parmval("type", $part);
 2659: }
 2660: sub weight {
 2661:     (my $self, my $part) = @_;
 2662:     return $self->parmval("weight", $part);
 2663: }
 2664: 
 2665: # Multiple things need this
 2666: sub getReturnHash {
 2667:     my $self = shift;
 2668:     
 2669:     if (!defined($self->{RETURN_HASH})) {
 2670:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
 2671:         $self->{RETURN_HASH} = \%tmpHash;
 2672:     }
 2673: }       
 2674: 
 2675: ######
 2676: # Status queries
 2677: ######
 2678: 
 2679: # These methods query the status of problems.
 2680: 
 2681: # If we need to count parts, this function determines the number of
 2682: # parts from the metadata. When called, it returns a reference to a list
 2683: # of strings corresponding to the parts. (Thus, using it in a scalar context
 2684: # tells you how many parts you have in the problem:
 2685: # $partcount = scalar($resource->countParts());
 2686: # Don't use $self->{PARTS} directly because you don't know if it's been
 2687: # computed yet.
 2688: 
 2689: =pod
 2690: 
 2691: =head2 Resource misc
 2692: 
 2693: Misc. functions for the resource.
 2694: 
 2695: =over 4
 2696: 
 2697: =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.
 2698: 
 2699: =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:
 2700: 
 2701:  for (split(/\,/, $res->getFeedback())) {
 2702:     my $link = &Apache::lonnet::escape($_);
 2703:     ...
 2704: 
 2705: and use the link as appropriate.
 2706: 
 2707: =cut
 2708: 
 2709: sub hasDiscussion {
 2710:     my $self = shift;
 2711:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 2712: }
 2713: 
 2714: sub getFeedback {
 2715:     my $self = shift;
 2716:     return $self->{NAV_MAP}->getFeedback($self->src());
 2717: }
 2718: 
 2719: =pod
 2720: 
 2721: =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. Filtering part 0 if you want it is up to you.)
 2722: 
 2723: =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. Thus, B<parts> may return an array with fewer parts in it then countParts might lead you to believe.
 2724: 
 2725: =back
 2726: 
 2727: =cut
 2728: 
 2729: sub parts {
 2730:     my $self = shift;
 2731: 
 2732:     if ($self->ext) { return ['0']; }
 2733: 
 2734:     $self->extractParts();
 2735:     return $self->{PARTS};
 2736: }
 2737: 
 2738: sub countParts {
 2739:     my $self = shift;
 2740:     
 2741:     my $parts = $self->parts();
 2742: 
 2743:     if ($self->{RESOURCE_ERROR}) {
 2744:         return 0;
 2745:     }
 2746: 
 2747:     if (scalar(@{$parts}) < 2) { return 1;}
 2748: 
 2749:     return scalar(@{$parts}) - 1;
 2750: }
 2751: 
 2752: # Private function: Extracts the parts information and saves it
 2753: sub extractParts { 
 2754:     my $self = shift;
 2755:     
 2756:     return if ($self->{PARTS});
 2757:     return if ($self->ext);
 2758: 
 2759:     $self->{PARTS} = [];
 2760: 
 2761:     # Retrieve part count, if this is a problem
 2762:     if ($self->is_problem()) {
 2763:         my $metadata = &Apache::lonnet::metadata($self->src(), 'allpossiblekeys');
 2764:         if (!$metadata) {
 2765:             $self->{RESOURCE_ERROR} = 1;
 2766:             $self->{PARTS} = [];
 2767:             return;
 2768:         }
 2769:         
 2770:         foreach (split(/\,/,$metadata)) {
 2771:             if ($_ =~ /^parameter\_(.*)\_opendate$/) {
 2772:                 push @{$self->{PARTS}}, $1;
 2773:             }
 2774:         }
 2775:         
 2776:         
 2777:         # Is this possible to do in one line? - Jeremy
 2778:         my @sortedParts = sort @{$self->{PARTS}};
 2779:         $self->{PARTS} = \@sortedParts;
 2780:     }
 2781: 
 2782:     return;
 2783: }
 2784: 
 2785: =pod
 2786: 
 2787: =head2 Resource Status
 2788: 
 2789: 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.
 2790: 
 2791: There are two aspects to the status: the date-related information and the completion information.
 2792: 
 2793: Idiomatic usage of these two methods would probably look something like
 2794: 
 2795:  foreach ($resource->parts()) {
 2796:     my $dateStatus = $resource->getDateStatus($_);
 2797:     my $completionStatus = $resource->getCompletionStatus($_);
 2798: 
 2799:     or
 2800: 
 2801:     my $status = $resource->status($_);
 2802: 
 2803:     ... use it here ...
 2804:  }
 2805: 
 2806: =over 4
 2807: 
 2808: =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. The possible return values are:
 2809: 
 2810: =back
 2811: 
 2812: B<Date Codes>
 2813: 
 2814: =over 4
 2815: 
 2816: =item * B<OPEN_LATER>: The problem will be opened later.
 2817: 
 2818: =item * B<OPEN>: Open and not yet due.
 2819: 
 2820: 
 2821: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
 2822: 
 2823: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
 2824: 
 2825: =item * B<ANSWER_OPEN>: The answer date is here.
 2826: 
 2827: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
 2828: 
 2829: =back
 2830: 
 2831: =cut
 2832: 
 2833: # Apparently the compiler optimizes these into constants automatically
 2834: sub OPEN_LATER             { return 0; }
 2835: sub OPEN                   { return 1; }
 2836: sub PAST_DUE_NO_ANSWER     { return 2; }
 2837: sub PAST_DUE_ANSWER_LATER  { return 3; }
 2838: sub ANSWER_OPEN            { return 4; }
 2839: sub NOTHING_SET            { return 5; } 
 2840: sub NETWORK_FAILURE        { return 100; }
 2841: 
 2842: # getDateStatus gets the date status for a given problem part. 
 2843: # Because answer date, due date, and open date are fully independent
 2844: # (i.e., it is perfectly possible to *only* have an answer date), 
 2845: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 2846: # (past, future, none given). This function handles this with a decision
 2847: # tree. Read the comments to follow the decision tree.
 2848: 
 2849: sub getDateStatus {
 2850:     my $self = shift;
 2851:     my $part = shift;
 2852:     $part = "0" if (!defined($part));
 2853: 
 2854:     # Always return network failure if there was one.
 2855:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2856: 
 2857:     my $now = time();
 2858: 
 2859:     my $open = $self->opendate($part);
 2860:     my $due = $self->duedate($part);
 2861:     my $answer = $self->answerdate($part);
 2862: 
 2863:     if (!$open && !$due && !$answer) {
 2864:         # no data on the problem at all
 2865:         # should this be the same as "open later"? think multipart.
 2866:         return $self->NOTHING_SET;
 2867:     }
 2868:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 2869:     if (!$due || $now < $due) {return $self->OPEN}
 2870:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 2871:     if ($answer) { return $self->ANSWER_OPEN; }
 2872:     return PAST_DUE_NO_ANSWER;
 2873: }
 2874: 
 2875: =pod
 2876: 
 2877: B<>
 2878: 
 2879: =over 4
 2880: 
 2881: =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:
 2882: 
 2883: =back 
 2884: 
 2885: B<Completion Codes>
 2886: 
 2887: =over 4
 2888: 
 2889: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
 2890: 
 2891: =item * B<INCORRECT>: Attempted, but wrong by student.
 2892: 
 2893: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
 2894: 
 2895: =item * B<CORRECT>: Correct or correct by instructor.
 2896: 
 2897: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
 2898: 
 2899: =item * B<EXCUSED>: Excused. Not yet implemented.
 2900: 
 2901: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
 2902: 
 2903: =item * B<ATTEMPTED>: Attempted, and not yet graded.
 2904: 
 2905: =back
 2906: 
 2907: =cut
 2908: 
 2909: sub NOT_ATTEMPTED         { return 10; }
 2910: sub INCORRECT             { return 11; }
 2911: sub INCORRECT_BY_OVERRIDE { return 12; }
 2912: sub CORRECT               { return 13; }
 2913: sub CORRECT_BY_OVERRIDE   { return 14; }
 2914: sub EXCUSED               { return 15; }
 2915: sub ATTEMPTED             { return 16; }
 2916: 
 2917: sub getCompletionStatus {
 2918:     my $self = shift;
 2919:     my $part = shift;
 2920:     $part = "0" if (!defined($part));
 2921:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2922: 
 2923:     # Make sure return hash exists
 2924:     $self->getReturnHash();
 2925:     
 2926:     my $status = $self->{RETURN_HASH}->{'resource.'.$part.'.solved'};
 2927: 
 2928:     # Left as seperate if statements in case we ever do more with this
 2929:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 2930:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 2931:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 2932:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 2933:     if ($status eq 'excused') {return $self->EXCUSED; }
 2934:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 2935:     return $self->NOT_ATTEMPTED;
 2936: }
 2937: 
 2938: =pod
 2939: 
 2940: B<Composite Status>
 2941: 
 2942: 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()):
 2943: 
 2944: =over 4
 2945: 
 2946: =item * B<NETWORK_FAILURE>: The network has failed and the information is not available.
 2947: 
 2948: =item * B<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".)
 2949: 
 2950: =item * B<CORRECT>: For any reason at all, the part is considered correct.
 2951: 
 2952: =item * B<EXCUSED>: For any reason at all, the problem is excused.
 2953: 
 2954: =item * B<PAST_DUE_NO_ANSWER>: The problem is past due, not considered correct, and no answer date is set.
 2955: 
 2956: =item * B<PAST_DUE_ANSWER_LATER>: The problem is past due, not considered correct, and an answer date in the future is set.
 2957: 
 2958: =item * B<ANSWER_OPEN>: The problem is past due, not correct, and the answer is now available.
 2959: 
 2960: =item * B<OPEN_LATER>: The problem is not yet open.
 2961: 
 2962: =item * B<TRIES_LEFT>: The problem is open, has been tried, is not correct, but there are tries left.
 2963: 
 2964: =item * B<INCORRECT>: The problem is open, and all tries have been used without getting the correct answer.
 2965: 
 2966: =item * B<OPEN>: The item is open and not yet tried.
 2967: 
 2968: =item * B<ATTEMPTED>: The problem has been attempted.
 2969: 
 2970: =back
 2971: 
 2972: =cut
 2973: 
 2974: sub TRIES_LEFT { return 10; }
 2975: 
 2976: sub status {
 2977:     my $self = shift;
 2978:     my $part = shift;
 2979:     if (!defined($part)) { $part = "0"; }
 2980:     my $completionStatus = $self->getCompletionStatus($part);
 2981:     my $dateStatus = $self->getDateStatus($part);
 2982: 
 2983:     # What we have is a two-dimensional matrix with 4 entries on one
 2984:     # dimension and 5 entries on the other, which we want to colorize,
 2985:     # plus network failure and "no date data at all".
 2986: 
 2987:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 2988: 
 2989:     # There are a few whole rows we can dispose of:
 2990:     if ($completionStatus == CORRECT ||
 2991:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 2992:         return CORRECT; 
 2993:     }
 2994: 
 2995:     if ($completionStatus == ATTEMPTED) {
 2996:         return ATTEMPTED;
 2997:     }
 2998: 
 2999:     # If it's EXCUSED, then return that no matter what
 3000:     if ($completionStatus == EXCUSED) {
 3001:         return EXCUSED; 
 3002:     }
 3003: 
 3004:     if ($dateStatus == NOTHING_SET) {
 3005:         return NOTHING_SET;
 3006:     }
 3007: 
 3008:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 3009:     # by 4 matrix (date statuses).
 3010: 
 3011:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 3012:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 3013:         return $dateStatus; 
 3014:     }
 3015: 
 3016:     if ($dateStatus == ANSWER_OPEN) {
 3017:         return ANSWER_OPEN;
 3018:     }
 3019: 
 3020:     # Now: (incorrect, incorrect_override, not_attempted) x 
 3021:     # (open_later), (open)
 3022:     
 3023:     if ($dateStatus == OPEN_LATER) {
 3024:         return OPEN_LATER;
 3025:     }
 3026: 
 3027:     # If it's WRONG...
 3028:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 3029:         # and there are TRIES LEFT:
 3030:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 3031:             return TRIES_LEFT;
 3032:         }
 3033:         return INCORRECT; # otherwise, return orange; student can't fix this
 3034:     }
 3035: 
 3036:     # Otherwise, it's untried and open
 3037:     return OPEN; 
 3038: }
 3039: 
 3040: =pod
 3041: 
 3042: =head2 Resource/Nav Map Navigation
 3043: 
 3044: =over 4
 3045: 
 3046: =item * B<getNext>($alreadySeenHashRef): Retreive an array of the possible next resources after this one. Always returns an array, even in the one- or zero-element case. The "alreadySeenHashRef" is an optional parameter that can be passed in to the method. If $$alreadySeenHashRef{$res->id()} is true in that hash, getNext will not return it in the list. In other words, you can use it to suppress resources you've already seen in the getNext method directly.
 3047: 
 3048: =item * B<getPrevious>($alreadySeenHashRef): Retreive an array of the possible previous resources from this one. Always returns an array, even in the one- or zero-element case. $alreadySeenHashRef is the same as in getNext.
 3049: 
 3050: =cut
 3051: 
 3052: sub getNext {
 3053:     my $self = shift;
 3054:     my $alreadySeenHash = shift;
 3055:     my @branches;
 3056:     my $to = $self->to();
 3057:     foreach my $branch ( split(/,/, $to) ) {
 3058:         my $choice = $self->{NAV_MAP}->getById($branch);
 3059:         my $next = $choice->goesto();
 3060:         $next = $self->{NAV_MAP}->getById($next);
 3061: 
 3062:         # Don't remember it if we've already seen it or if
 3063:         # the student doesn't have browse priviledges
 3064:         my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 3065:         if (!defined($alreadySeenHash) ||
 3066:             !defined($alreadySeenHash->{$next->{ID}}) ||
 3067:             ($browsePriv ne '2' && $browsePriv ne 'F')) {
 3068:                 push @branches, $next;
 3069:             }
 3070:     }
 3071:     return \@branches;
 3072: }
 3073: 
 3074: sub getPrevious {
 3075:     my $self = shift;
 3076:     my $alreadySeenHash = shift;
 3077:     my @branches;
 3078:     my $from = $self->from();
 3079:     foreach my $branch ( split /,/, $from) {
 3080:         my $choice = $self->{NAV_MAP}->getById($branch);
 3081:         my $prev = $choice->comesfrom();
 3082:         $prev = $self->{NAV_MAP}->getById($prev);
 3083: 
 3084:         # Skip it if we've already seen it or the user doesn't have
 3085:         # browse privs
 3086:         my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 3087:         if (!defined($alreadySeenHash) ||
 3088:             !defined($alreadySeenHash->{$prev->{ID}}) ||
 3089:             ($browsePriv ne '2' && $browsePriv ne 'F')) {
 3090:             push @branches, $prev;
 3091:         }
 3092:     }
 3093:     return \@branches;
 3094: }
 3095: 
 3096: =pod
 3097: 
 3098: =back
 3099: 
 3100: =cut
 3101: 
 3102: 1;
 3103: 
 3104: __END__
 3105: 
 3106: 

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