4 * Copyright (C) 2002 Johannes Große
6 * This file is part of PhpWiki.
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.
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.
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.
24 * Produces graphical site map of PhpWiki
25 * @author Johannes Große
28 /* define('VISUALWIKI_ALLOWOPTIONS', true); */
29 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
30 define('VISUALWIKI_ALLOWOPTIONS', false);
32 require_once 'lib/plugin/GraphViz.php';
34 class WikiPlugin_VisualWiki
35 extends WikiPlugin_GraphViz
38 * Sets plugin type to map production
40 function getPluginType()
42 return ($GLOBALS['request']->getArg('debug')) ? PLUGIN_CACHED_IMG_ONDEMAND
47 * Sets the plugin's name to VisualWiki. It can be called by
48 * <code><?plugin VisualWiki?></code>, now. This
49 * name must correspond to the filename and the class name.
57 * Sets textual description.
59 function getDescription()
61 return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
65 * Returns default arguments. This is put into a separate
66 * function to allow its usage by both <code>getDefaultArguments</code>
67 * and <code>checkArguments</code>
69 function defaultarguments()
71 return array('imgtype' => 'png',
72 'width' => false, // was 5, scale it automatically
73 'height' => false, // was 7, scale it automatically
74 'colorby' => 'age', // sort by 'age' or 'revtime'
82 'neighbour_list' => '',
91 * Sets the default arguments. WikiPlugin also regards these as
92 * the allowed arguments. Since WikiPluginCached stores an image
93 * for each different set of parameters, there can be a lot of
94 * these (large) graphs if you allow different parameters.
95 * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
96 * to allow no options to be set and use only the default parameters.
97 * This will need an disk space of about 20 Kbyte all the time.
99 function getDefaultArguments()
101 if (VISUALWIKI_ALLOWOPTIONS)
102 return $this->defaultarguments();
108 * Substitutes each forbidden parameter value by the default value
109 * defined in <code>defaultarguments</code>.
111 function checkArguments(&$arg)
114 $def = $this->defaultarguments();
115 if (($width < 3) || ($width > 15))
116 $arg['width'] = $def['width'];
117 if (($height < 3) || ($height > 20))
118 $arg['height'] = $def['height'];
119 if (($fontsize < 8) || ($fontsize > 24))
120 $arg['fontsize'] = $def['fontsize'];
121 if (!in_array($label, array('name', 'number')))
122 $arg['label'] = $def['label'];
124 if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
127 $arg['shape'] = $def['shape'];
128 if (!in_array($colorby, array('age', 'revtime')))
129 $arg['colorby'] = $def['colorby'];
130 if (!in_array($fillnodes, array('on', 'off')))
131 $arg['fillnodes'] = $def['fillnodes'];
132 if (($large_nb < 0) || ($large_nb > 50))
133 $arg['large_nb'] = $def['large_nb'];
134 if (($recent_nb < 0) || ($recent_nb > 50))
135 $arg['recent_nb'] = $def['recent_nb'];
136 if (($refined_nb < 0) || ($refined_nb > 50))
137 $arg['refined_nb'] = $def['refined_nb'];
138 if (($backlink_nb < 0) || ($backlink_nb > 50))
139 $arg['backlink_nb'] = $def['backlink_nb'];
140 // ToDo: check if "ImageCreateFrom$imgtype"() exists.
141 if (!in_array($imgtype, $GLOBALS['PLUGIN_CACHED_IMGTYPES']))
142 $arg['imgtype'] = $def['imgtype'];
143 if (empty($fontname))
144 $arg['fontname'] = VISUALWIKIFONT;
148 * Checks options, creates help page if necessary, calls both
149 * database access and image map production functions.
151 * @param array $argarray
152 * @param Request $request
153 * @return array($map,$html)
155 function getMap($dbi, $argarray, $request)
157 if (!VISUALWIKI_ALLOWOPTIONS)
158 $argarray = $this->defaultarguments();
159 $this->checkArguments($argarray);
160 $request->setArg('debug', $argarray['debug']);
161 //extract($argarray);
162 if ($argarray['help'])
163 return array($this->helpImage(), ' '); // FIXME
164 $this->createColors();
165 $this->extract_wikipages($dbi, $argarray);
166 /* ($dbi, $large, $recent, $refined, $backlink,
167 $neighbour, $excludelist, $includelist, $color); */
168 $result = $this->invokeDot($argarray);
169 if (isa($result, 'HtmlElement'))
170 return array(false, $result);
173 /* => ($width, $height, $color, $shape, $text); */
177 * Returns an image containing a usage description of the plugin.
178 * @return string image handle
182 $def = $this->defaultarguments();
183 $other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
184 unset ($other_imgtypes[$def['imgtype']]);
186 '<<' . $this->getName() .
187 ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|', $GLOBALS['PLUGIN_CACHED_IMGTYPES']) . '"',
188 'width' => ' = "width in inches"',
189 'height' => ' = "height in inches"',
190 'fontname' => ' = "font family"',
191 'fontsize' => ' = "fontsize in points"',
192 'colorby' => ' = "age|revtime|none"',
193 'fillnodes' => ' = "on|off"',
194 'shape' => ' = "ellipse(default)|box|circle|point"',
195 'label' => ' = "name|number"',
196 'large_nb' => ' = "number of largest pages to be selected"',
197 'recent_nb' => ' = "number of youngest pages"',
198 'refined_nb' => ' = "#pages with smallest time between revisions"',
199 'backlink_nb' => ' = "number of pages with most backlinks"',
200 'neighbour_list' => ' = "find pages linked from and to these pages"',
201 'exclude_list' => ' = "colon separated list of pages to be excluded"',
202 'include_list' => ' = "colon separated list" >>'
205 foreach ($helparr as $alignright => $alignleft) {
206 $length = max($length, strlen($alignright));
209 foreach ($helparr as $alignright => $alignleft) {
210 $helptext .= substr(' '
211 . $alignright, -$length) . $alignleft . "\n";
213 return $this->text2img($helptext, 4, array(1, 0, 0),
214 array(255, 255, 255));
218 * Selects the first (smallest or biggest) WikiPages in
222 * @param string $category
223 * @param bool $minimum
224 * @internal param int $number number of page names to be found
225 * @internal param string $category attribute of the pages which is used
227 * @internal param bool $minimum true finds smallest, false finds biggest
228 * @return array list of page names found to be the best
230 function findbest($number, $category, $minimum)
232 // select the $number best in the category '$category'
233 $pages = &$this->pages;
234 $names = &$this->names;
238 foreach ($names as $name) {
241 $selected[$name] = $pages[$name][$category];
243 //echo "<pre>$category "; var_dump($selected); "</pre>";
244 $compareto = $minimum ? 0x79999999 : -0x79999999;
247 foreach ($names as $name) {
251 if (($crit = $pages[$name][$category]) < $compareto) {
252 $selected[$name] = $crit;
253 asort($selected, SORT_NUMERIC);
254 array_pop($selected);
255 $compareto = end($selected);
257 } elseif (($crit = $pages[$name][$category]) > $compareto) {
258 $selected[$name] = $crit;
259 arsort($selected, SORT_NUMERIC);
260 array_pop($selected);
261 $compareto = end($selected);
264 //echo "<pre>$category "; var_dump($selected); "</pre>";
266 return array_keys($selected);
270 * Extracts a subset of all pages from the wiki and find their
271 * connections to other pages. Also collects some page features
272 * like size, age, revision number which are used to find the
273 * most attractive pages.
277 * @internal param \WikiDB $dbi database handle to access all Wiki pages
278 * @internal param int $LARGE number of largest pages which should
280 * @internal param int $RECENT number of the youngest pages to be included
281 * @internal param int $REFINED number of the pages with shortes revision
283 * @internal param int $BACKLINK number of the pages with most backlinks
284 * @internal param string $EXCLUDELIST colon ':' separated list of page names which
285 * should not be displayed (like PhpWiki, for
287 * @internal param string $INCLUDELIST colon separated list of pages which are
288 * always included (for example your own
290 * @internal param string $COLOR 'age', 'revtime' or 'none'; Selects which
291 * page feature is used to determine the
292 * filling color of the nodes in the graph.
295 function extract_wikipages($dbi, $argarray)
297 // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
298 // $EXCLUDELIST, $INCLUDELIST,$COLOR
302 // FIXME: gettextify?
303 $exclude_list = $exclude_list ? explode(':', $exclude_list) : array();
304 $include_list = $include_list ? explode(':', $include_list) : array();
305 $neighbour_list = $neighbour_list ? explode(':', $neighbour_list) : array();
307 // remove INCLUDED from EXCLUDED, includes override excludes.
308 if ($exclude_list and $include_list) {
309 $diff = array_diff($exclude_list, $include_list);
311 $exclude_list = $diff;
315 $allpages = $dbi->getAllPages(false, false, false, $exclude_list);
316 $pages = &$this->pages;
318 while ($page = $allpages->next()) {
319 $name = $page->getName();
321 // skip excluded pages
322 if (in_array($name, $exclude_list)) {
327 // false = get links from actual page
328 // true = get links to actual page ("backlinks")
329 $backlinks = $page->getLinks(true);
331 $bconnection = array();
332 while ($blink = $backlinks->next()) {
333 array_push($bconnection, $blink->getName());
338 // include all neighbours of pages listed in $NEIGHBOUR
339 if (in_array($name, $neighbour_list)) {
340 $ln = $page->getLinks(false);
342 while ($link = $ln->next()) {
343 array_push($con, $link->getName());
345 $include_list = array_merge($include_list, $bconnection, $con);
352 $rev = $page->getCurrentRevision();
354 $pages[$name] = array(
355 'age' => $now - $rev->get('mtime'),
356 'revnr' => $rev->getVersion(),
358 'backlink_nb' => count($bconnection),
359 'backlinks' => $bconnection,
360 'size' => 1000 // FIXME
362 $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
368 $this->names = array_keys($pages);
370 // now select each page matching to given parameters
371 $all_selected = array_unique(array_merge(
372 $this->findbest($recent_nb, 'age', true),
373 $this->findbest($refined_nb, 'revtime', true),
374 $x = $this->findbest($backlink_nb, 'backlink_nb', false),
375 // $this->findbest($large_nb, 'size', false),
378 foreach ($all_selected as $name)
379 if (isset($pages[$name]))
380 $newpages[$name] = $pages[$name];
383 $this->pages = $newpages;
384 $pages = &$this->pages;
385 $this->names = array_keys($pages);
387 unset($all_selected);
389 // remove dead links and collect links
391 while (list($name, $page) = each($pages)) {
392 if (is_array($page['backlinks'])) {
393 reset($page['backlinks']);
394 while (list($index, $link) = each($page['backlinks'])) {
395 if (!isset($pages[$link]) || $link == $name) {
396 unset($pages[$name]['backlinks'][$index]);
398 array_push($pages[$link]['links'], $name);
399 //array_push($this->everylink, array($link,$name));
405 if ($colorby == 'none')
407 list($oldestname) = $this->findbest(1, $colorby, false);
408 $this->oldest = $pages[$oldestname][$colorby];
409 foreach ($this->names as $name)
410 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
414 * Creates the text file description of the graph needed to invoke
417 * @param string $filename
418 * @param bool $argarray
419 * @internal param string $filename name of the dot file to be created
420 * @internal param float $width width of the output graph in inches
421 * @internal param float $height height of the graph in inches
422 * @internal param string $colorby color sceme beeing used ('age', 'revtime',
424 * @internal param string $shape node shape; 'ellipse', 'box', 'circle', 'point'
425 * @internal param string $label 'name': label by name,
426 * 'number': label by unique number
427 * @return boolean error status; true=ok; false=error
429 function createDotFile($filename, $argarray)
432 if (!$fp = fopen($filename, 'w'))
435 $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
437 $names = &$this->names;
438 $pages = &$this->pages;
440 $nametonumber = array_flip($names);
442 $dot = "digraph VisualWiki {\n" // }
443 . (!empty($fontpath) ? " fontpath=\"$fontpath\"\n" : "");
444 if ($width and $height)
445 $dot .= " size=\"$width,$height\";\n ";
449 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
452 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
455 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
458 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n";
461 foreach ($names as $name) {
463 $url = rawurlencode($name);
464 // patch to allow Page/SubPage
465 $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, $url);
466 $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
468 $dot .= " \"$nodename\" [URL=\"$url\"";
469 if ($colorby != 'none') {
470 $col = $pages[$name]['color'];
471 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
472 $col[0], $col[1], $col[2]);
476 if (!empty($pages[$name]['links'])) {
478 if ($label != 'name')
479 foreach ($pages[$name]['links'] as $linkname)
480 $linkarray[] = $nametonumber[$linkname] + 1;
482 $linkarray = $pages[$name]['links'];
483 $linkstring = join('"; "', $linkarray);
485 $c = count($pages[$name]['links']);
486 $dot .= " \"$nodename\" -> "
487 . ($c > 1 ? '{' : '')
489 . ($c > 1 ? '}' : '')
493 if ($colorby != 'none') {
494 $dot .= "\n subgraph cluster_legend {\n"
495 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
496 . " fillcolor=lightgrey;\n"
498 . " fontname=$fontname;\n"
499 . " fontsize=$fontsize;\n"
500 . " label=\"" . gettext("Legend") . "\";\n";
501 $oldest = ceil($this->oldest / (24 * 3600));
504 for ($i = 0; $i < $max; $i++) {
505 $time = floor($i / $max * $oldest);
506 $name = '"' . $time . ' ' . _("days") . '"';
507 $col = $this->getColor($i / $max);
508 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
509 $name, $fillstring, $col[0], $col[1], $col[2])
513 $dot .= ' ' . join(' -> ', $legend)
519 $this->source = $dot;
521 $ok = fwrite($fp, $dot);
522 $ok = fclose($fp) && $ok; // close anyway
528 * static workaround on broken Cache or broken dot executable,
529 * called only if debug=static.
534 * @param array $argarray
535 * @param request Request ???
536 * @internal param string $url url pointing to the image part of the map
537 * @internal param string $map <area> tags defining active
539 * @internal param \WikiDB $dbi database abstraction class
540 * @internal param array $argarray complete (!) arguments to produce
541 * image. It is not necessary to call
542 * WikiPlugin->getArgs anymore.
543 * @return string html output
545 function embedImg($url, &$dbi, $argarray, &$request)
547 if (!VISUALWIKI_ALLOWOPTIONS)
548 $argarray = $this->defaultarguments();
549 $this->checkArguments($argarray);
550 //extract($argarray);
551 if ($argarray['help'])
552 return array($this->helpImage(), ' '); // FIXME
553 $this->createColors();
554 $this->extract_wikipages($dbi, $argarray);
555 list($imagehandle, $content['html']) = $this->invokeDot($argarray);
556 // write to uploads and produce static url
557 $file_dir = getUploadFilePath();
558 $upload_dir = getUploadDataPath();
559 $tmpfile = tempnam($file_dir, "VisualWiki") . "." . $argarray['imgtype'];
560 WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile);
561 ImageDestroy($imagehandle);
562 return WikiPluginCached::embedMap(1, $upload_dir . basename($tmpfile), $content['html'],
563 $dbi, $argarray, $request);
567 * Prepares some rainbow colors for the nodes of the graph
568 * and stores them in an array which may be accessed with
569 * <code>getColor</code>.
571 function createColors()
573 $predefcolors = array(
574 array('red' => 255, 'green' => 0, 'blue' => 0),
575 array('red' => 255, 'green' => 255, 'blue' => 0),
576 array('red' => 0, 'green' => 255, 'blue' => 0),
577 array('red' => 0, 'green' => 255, 'blue' => 255),
578 array('red' => 0, 'green' => 0, 'blue' => 255),
579 array('red' => 100, 'green' => 100, 'blue' => 100)
583 $numberofcolors = count($predefcolors) * $steps;
586 foreach ($predefcolors as $color) {
592 for ($i = 0; $i < $steps; $i++)
593 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
594 floor(interpolate($oldcolor['red'], $color['red'], $i / $steps)),
595 floor(interpolate($oldcolor['green'], $color['green'], $i / $steps)),
596 floor(interpolate($oldcolor['blue'], $color['blue'], $i / $steps))
600 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
604 * Translates a value from 0.0 to 1.0 into rainbow color.
605 * red -> orange -> green -> blue -> gray
607 * @param float $promille
608 * @internal param float $promille value between 0.0 and 1.0
609 * @return array(red,green,blue)
611 function getColor($promille)
613 foreach ($this->ColorTab as $pro => $col) {
614 if ($promille * 1000 < $pro)
617 $lastcol = end($this->ColorTab);
623 * Linear interpolates a value between two point a and b
628 * @return float interpolated value
630 function interpolate($a, $b, $pos)
632 return $a + ($b - $a) * $pos;
639 // c-hanging-comment-ender-p: nil
640 // indent-tabs-mode: nil