GraphViz.php 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Image_GraphViz
 *
 * Copyright (c) 2001-2006, Dr. Volker Göbbels <vmg@arachnion.de> and
 * Sebastian Bergmann <sb@sebastian-bergmann.de>. All rights reserved.
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Image
 * @package    GraphViz
 * @author     Dr. Volker Göbbels <vmg@arachnion.de>
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @author     Karsten Dambekalns <k.dambekalns@fishfarm.de>
 * @author     Michael Lively Jr. <mlively@ft11.net>
 * @copyright  2001-2006 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: $Id$
 * @link       http://pear.php.net/package/Image_GraphViz
 * @since      File available since Release 0.1
 */

require_once 'System.php';

/**
 * Interface to AT&T's GraphViz tools.
 *
 * The GraphViz class allows for the creation of and the work with directed
 * and undirected graphs and their visualization with AT&T's GraphViz tools.
 *
 * <code>
 * <?php
 * require_once 'Image/GraphViz.php';
 *
 * $graph = new Image_GraphViz();
 *
 * $graph->addNode(
 *   'Node1',
 *   array(
 *     'URL'   => 'http://link1',
 *     'label' => 'This is a label',
 *     'shape' => 'box'
 *   )
 * );
 *
 * $graph->addNode(
 *   'Node2',
 *   array(
 *     'URL'      => 'http://link2',
 *     'fontsize' => '14'
 *   )
 * );
 *
 * $graph->addNode(
 *   'Node3',
 *   array(
 *     'URL'      => 'http://link3',
 *     'fontsize' => '20'
 *   )
 * );
 *
 * $graph->addEdge(
 *   array(
 *     'Node1' => 'Node2'
 *   ),
 *   array(
 *     'label' => 'Edge Label'
 *   )
 * );
 *
 * $graph->addEdge(
 *   array(
 *     'Node1' => 'Node2'
 *   ),
 *   array(
 *     'color' => 'red'
 *   )
 * );
 *
 * $graph->image();
 * ?>
 * </code>
 *
 * @category  Image
 * @package   GraphViz
 * @author    Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @author    Dr. Volker Göbbels <vmg@arachnion.de>
 * @author    Karsten Dambekalns <k.dambekalns@fishfarm.de>
 * @author    Michael Lively Jr. <mlively@ft11.net>
 * @copyright Copyright &copy; 2001-2006 Dr. Volker Göbbels <vmg@arachnion.de> and Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license   http://www.php.net/license/3_0.txt The PHP License, Version 3.0
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/Image_GraphViz
 * @since     Class available since Release 0.1
 */
class Image_GraphViz
{
    /**
     * Path to GraphViz/dot command
     *
     * @var  string
     */
    var $dotCommand = 'dot';

    /**
     * Path to GraphViz/neato command
     *
     * @var  string
     */
    var $neatoCommand = 'neato';

    /**
     * Representation of the graph
     *
     * @var  array
     */
    var $graph;

    /**
     * Constructor.
     *
     * Setting the name of the Graph is useful for including multiple image maps on
     * one page. If not set, the graph will be named 'G'.
     *
     * @param  boolean $directed Directed (TRUE) or undirected (FALSE) graph.
     * @param  array   $attributes Attributes of the graph
     * @param  string  $name Name of the Graph
     * @access public
     */
    function Image_GraphViz($directed = TRUE, $attributes = array(), $name = NULL)
    {
        $this->setDirected($directed);
        $this->setAttributes($attributes);
        $this->graph['name'] = $name;
    }

    /**
     * Output image of the graph in a given format.
     *
     * @param  string  Format of the output image.
     *                 This may be one of the formats supported by GraphViz.
     * @access public
     */
    function image($format = 'svg')
    {
        if ($data = $this->fetch($format)) {
            $sendContentLengthHeader = TRUE;

            switch ($format) {
                case 'gif':
                case 'png':
                case 'wbmp': {
                    header('Content-Type: image/' . $format);
                }
                break;

                case 'jpg': {
                    header('Content-Type: image/jpeg');
                }
                break;

                case 'pdf': {
                    header('Content-Type: application/pdf');
                }
                break;

                case 'svg': {
                    header('Content-Type: image/svg+xml');
                }
                break;

                default: {
                    $sendContentLengthHeader = FALSE;
                }
            }

            if ($sendContentLengthHeader) {
                header('Content-Length: ' . strlen($data));
            }

            echo $data;
        }
    }

    /**
     * Return image (data) of the graph in a given format.
     *
     * @param  string  Format of the output image.
     *                 This may be one of the formats supported by GraphViz.
     * @return string  The image (data) created by GraphViz.
     * @access public
     * @since  Method available since Release 1.1.0
     */
    function fetch($format = 'svg')
    {
        if ($file = $this->saveParsedGraph()) {
            $outputfile = $file . '.' . $format;
            $command  = $this->graph['directed'] ? $this->dotCommand : $this->neatoCommand;
            $command .= ' -T' . escapeshellarg($format) . ' -o'  . escapeshellarg($outputfile) . ' ' . escapeshellarg($file);
    
            @`$command`;
            @unlink($file);
    
            $fp = fopen($outputfile, 'rb');
    
            if ($fp) {
                $data = fread($fp, filesize($outputfile));
                fclose($fp);
                @unlink($outputfile);
            }
    
            return $data;
        }
    
        return FALSE;
    }

    /**
     * Render a given dot file into another format.
     *
     * @param string The absolute path of the dot file to use.
     * @param string The absolute path of the file to save to.
     * @param string Format of the output image.
     *               This may be one of the formats supported by GraphViz.
     * @return bool  True if the file was saved, false otherwise.
     * @access public
     */
    function renderDotFile($dotfile, $outputfile, $format = 'svg')
    {
        if (file_exists($dotfile)) {
            $oldmtime = file_exists($outputfile) ? filemtime($outputfile) : 0;

            $command  = $this->graph['directed'] ? $this->dotCommand : $this->neatoCommand;
            $command .= ' -T' . escapeshellarg($format) . ' -o'  . escapeshellarg($outputfile) . ' ' . escapeshellarg($dotfile);
    
            @`$command`;
    
            if (file_exists($outputfile) && filemtime($outputfile) > $oldmtime) {
                return TRUE;
            }
        }

        return FALSE;
    }

    /**
     * Add a cluster to the graph.
     *
     * @param  string  ID.
     * @param  array   Title.
     * @param  array   Attributes of the cluster.
     * @access public
     */
    function addCluster($id, $title, $attributes = array())
    {
        $this->graph['clusters'][$id]['title'] = $title;
        $this->graph['clusters'][$id]['attributes'] = $attributes;
    }

    /**
     * Add a note to the graph.
     *
     * @param  string  Name of the node.
     * @param  array   Attributes of the node.
     * @param  string  Group of the node.
     * @access public
     */
    function addNode($name, $attributes = array(), $group = 'default')
    {
        $this->graph['nodes'][$group][$name] = $attributes;
    }

    /**
     * Remove a node from the graph.
     *
     * @param  Name of the node to be removed.
     * @access public
     */
    function removeNode($name, $group = 'default')
    {
        if (isset($this->graph['nodes'][$group][$name])) {
            unset($this->graph['nodes'][$group][$name]);
        }
    }

    /**
     * Add an edge to the graph.
     *
     * Caveat! This cannot handle multiple identical edges. If you use non-numeric
     * IDs for the nodes, this will not do (too much) harm. For numeric IDs the
     * array_merge() that is used will change the keys when merging arrays, leading
     * to new nodes appearing in the graph.
     *
     * @param  array Start and End node of the edge.
     * @param  array Attributes of the edge.
     * @access public
     */
    function addEdge($edge, $attributes = array())
    {
        if (is_array($edge)) {
            $from = key($edge);
            $to   = $edge[$from];
            $id   = $from . '_' . $to;

            if (!isset($this->graph['edges'][$id])) {
                $this->graph['edges'][$id] = $edge;
            } else {
                $this->graph['edges'][$id] = array_merge(
                  $this->graph['edges'][$id],
                  $edge
                );
            }

            if (is_array($attributes)) {
                if (!isset($this->graph['edgeAttributes'][$id])) {
                    $this->graph['edgeAttributes'][$id] = $attributes;
                } else {
                    $this->graph['edgeAttributes'][$id] = array_merge(
                      $this->graph['edgeAttributes'][$id],
                      $attributes
                    );
                }
            }
        }
    }

    /**
     * Remove an edge from the graph.
     *
     * @param  array Start and End node of the edge to be removed.
     * @access public
     */
    function removeEdge($edge)
    {
        if (is_array($edge)) {
              $from = key($edge);
              $to   = $edge[$from];
              $id   = $from . '_' . $to;

            if (isset($this->graph['edges'][$id])) {
                unset($this->graph['edges'][$id]);
            }

            if (isset($this->graph['edgeAttributes'][$id])) {
                unset($this->graph['edgeAttributes'][$id]);
            }
        }
    }

    /**
     * Add attributes to the graph.
     *
     * @param  array Attributes to be added to the graph.
     * @access public
     */
    function addAttributes($attributes)
    {
        if (is_array($attributes)) {
            $this->graph['attributes'] = array_merge(
              $this->graph['attributes'],
              $attributes
            );
        }
    }

    /**
     * Set attributes of the graph.
     *
     * @param  array Attributes to be set for the graph.
     * @access public
     */
    function setAttributes($attributes)
    {
        if (is_array($attributes)) {
            $this->graph['attributes'] = $attributes;
        }
    }

    /**
     * Set directed/undirected flag for the graph.
     *
     * @param  boolean Directed (TRUE) or undirected (FALSE) graph.
     * @access public
     */
    function setDirected($directed)
    {
        if (is_bool($directed)) {
            $this->graph['directed'] = $directed;
        }
    }

    /**
     * Load graph from file.
     *
     * @param  string  File to load graph from.
     * @access public
     */
    function load($file)
    {
        if ($serializedGraph = implode('', @file($file))) {
            $this->graph = unserialize($serializedGraph);
        }
    }

    /**
     * Save graph to file.
     *
     * @param  string  File to save the graph to.
     * @return mixed   File the graph was saved to, FALSE on failure.
     * @access public
     */
    function save($file = '')
    {
        $serializedGraph = serialize($this->graph);

        if (empty($file)) {
            $file = System::mktemp('graph_');
        }

        if ($fp = @fopen($file, 'w')) {
            @fputs($fp, $serializedGraph);
            @fclose($fp);

            return $file;
        }

        return FALSE;
    }

    /**
     * Parse the graph into GraphViz markup.
     *
     * @return string  GraphViz markup
     * @access public
     */
    function parse()
    {
        if (isset($this->graph['name']) && is_string($this->graph['name'])) {
            $parsedGraph = "digraph " . $this->graph['name'] . " {\n";
        } else {
            $parsedGraph = "digraph G {\n";
        }

        if (isset($this->graph['attributes'])) {
            foreach ($this->graph['attributes'] as $key => $value) {
                $attributeList[] = $key . '="' . $value . '"';
            }

            if (!empty($attributeList)) {
                $parsedGraph .= 'graph [ '.implode(',', $attributeList) . " ];\n";
            }
        }

        if (isset($this->graph['nodes'])) {
            foreach($this->graph['nodes'] as $group => $nodes) {
                if ($group != 'default') {
                    $parsedGraph .= sprintf(
                      "subgraph \"cluster_%s\" {\nlabel=\"%s\";\n",

                      $group,
                      isset($this->graph['clusters'][$group]) ? $this->graph['clusters'][$group]['title'] : ''
                    );

                    if (isset($this->graph['clusters'][$group]['attributes'])) {
                        unset($attributeList);

                        foreach ($this->graph['clusters'][$group]['attributes'] as $key => $value) {
                            $attributeList[] = $key . '="' . $value . '"';
                        }

                        if (!empty($attributeList)) {
                            $parsedGraph .= implode(',', $attributeList) . ";\n";
                        }
                    }
                }

                foreach($nodes as $node => $attributes) {
                    unset($attributeList);

                    foreach($attributes as $key => $value) {
                        $attributeList[] = $key . '="' . $value . '"';
                    }

                    if (!empty($attributeList)) {
                        $parsedGraph .= sprintf(
                          "\"%s\" [ %s ];\n",
                          addslashes(stripslashes($node)),
                          implode(',', $attributeList)
                        );
                    }
                }

                if ($group != 'default') {
                  $parsedGraph .= "}\n";
                }
            }
        }

        if (isset($this->graph['edges'])) {
            foreach($this->graph['edges'] as $label => $node) {
                unset($attributeList);

                $from = key($node);
                $to   = $node[$from];

                foreach($this->graph['edgeAttributes'][$label] as $key => $value) {
                    $attributeList[] = $key . '="' . $value . '"';
                }

                $parsedGraph .= sprintf(
                  '"%s" -> "%s"',
                  addslashes(stripslashes($from)),
                  addslashes(stripslashes($to))
                );
                
                if (!empty($attributeList)) {
                    $parsedGraph .= sprintf(
                      ' [ %s ]',
                      implode(',', $attributeList)
                    );
                }

                $parsedGraph .= ";\n";
            }
        }

        return $parsedGraph . "}\n";
    }

    /**
     * Save GraphViz markup to file.
     *
     * @param  string  File to write the GraphViz markup to.
     * @return mixed   File to which the GraphViz markup was
     *                 written, FALSE on failure.
     * @access public
     */
    function saveParsedGraph($file = '')
    {
        $parsedGraph = $this->parse();

        if (!empty($parsedGraph)) {
            if (empty($file)) {
                $file = System::mktemp('graph_');
            }

            if ($fp = @fopen($file, 'w')) {
                @fputs($fp, $parsedGraph);
                @fclose($fp);

                return $file;
            }
        }

        return FALSE;
    }
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */
?>