]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/GraphViz.php
Improve docs
[SourceForge/phpwiki.git] / lib / plugin / GraphViz.php
1 <?php // -*-php-*-
2 rcs_id('$Id: GraphViz.php,v 1.9 2007-01-11 21:16:30 rurban Exp $');
3 /*
4  Copyright 2004 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  * The GraphViz plugin passes all its arguments to the grapviz dot
25  * binary and displays the result as cached image (PNG,GIF,SVG) or imagemap.
26  *
27  * @Author: Reini Urban
28  *
29  * Note: 
30  * - We support only images supported by GD so far (PNG most likely). 
31  *   EPS, PS, SWF, SVG or SVGZ and imagemaps need to be tested.
32  *
33  * Usage:
34 <?plugin GraphViz [options...]
35    multiline dot script ...
36 ?>
37
38  * See also: VisualWiki, which depends on GraphViz and WikiPluginCached.
39  *
40  * TODO: 
41  * - neato binary ?
42  * - expand embedded <!plugin-list pagelist !> within the digraph script.
43  */
44
45 if (PHP_OS == "Darwin") { // Mac OS X
46     if (!defined("GRAPHVIZ_EXE"))
47         define('GRAPHVIZ_EXE', '/sw/bin/dot'); // graphviz via Fink
48     // Name of the Truetypefont - at least LucidaSansRegular.ttf is always present on OS X
49     if (!defined('VISUALWIKIFONT'))
50         define('VISUALWIKIFONT', 'LucidaSansRegular');
51     // The default font paths do not find your fonts, set the path here:
52     $fontpath = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/";
53     //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
54 }
55 elseif (isWindows()) {
56     if (!defined("GRAPHVIZ_EXE"))
57         define('GRAPHVIZ_EXE','dot.exe');
58     if (!defined('VISUALWIKIFONT'))
59         define('VISUALWIKIFONT', 'Arial');
60 } elseif ($_SERVER["SERVER_NAME"] == 'phpwiki.sourceforge.net') { // sf.net hack
61     if (!defined("GRAPHVIZ_EXE"))
62         define('GRAPHVIZ_EXE','/home/groups/p/ph/phpwiki/bin/dot');
63     if (!defined('VISUALWIKIFONT'))
64         define('VISUALWIKIFONT', 'luximr'); 
65 } else { // other os
66     if (!defined("GRAPHVIZ_EXE"))
67         define('GRAPHVIZ_EXE','/usr/local/bin/dot');
68     // Name of the Truetypefont - Helvetica is probably easier to read
69     if (!defined('VISUALWIKIFONT'))
70         define('VISUALWIKIFONT', 'Helvetica');
71     //define('VISUALWIKIFONT', 'Times');
72     //define('VISUALWIKIFONT', 'Arial');
73     // The default font paths do not find your fonts, set the path here:
74     //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
75     //$fontpath = "/usr/share/fonts/default/TrueType/";
76 }
77
78 require_once "lib/WikiPluginCached.php"; 
79
80 class WikiPlugin_GraphViz
81 extends WikiPluginCached
82 {
83
84     function _mapTypes() {
85         return array("imap", "cmapx", "ismap", "cmap");
86     }
87
88     /**
89      * Sets plugin type to MAP
90      * or HTML if the imagetype is not supported by GD (EPS, SVG, SVGZ) (not yet)
91      * or IMG_INLINE if device = png, gif or jpeg
92      */
93     function getPluginType() {
94         $type = $this->decideImgType($this->_args['imgtype']);
95         if ($type == $this->_args['imgtype'])
96             return PLUGIN_CACHED_IMG_INLINE;
97         $device = strtolower($this->_args['imgtype']);
98         if (in_array($device, $this->_mapTypes()))
99             return PLUGIN_CACHED_MAP;
100         if (in_array($device, array('svg','swf','svgz','eps','ps'))) {
101             switch ($this->_args['imgtype']) {
102                 case 'svg':
103                 case 'svgz':
104                    return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SVG_PNG;
105                 case 'swf':
106                    return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SWF;
107                 default: 
108                    return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_HTML;
109             }
110         }
111         else
112             return PLUGIN_CACHED_IMG_INLINE; // normal cached libgd image handles
113     }
114     function getName () {
115         return _("GraphViz");
116     }
117     function getDescription () {
118         return _("GraphViz image or imagemap creation of directed graphs");
119     }
120     function managesValidators() {
121         return true;
122     }
123     function getVersion() {
124         return preg_replace("/[Revision: $]/", '',
125                             "\$Revision: 1.9 $");
126     }
127     function getDefaultArguments() {
128         return array(
129                      'imgtype' => 'png', // png,gif,svgz,svg,...
130                      'alt'     => false,
131                      'pages'   => false,  // <!plugin-list !> support
132                      'exclude' => false,
133                      'help'    => false,
134                      'debug'    => false,
135                      );
136     }
137     function handle_plugin_args_cruft(&$argstr, &$args) {
138         $this->source = $argstr;
139     }
140     /**
141      * Sets the expire time to one day (so the image producing
142      * functions are called seldomly) or to about two minutes
143      * if a help screen is created.
144      */
145     function getExpire($dbi, $argarray, $request) {
146         if (!empty($argarray['help']))
147             return '+120'; // 2 minutes
148         return sprintf('+%d', 3*86000); // approx 3 days
149     }
150
151     /**
152      * Sets the imagetype according to user wishes and
153      * relies on WikiPluginCached to catch illegal image
154      * formats.
155      * @return string 'png', 'jpeg', 'gif'
156      */
157     function getImageType($dbi, $argarray, $request) {
158         return $argarray['imgtype'];
159     }
160
161     /**
162      * This gives an alternative text description of
163      * the image.
164      */
165     function getAlt($dbi, $argstr, $request) {
166         return (!empty($this->_args['alt'])) ? $this->_args['alt']
167                                              : $this->getDescription();
168     }
169
170     /**
171      * Returns an image containing a usage description of the plugin.
172      *
173      * TODO: *map features.
174      * @return string image handle
175      */
176     function helpImage() {
177         $def = $this->defaultArguments();
178         //$other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
179         //unset ($other_imgtypes[$def['imgtype']]);
180         $imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
181         $imgtypes = array_merge($imgtypes, array("svg", "svgz", "ps"), $this->_mapTypes());
182         $helparr = array(
183             '<?plugin GraphViz ' .
184             'imgtype'          => ' = "' . $def['imgtype'] . "(default)|" . join('|',$imgtypes).'"',
185             'alt'              => ' = "alternate image text"',
186             'pages'            => ' = "pagenames,*" or <!plugin-list !> pagelist as input',
187             'exclude'          => ' = "pagenames,*" or <!plugin-list !> pagelist as input',
188             'help'             => ' bool: displays this screen',
189             '...'              => ' all further lines below the first plugin line ',
190             ''                 => ' and inside the tags are the dot script.',
191             "\n  ?>"
192             );
193         $length = 0;
194         foreach($helparr as $alignright => $alignleft) {
195             $length = max($length, strlen($alignright));
196         }
197         $helptext ='';
198         foreach($helparr as $alignright => $alignleft) {
199             $helptext .= substr('                                                        '
200                                 . $alignright, -$length).$alignleft."\n";
201         }
202         return $this->text2img($helptext, 4, array(1, 0, 0),
203                                array(255, 255, 255));
204     }
205
206     function processSource($argarray=false) {
207         if (empty($this->source)) {
208             // create digraph from pages
209             if (empty($argarray['pages'])) {
210                 trigger_error(sprintf(_("%s is empty"), 'GraphViz argument source'), E_USER_WARNING);
211                 return '';
212             }
213             $source = "digraph GraphViz {\n";  // }
214             foreach ($argarray['pages'] as $name) { // support <!plugin-list !> pagelists
215                 // allow Page/SubPage
216                 $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, 
217                                    rawurlencode($name));
218                 $source .= "  \"$name\" [URL=\"$url\"];\n";
219             }
220             // {
221             $source .= "\n  }";
222         } else {
223             $source = $this->source;
224         }
225         /* //TODO: expand inlined plugin-list arg
226          $i = 0;
227          foreach ($source as $data) {
228              // hash or array?
229              if (is_array($data))
230                  $src .= ("\t" . join(" ", $data) . "\n");
231              else
232                  $src .= ("\t" . '"' . $data . '" ' . $i++ . "\n");
233              $src .= $source;
234              $source = $src;
235         }
236         */
237         return $source;
238     }
239
240     function createDotFile($tempfile='', $argarray=false) {
241         $this->source = $this->processSource($argarray);
242         if (!$this->source)
243             return false;
244         if (!$tempfile) {
245             $tempfile = $this->tempnam($this->getName().".dot");
246             @unlink($tempfile);
247         }
248         if (!$fp = fopen($tempfile, 'w'))
249             return false;
250         $ok = fwrite($fp, $this->source);
251         $ok = fclose($fp) && $ok;  // close anyway
252         return $ok ? $tempfile : false;
253     }
254
255     function getImage($dbi, $argarray, $request) {
256         $dotbin = GRAPHVIZ_EXE;
257         $tempfiles = $this->tempnam($this->getName());
258         $gif = $argarray['imgtype'];
259         if (in_array($gif, array("imap", "cmapx", "ismap", "cmap"))) {
260             $this->_mapfile = "$tempfiles.map";
261             $gif = $this->decideImgType($argarray['imgtype']);
262             if ($gif == $argarray['imgtype']) $gif = 'png';
263         }
264
265         $ImageCreateFromFunc = "ImageCreateFrom$gif";
266         $outfile = $tempfiles.".".$gif;
267         $debug = $request->getArg('debug');
268         if ($debug) {
269             $tempdir = dirname($tempfiles);
270             $tempout = $tempdir . "/.debug";
271         }
272         $source = $this->processSource($argarray);
273         if (empty($source))
274             return $this->error(fmt("No dot graph given"));
275         if (isWindows()) {
276           $ok = $tempfiles;
277           $dotfile = $this->createDotFile($tempfiles.'.dot', $argarray);
278           $args = "-T$gif $dotfile -o $outfile";
279           $cmdline = "$dotbin $args";
280           $code = $this->execute($cmdline, $outfile);
281           if (!$code)
282             $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline));
283         } else {
284           $args = "-T$gif -o $outfile";
285           $cmdline = "$dotbin $args";
286           if ($debug) $cmdline .= " > $tempout";
287           //if (!isWindows()) $cmdline .= " 2>&1";
288           $code = $this->filterThroughCmd($source, $cmdline);
289           if ($code)
290             $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline));
291           sleep(0.1);
292         }
293         if (! file_exists($outfile) ) {
294             $this->complain(sprintf(_("%s error: outputfile '%s' not created"), 
295                                     "GraphViz", $outfile));
296             $this->complain("\ncmd-line: $cmdline");
297             return false;
298         }
299         if (function_exists($ImageCreateFromFunc)) {
300             $img = $ImageCreateFromFunc( $outfile );
301             // clean up tempfiles
302             @unlink($tempfiles);
303             if (empty($argarray['debug']))
304                 foreach (array(".$gif",'.dot') as $ext) {
305                     //if (file_exists($tempfiles.$ext))
306                     @unlink($tempfiles.$ext);
307                 }
308             return $img;
309         }
310         return $outfile;
311     }
312     
313     // which argument must be set to 'png', for the fallback image when svg will fail on the client.
314     // type: SVG_PNG
315     function pngArg() {
316         return 'imgtype';
317     }
318     
319     function getMap($dbi, $argarray, $request) {
320         $result = $this->invokeDot($argarray);
321         if (isa($result, 'HtmlElement'))
322             return array(false, $result);
323         else
324             return $result;
325         // $img = $this->getImage($dbi, $argarray, $request);
326         //return array($this->_mapfile, $img);
327     }
328
329     /**
330      * Produces a dot file, calls dot twice to obtain an image and a
331      * text description of active areas for hyperlinking and returns
332      * an image and an html map.
333      *
334      * @param width     float   width of the output graph in inches
335      * @param height    float   height of the graph in inches
336      * @param colorby   string  color sceme beeing used ('age', 'revtime',
337      *                                                   'none')
338      * @param shape     string  node shape; 'ellipse', 'box', 'circle', 'point'
339      * @param label     string  not used anymore
340      */
341     function invokeDot($argarray) {
342         $dotbin = GRAPHVIZ_EXE;
343         $tempfiles = $this->tempnam($this->getName());
344         $gif = $argarray['imgtype'];
345         $ImageCreateFromFunc = "ImageCreateFrom$gif";
346         $outfile = $tempfiles.".".$gif;
347         $debug = $GLOBALS['request']->getArg('debug');
348         if ($debug) {
349             $tempdir = dirname($tempfiles);
350             $tempout = $tempdir . "/.debug";
351         }
352         $ok = $tempfiles;
353         $source = $this->processSource($argarray);
354         if (empty($source)) {
355             $this->complain("No dot graph given");
356             return array(false, $this->GetError());
357         }
358         //$ok = $ok and $this->createDotFile($tempfiles.'.dot', $argarray);
359
360         $args = "-T$gif $tempfiles.dot -o $outfile";
361         $cmdline1 = "$dotbin $args";
362         if ($debug) $cmdline1 .= " > $tempout";
363         $ok = $ok and $this->filterThroughCmd($source, $cmdline1);
364         //$ok = $this->execute("$dotbin -T$gif $tempfiles.dot -o $outfile" . 
365         //                   ($debug ? " > $tempout 2>&1" : " 2>&1"), $outfile)
366
367         $args = "-Timap $tempfiles.dot -o $tempfiles.map";
368         $cmdline2 = "$dotbin $args";
369         if ($debug) $cmdline2 .= " > $tempout";
370         $ok = $ok and $this->filterThroughCmd($source, $cmdline2);
371         // $this->execute("$dotbin -Timap $tempfiles.dot -o ".$tempfiles.".map" . 
372         //                    ($debug ? " > $tempout 2>&1" : " 2>&1"), $tempfiles.".map")
373         $ok = $ok and file_exists( $outfile );
374         $ok = $ok and file_exists( $tempfiles.'.map' );
375         $ok = $ok and ($img = $ImageCreateFromFunc($outfile));
376         $ok = $ok and ($fp = fopen($tempfiles.'.map', 'r'));
377
378         $map = HTML();
379         if ($debug == 'static') {
380             // workaround for misconfigured WikiPluginCached (sf.net) or dot.
381             // present a static png and map file.
382             if (file_exists($outfile) and filesize($outfile) > 900)
383                 $img = $outfile;
384             else
385                 $img = $tempdir . "/".$this->getName().".".$gif;
386             if (file_exists( $tempfiles.".map") and filesize($tempfiles.".map") > 20)
387                 $map = $tempfiles.".map";
388             else
389                 $map = $tempdir . "/".$this->getName().".map";
390             $img = $ImageCreateFromFunc($img);
391             $fp = fopen($map, 'r');
392             $map = HTML();      
393             $ok = true;
394         }
395         if ($ok and $fp) {
396             while (!feof($fp)) {
397                 $line = fgets($fp, 1000);
398                 if (substr($line, 0, 1) == '#')
399                     continue;
400                 list($shape, $url, $e1, $e2, $e3, $e4) = sscanf($line,
401                                                                 "%s %s %d,%d %d,%d");
402                 if ($shape != 'rect')
403                     continue;
404
405                 // dot sometimes gives not always the right order so
406                 // so we have to sort a bit
407                 $x1 = min($e1, $e3);
408                 $x2 = max($e1, $e3);
409                 $y1 = min($e2, $e4);
410                 $y2 = max($e2, $e4);
411                 $map->pushContent(HTML::area(array(
412                             'shape'  => 'rect',
413                             'coords' => "$x1,$y1,$x2,$y2",
414                             'href'   => $url,
415                             'title'  => rawurldecode($url),
416                             'alt' => $url)));
417             }
418             fclose($fp);
419             //trigger_error("url=".$url);
420         } else {
421             $this->complain("$outfile: "
422                             . (file_exists($outfile) ? filesize($outfile):'missing')
423                             ."\n"
424                             . "$tempfiles.map: "
425                             . (file_exists("$tempfiles.map") ? filesize("$tempfiles.map"):'missing'));
426             $this->complain("\ncmd-line: $cmdline1");
427             $this->complain("\ncmd-line: $cmdline2");
428             //trigger_error($this->GetError(), E_USER_WARNING);
429             return array(false, $this->GetError());
430         }
431
432         // clean up tempfiles
433         @unlink($tempfiles);
434         if ($ok and !$argarray['debug'])
435             foreach (array('',".$gif",'.map','.dot') as $ext) {
436                 @unlink($tempfiles.$ext);
437             }
438
439         if ($ok)
440             return array($img, $map);
441         else
442             return array(false, $this->GetError());
443     }
444
445 };
446
447 // $Log: not supported by cvs2svn $
448 // Revision 1.8  2007/01/10 22:28:43  rurban
449 // use temp dotfile on windows
450 //
451 // Revision 1.7  2006/12/22 17:55:06  rurban
452 // fix source handling
453 //
454 // Revision 1.6  2005/10/12 06:19:07  rurban
455 // protect unsafe calls
456 //
457 // Revision 1.5  2005/09/26 06:39:14  rurban
458 // use cached img and map - again. Remove execute from here
459 //
460 // Revision 1.4  2005/05/06 16:54:59  rurban
461 // add failing cmdline for .map
462 //
463 // Revision 1.3  2004/12/17 16:49:52  rurban
464 // avoid Invalid username message on Sign In button click
465 //
466 // Revision 1.2  2004/12/14 21:34:22  rurban
467 // fix syntax error
468 //
469 // Revision 1.1  2004/12/13 14:45:33  rurban
470 // new generic GraphViz plugin: similar to Ploticus
471 //
472
473 // For emacs users
474 // Local Variables:
475 // mode: php
476 // tab-width: 8
477 // c-basic-offset: 4
478 // c-hanging-comment-ender-p: nil
479 // indent-tabs-mode: nil
480 // End:
481 ?>