File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.92: download - view: text, annotated - select for diffs
Tue Oct 29 20:20:45 2002 UTC (21 years, 7 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Split init and creation, as requested.

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

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