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 $countpages = count($pages);
372 // now select each page matching to given parameters
373 $all_selected = array_unique(array_merge(
374 $this->findbest($recent_nb, 'age', true),
375 $this->findbest($refined_nb, 'revtime', true),
376 $x = $this->findbest($backlink_nb, 'backlink_nb', false),
377 // $this->findbest($large_nb, 'size', false),
380 foreach ($all_selected as $name)
381 if (isset($pages[$name]))
382 $newpages[$name] = $pages[$name];
385 $this->pages = $newpages;
386 $pages = &$this->pages;
387 $this->names = array_keys($pages);
389 unset($all_selected);
391 $countpages = count($pages);
393 // remove dead links and collect links
395 while (list($name, $page) = each($pages)) {
396 if (is_array($page['backlinks'])) {
397 reset($page['backlinks']);
398 while (list($index, $link) = each($page['backlinks'])) {
399 if (!isset($pages[$link]) || $link == $name) {
400 unset($pages[$name]['backlinks'][$index]);
402 array_push($pages[$link]['links'], $name);
403 //array_push($this->everylink, array($link,$name));
409 if ($colorby == 'none')
411 list($oldestname) = $this->findbest(1, $colorby, false);
412 $this->oldest = $pages[$oldestname][$colorby];
413 foreach ($this->names as $name)
414 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
418 * Creates the text file description of the graph needed to invoke
421 * @param string $filename
422 * @param bool $argarray
423 * @internal param string $filename name of the dot file to be created
424 * @internal param float $width width of the output graph in inches
425 * @internal param float $height height of the graph in inches
426 * @internal param string $colorby color sceme beeing used ('age', 'revtime',
428 * @internal param string $shape node shape; 'ellipse', 'box', 'circle', 'point'
429 * @internal param string $label 'name': label by name,
430 * 'number': label by unique number
431 * @return boolean error status; true=ok; false=error
433 function createDotFile($filename, $argarray)
436 if (!$fp = fopen($filename, 'w'))
439 $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
442 $names = &$this->names;
443 $pages = &$this->pages;
445 $nametonumber = array_flip($names);
447 $dot = "digraph VisualWiki {\n" // }
448 . (!empty($fontpath) ? " fontpath=\"$fontpath\"\n" : "");
449 if ($width and $height)
450 $dot .= " size=\"$width,$height\";\n ";
454 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
457 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
460 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
463 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n";
466 foreach ($names as $name) {
468 $url = rawurlencode($name);
469 // patch to allow Page/SubPage
470 $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, $url);
471 $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
473 $dot .= " \"$nodename\" [URL=\"$url\"";
474 if ($colorby != 'none') {
475 $col = $pages[$name]['color'];
476 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
477 $col[0], $col[1], $col[2]);
481 if (!empty($pages[$name]['links'])) {
483 if ($label != 'name')
484 foreach ($pages[$name]['links'] as $linkname)
485 $linkarray[] = $nametonumber[$linkname] + 1;
487 $linkarray = $pages[$name]['links'];
488 $linkstring = join('"; "', $linkarray);
490 $c = count($pages[$name]['links']);
491 $dot .= " \"$nodename\" -> "
492 . ($c > 1 ? '{' : '')
494 . ($c > 1 ? '}' : '')
498 if ($colorby != 'none') {
499 $dot .= "\n subgraph cluster_legend {\n"
500 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
501 . " fillcolor=lightgrey;\n"
503 . " fontname=$fontname;\n"
504 . " fontsize=$fontsize;\n"
505 . " label=\"" . gettext("Legend") . "\";\n";
506 $oldest = ceil($this->oldest / (24 * 3600));
509 for ($i = 0; $i < $max; $i++) {
510 $time = floor($i / $max * $oldest);
511 $name = '"' . $time . ' ' . _("days") . '"';
512 $col = $this->getColor($i / $max);
513 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
514 $name, $fillstring, $col[0], $col[1], $col[2])
518 $dot .= ' ' . join(' -> ', $legend)
524 $this->source = $dot;
526 $ok = fwrite($fp, $dot);
527 $ok = fclose($fp) && $ok; // close anyway
533 * static workaround on broken Cache or broken dot executable,
534 * called only if debug=static.
539 * @param array $argarray
540 * @param request Request ???
541 * @internal param string $url url pointing to the image part of the map
542 * @internal param string $map <area> tags defining active
544 * @internal param \WikiDB $dbi database abstraction class
545 * @internal param array $argarray complete (!) arguments to produce
546 * image. It is not necessary to call
547 * WikiPlugin->getArgs anymore.
548 * @return string html output
550 function embedImg($url, &$dbi, $argarray, &$request)
552 if (!VISUALWIKI_ALLOWOPTIONS)
553 $argarray = $this->defaultarguments();
554 $this->checkArguments($argarray);
555 //extract($argarray);
556 if ($argarray['help'])
557 return array($this->helpImage(), ' '); // FIXME
558 $this->createColors();
559 $this->extract_wikipages($dbi, $argarray);
560 list($imagehandle, $content['html']) = $this->invokeDot($argarray);
561 // write to uploads and produce static url
562 $file_dir = getUploadFilePath();
563 $upload_dir = getUploadDataPath();
564 $tmpfile = tempnam($file_dir, "VisualWiki") . "." . $argarray['imgtype'];
565 WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile);
566 ImageDestroy($imagehandle);
567 return WikiPluginCached::embedMap(1, $upload_dir . basename($tmpfile), $content['html'],
568 $dbi, $argarray, $request);
572 * Prepares some rainbow colors for the nodes of the graph
573 * and stores them in an array which may be accessed with
574 * <code>getColor</code>.
576 function createColors()
578 $predefcolors = array(
579 array('red' => 255, 'green' => 0, 'blue' => 0),
580 array('red' => 255, 'green' => 255, 'blue' => 0),
581 array('red' => 0, 'green' => 255, 'blue' => 0),
582 array('red' => 0, 'green' => 255, 'blue' => 255),
583 array('red' => 0, 'green' => 0, 'blue' => 255),
584 array('red' => 100, 'green' => 100, 'blue' => 100)
588 $numberofcolors = count($predefcolors) * $steps;
591 foreach ($predefcolors as $color) {
597 for ($i = 0; $i < $steps; $i++)
598 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
599 floor(interpolate($oldcolor['red'], $color['red'], $i / $steps)),
600 floor(interpolate($oldcolor['green'], $color['green'], $i / $steps)),
601 floor(interpolate($oldcolor['blue'], $color['blue'], $i / $steps))
605 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
609 * Translates a value from 0.0 to 1.0 into rainbow color.
610 * red -> orange -> green -> blue -> gray
612 * @param float $promille
613 * @internal param float $promille value between 0.0 and 1.0
614 * @return array(red,green,blue)
616 function getColor($promille)
618 foreach ($this->ColorTab as $pro => $col) {
619 if ($promille * 1000 < $pro)
622 $lastcol = end($this->ColorTab);
628 * Linear interpolates a value between two point a and b
633 * @return float interpolated value
635 function interpolate($a, $b, $pos)
637 return $a + ($b - $a) * $pos;
644 // c-hanging-comment-ender-p: nil
645 // indent-tabs-mode: nil