4 * Copyright (C) 2002 Johannes Große (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
19 * along with PhpWiki; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * Produces graphical site map of PhpWiki
25 * Example for an image map creating plugin. It produces a graphical
26 * sitemap of PhpWiki by calling the <code>dot</code> commandline tool
27 * from graphviz (http://www.graphviz.org).
28 * @author Johannes Große
31 /* define('VISUALWIKI_ALLOWOPTIONS', true); */
32 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
33 define('VISUALWIKI_ALLOWOPTIONS', false);
35 require_once "lib/plugin/GraphViz.php";
37 class WikiPlugin_VisualWiki
38 extends WikiPlugin_GraphViz
41 * Sets plugin type to map production
43 function getPluginType() {
44 return ($GLOBALS['request']->getArg('debug')) ? PLUGIN_CACHED_IMG_ONDEMAND
49 * Sets the plugin's name to VisualWiki. It can be called by
50 * <code><?plugin VisualWiki?></code>, now. This
51 * name must correspond to the filename and the class name.
57 function getVersion() {
58 return preg_replace("/[Revision: $]/", '',
63 * Sets textual description.
65 function getDescription() {
66 return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
70 * Returns default arguments. This is put into a separate
71 * function to allow its usage by both <code>getDefaultArguments</code>
72 * and <code>checkArguments</code>
74 function defaultarguments() {
75 return array('imgtype' => 'png',
76 'width' => false, // was 5, scale it automatically
77 'height' => false, // was 7, scale it automatically
78 'colorby' => 'age', // sort by 'age' or 'revtime'
86 'neighbour_list' => '',
95 * Sets the default arguments. WikiPlugin also regards these as
96 * the allowed arguments. Since WikiPluginCached stores an image
97 * for each different set of parameters, there can be a lot of
98 * these (large) graphs if you allow different parameters.
99 * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
100 * to allow no options to be set and use only the default parameters.
101 * This will need an disk space of about 20 Kbyte all the time.
103 function getDefaultArguments() {
104 if (VISUALWIKI_ALLOWOPTIONS)
105 return $this->defaultarguments();
111 * Substitutes each forbidden parameter value by the default value
112 * defined in <code>defaultarguments</code>.
114 function checkArguments(&$arg) {
116 $def = $this->defaultarguments();
117 if (($width < 3) || ($width > 15))
118 $arg['width'] = $def['width'];
119 if (($height < 3) || ($height > 20))
120 $arg['height'] = $def['height'];
121 if (($fontsize < 8) || ($fontsize > 24))
122 $arg['fontsize'] = $def['fontsize'];
123 if (!in_array($label, array('name', 'number')))
124 $arg['label'] = $def['label'];
126 if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
128 $arg['shape'] = $def['shape'];
129 if (!in_array($colorby, array('age', 'revtime')))
130 $arg['colorby'] = $def['colorby'];
131 if (!in_array($fillnodes, array('on', 'off')))
132 $arg['fillnodes'] = $def['fillnodes'];
133 if (($large_nb < 0) || ($large_nb > 50))
134 $arg['large_nb'] = $def['large_nb'];
135 if (($recent_nb < 0) || ($recent_nb > 50))
136 $arg['recent_nb'] = $def['recent_nb'];
137 if (($refined_nb < 0 ) || ( $refined_nb > 50))
138 $arg['refined_nb'] = $def['refined_nb'];
139 if (($backlink_nb < 0) || ($backlink_nb > 50))
140 $arg['backlink_nb'] = $def['backlink_nb'];
141 // ToDo: check if "ImageCreateFrom$imgtype"() exists.
142 if (!in_array($imgtype, $GLOBALS['PLUGIN_CACHED_IMGTYPES']))
143 $arg['imgtype'] = $def['imgtype'];
144 if (empty($fontname))
145 $arg['fontname'] = VISUALWIKIFONT;
149 * Checks options, creates help page if necessary, calls both
150 * database access and image map production functions.
151 * @return array($map,$html)
153 function getMap($dbi, $argarray, $request) {
154 if (!VISUALWIKI_ALLOWOPTIONS)
155 $argarray = $this->defaultarguments();
156 $this->checkArguments($argarray);
157 $request->setArg('debug',$argarray['debug']);
158 //extract($argarray);
159 if ($argarray['help'])
160 return array($this->helpImage(), ' '); // FIXME
161 $this->createColors();
162 $this->extract_wikipages($dbi, $argarray);
163 /* ($dbi, $large, $recent, $refined, $backlink,
164 $neighbour, $excludelist, $includelist, $color); */
165 $result = $this->invokeDot($argarray);
166 if (isa($result, 'HtmlElement'))
167 return array(false, $result);
170 /* => ($width, $height, $color, $shape, $text); */
173 // ------------------------------------------------------------------------------------------
176 * Returns an image containing a usage description of the plugin.
177 * @return string image handle
179 function helpImage() {
180 $def = $this->defaultarguments();
181 $other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
182 unset ($other_imgtypes[$def['imgtype']]);
184 '<?plugin '.$this->getName() .
185 ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['PLUGIN_CACHED_IMGTYPES']).'"',
186 'width' => ' = "width in inches"',
187 'height' => ' = "height in inches"',
188 'fontname' => ' = "font family"',
189 'fontsize' => ' = "fontsize in points"',
190 'colorby' => ' = "age|revtime|none"',
191 'fillnodes' => ' = "on|off"',
192 'shape' => ' = "ellipse(default)|box|circle|point"',
193 'label' => ' = "name|number"',
194 'large_nb' => ' = "number of largest pages to be selected"',
195 'recent_nb' => ' = "number of youngest pages"',
196 'refined_nb' => ' = "#pages with smallest time between revisions"',
197 'backlink_nb' => ' = "number of pages with most backlinks"',
198 'neighbour_list' => ' = "find pages linked from and to these pages"',
199 'exclude_list' => ' = "colon separated list of pages to be excluded"',
200 'include_list' => ' = "colon separated list" ?>'
203 foreach($helparr as $alignright => $alignleft) {
204 $length = max($length, strlen($alignright));
207 foreach($helparr as $alignright => $alignleft) {
208 $helptext .= substr(' '
209 . $alignright, -$length).$alignleft."\n";
211 return $this->text2img($helptext, 4, array(1, 0, 0),
212 array(255, 255, 255));
217 * Selects the first (smallest or biggest) WikiPages in
220 * @param number integer number of page names to be found
221 * @param category string attribute of the pages which is used
223 * @param minimum boolean true finds smallest, false finds biggest
224 * @return array list of page names found to be the best
226 function findbest($number, $category, $minimum ) {
227 // select the $number best in the category '$category'
228 $pages = &$this->pages;
229 $names = &$this->names;
233 foreach($names as $name) {
236 $selected[$name] = $pages[$name][$category];
238 //echo "<pre>$category "; var_dump($selected); "</pre>";
239 $compareto = $minimum ? 0x79999999 : -0x79999999;
242 foreach ($names as $name) {
246 if (($crit = $pages[$name][$category]) < $compareto) {
247 $selected[$name] = $crit;
248 asort($selected, SORT_NUMERIC);
249 array_pop($selected);
250 $compareto = end($selected);
252 } elseif (($crit = $pages[$name][$category]) > $compareto) {
253 $selected[$name] = $crit;
254 arsort($selected, SORT_NUMERIC);
255 array_pop($selected);
256 $compareto = end($selected);
259 //echo "<pre>$category "; var_dump($selected); "</pre>";
261 return array_keys($selected);
266 * Extracts a subset of all pages from the wiki and find their
267 * connections to other pages. Also collects some page features
268 * like size, age, revision number which are used to find the
269 * most attractive pages.
271 * @param dbi WikiDB database handle to access all Wiki pages
272 * @param LARGE integer number of largest pages which should
274 * @param RECENT integer number of the youngest pages to be included
275 * @param REFINED integer number of the pages with shortes revision
277 * @param BACKLINK integer number of the pages with most backlinks
278 * @param EXCLUDELIST string colon ':' separated list of page names which
279 * should not be displayed (like PhpWiki, for
281 * @param INCLUDELIST string colon separated list of pages which are
282 * always included (for example your own
284 * @param COLOR string 'age', 'revtime' or 'none'; Selects which
285 * page feature is used to determine the
286 * filling color of the nodes in the graph.
289 function extract_wikipages($dbi, $argarray) {
290 // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
291 // $EXCLUDELIST, $INCLUDELIST,$COLOR
295 // FIXME: gettextify?
296 $exclude_list = $exclude_list ? explode(':', $exclude_list) : array();
297 $include_list = $include_list ? explode(':', $include_list) : array();
298 $neighbour_list = $neighbour_list ? explode(':', $neighbour_list) : array();
300 // remove INCLUDED from EXCLUDED, includes override excludes.
301 if ($exclude_list and $include_list) {
302 $diff = array_diff($exclude_list, $include_list);
304 $exclude_list = $diff;
308 $allpages = $dbi->getAllPages(false, false, false, $exclude_list);
309 $pages = &$this->pages;
311 while ($page = $allpages->next()) {
312 $name = $page->getName();
314 // skip excluded pages
315 if (in_array($name, $exclude_list)) {
320 // false = get links from actual page
321 // true = get links to actual page ("backlinks")
322 $backlinks = $page->getLinks(true);
324 $bconnection = array();
325 while ($blink = $backlinks->next()) {
326 array_push($bconnection, $blink->getName());
331 // include all neighbours of pages listed in $NEIGHBOUR
332 if (in_array($name, $neighbour_list)) {
333 $ln = $page->getLinks(false);
335 while ($link = $ln->next()) {
336 array_push($con, $link->getName());
338 $include_list = array_merge($include_list, $bconnection, $con);
345 $rev = $page->getCurrentRevision();
347 $pages[$name] = array(
348 'age' => $now - $rev->get('mtime'),
349 'revnr' => $rev->getVersion(),
351 'backlink_nb' => count($bconnection),
352 'backlinks' => $bconnection,
353 'size' => 1000 // FIXME
355 $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
361 $this->names = array_keys($pages);
363 $countpages = count($pages);
365 // now select each page matching to given parameters
366 $all_selected = array_unique(array_merge(
367 $this->findbest($recent_nb, 'age', true),
368 $this->findbest($refined_nb, 'revtime', true),
369 $x = $this->findbest($backlink_nb, 'backlink_nb', false),
370 // $this->findbest($large_nb, 'size', false),
373 foreach($all_selected as $name)
374 if (isset($pages[$name]))
375 $newpages[$name] = $pages[$name];
378 $this->pages = $newpages;
379 $pages = &$this->pages;
380 $this->names = array_keys($pages);
382 unset($all_selected);
384 $countpages = count($pages);
386 // remove dead links and collect links
388 while( list($name, $page) = each($pages) ) {
389 if (is_array($page['backlinks'])) {
390 reset($page['backlinks']);
391 while ( list($index, $link) = each( $page['backlinks'] ) ) {
392 if ( !isset($pages[$link]) || $link == $name ) {
393 unset($pages[$name]['backlinks'][$index]);
395 array_push($pages[$link]['links'],$name);
396 //array_push($this->everylink, array($link,$name));
402 if ($colorby == 'none')
404 list($oldestname) = $this->findbest(1, $colorby, false);
405 $this->oldest = $pages[$oldestname][$colorby];
406 foreach($this->names as $name)
407 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
411 * Creates the text file description of the graph needed to invoke
414 * @param filename string name of the dot file to be created
415 * @param width float width of the output graph in inches
416 * @param height float height of the graph in inches
417 * @param colorby string color sceme beeing used ('age', 'revtime',
419 * @param shape string node shape; 'ellipse', 'box', 'circle', 'point'
420 * @param label string 'name': label by name,
421 * 'number': label by unique number
422 * @return boolean error status; true=ok; false=error
424 function createDotFile($filename, $argarray) {
426 if (!$fp = fopen($filename, 'w'))
429 $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
432 $names = &$this->names;
433 $pages = &$this->pages;
435 $nametonumber = array_flip($names);
437 $dot = "digraph VisualWiki {\n" // }
438 . (!empty($fontpath) ? " fontpath=\"$fontpath\"\n" : "");
439 if ($width and $height)
440 $dot .= " size=\"$width,$height\";\n ";
445 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
448 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
451 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
454 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
458 foreach ($names as $name) {
460 $url = rawurlencode($name);
461 // patch to allow Page/SubPage
462 $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, $url);
463 $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
465 $dot .= " \"$nodename\" [URL=\"$url\"";
466 if ($colorby != 'none') {
467 $col = $pages[$name]['color'];
468 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
469 $col[0], $col[1], $col[2]);
473 if (!empty($pages[$name]['links'])) {
475 if ($label != 'name')
476 foreach($pages[$name]['links'] as $linkname)
477 $linkarray[] = $nametonumber[$linkname] + 1;
479 $linkarray = $pages[$name]['links'];
480 $linkstring = join('"; "', $linkarray );
482 $c = count($pages[$name]['links']);
483 $dot .= " \"$nodename\" -> "
490 if ($colorby != 'none') {
491 $dot .= "\n subgraph cluster_legend {\n"
492 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
493 . " fillcolor=lightgrey;\n"
495 . " fontname=$fontname;\n"
496 . " fontsize=$fontsize;\n"
497 . " label=\"".gettext("Legend")."\";\n";
498 $oldest= ceil($this->oldest / (24 * 3600));
501 for($i = 0; $i < $max; $i++) {
502 $time = floor($i / $max * $oldest);
503 $name = '"' . $time .' '. _("days") .'"';
504 $col = $this->getColor($i/$max);
505 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
506 $name, $fillstring, $col[0], $col[1], $col[2])
510 $dot .= ' '. join(' -> ', $legend)
516 $this->source = $dot;
518 $ok = fwrite($fp, $dot);
519 $ok = fclose($fp) && $ok; // close anyway
526 * static workaround on broken Cache or broken dot executable,
527 * called only if debug=static.
530 * @param url string url pointing to the image part of the map
531 * @param map string <area> tags defining active
533 * @param dbi WikiDB database abstraction class
534 * @param argarray array complete (!) arguments to produce
535 * image. It is not necessary to call
536 * WikiPlugin->getArgs anymore.
537 * @param request Request ???
538 * @return string html output
540 function embedImg($url,&$dbi,$argarray,&$request) {
541 if (!VISUALWIKI_ALLOWOPTIONS)
542 $argarray = $this->defaultarguments();
543 $this->checkArguments($argarray);
544 //extract($argarray);
545 if ($argarray['help'])
546 return array($this->helpImage(), ' '); // FIXME
547 $this->createColors();
548 $this->extract_wikipages($dbi, $argarray);
549 list($imagehandle, $content['html']) = $this->invokeDot($argarray);
550 // write to uploads and produce static url
551 $file_dir = getUploadFilePath();
552 $upload_dir = getUploadDataPath();
553 $tmpfile = tempnam($file_dir,"VisualWiki").".".$argarray['imgtype'];
554 WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile);
555 ImageDestroy($imagehandle);
556 return WikiPluginCached::embedMap(1,$upload_dir.basename($tmpfile),$content['html'],
557 $dbi,$argarray,$request);
561 * Prepares some rainbow colors for the nodes of the graph
562 * and stores them in an array which may be accessed with
563 * <code>getColor</code>.
565 function createColors() {
566 $predefcolors = array(
567 array('red' => 255, 'green' => 0, 'blue' => 0),
568 array('red' => 255, 'green' => 255, 'blue' => 0),
569 array('red' => 0, 'green' => 255, 'blue' => 0),
570 array('red' => 0, 'green' => 255, 'blue' => 255),
571 array('red' => 0, 'green' => 0, 'blue' => 255),
572 array('red' => 100, 'green' => 100, 'blue' => 100)
576 $numberofcolors = count($predefcolors) * $steps;
579 foreach($predefcolors as $color) {
585 for ($i = 0; $i < $steps; $i++)
586 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
587 floor(interpolate( $oldcolor['red'], $color['red'], $i/$steps )),
588 floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
589 floor(interpolate( $oldcolor['blue'], $color['blue'], $i/$steps ))
593 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
597 * Translates a value from 0.0 to 1.0 into rainbow color.
598 * red -> orange -> green -> blue -> gray
600 * @param promille float value between 0.0 and 1.0
601 * @return array(red,green,blue)
603 function getColor($promille) {
604 foreach( $this->ColorTab as $pro => $col ) {
605 if ($promille*1000 < $pro)
608 $lastcol = end($this->ColorTab);
614 * Linear interpolates a value between two point a and b
616 * @return float interpolated value
618 function interpolate($a, $b, $pos) {
619 return $a + ($b - $a) * $pos;
626 // c-hanging-comment-ender-p: nil
627 // indent-tabs-mode: nil