<?php if (!defined('PmWiki')) exit();
# vim: set ts=4 sw=4 et:
##
##        File: graphwiz.php
##     Version: 2009-04-02B
##      SVN ID: $Id$
##      Status: alpha
##      Author: Peter Bowers
## Create Date: April 2, 2009
##   Copyright: 2009, Peter Bowers
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License, Version 2, as
## published by the Free Software Foundation.
## http://www.gnu.org/copyleft/gpl.html
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##

$RecipeInfo['GraphWiz']['Version'] = '2009-04-02B';

$HandleActions['graphwiz'] = 'MkGraphWiz';
$gwStart = time();

function MkGraphWiz($pagename, $auth)
{
  if (@$_GET['timeout']) 
        set_time_limit($_GET['timeout']);
  $basegw = array($pagename);
  $targets = MkGW($pagename, $auth, 0, $basegw);
  # Now it's just a question of traversing $targets and outputting the appropriate syntax for GraphWiz -- seems like there's some array_walk() function or something that would do this nicely?
  if (!$targets) echo "ERROR: No links from this page.<br>\n";
  else {
    echo "<br>\ndigraph xyz {<br>\nsize=\"6,6\";<br>\nnode [color=lightblue2, style=filled];<br>\n";
    foreach ($targets as $k => $t)
      printgw($pagename, $t, $k);
    echo "}<br>\n";
  }
}

function MkGW($pagename, $auth, $level, $basegw)
{
  global $LinkTargets, $gwStart;

  if (time() > $gwStart+10) { echo "."; $gwStart = time(); flush; }
  #echo "MkGW($pagename, ...): Entering<br>\n";
  $page = RetrieveAuthPage($pagename, $auth);
  $text = $page['text'];
  if (!$text) return(0); // indicates we've reached a node
  $LinkTargets = array();
  $html = MarkupToHTML($pagename,$text); // calculate $LinkTargets as byproduct
  #echo "MkGW: LinkTargets=".print_r($LinkTargets,true)."<br>\n";
  $targets = array_keys((array)$LinkTargets);
  if (!$targets) return(0); // indicates we've reached a node
  foreach ($targets as $t) {
    if (in_array($t, $basegw)) {
      #echo "MkGW($pagename): $t is a repeat!<br>\n";
      $gw[$t] = -1;
    } else {
      $basegw[] = $t;
      #echo "MkGW($pagename): Calling MkGW($t)<br>\n";
      $gw[$t] = MkGW($t, $auth, $level+1, $basegw);
    }
  }
  #echo "MkGW($pagename): returning ".print_r($gw,true)."<br>\n";
  return($gw);
}

function printgw($src, $val, $key)
{
  echo "'$src' -> '$key';<br>\n";
  if (is_array($val))
    foreach ($val as $k => $t)
      printgw($key, $t, $k);
}