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