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