2 rcs_id('$Id: VisualWiki.php,v 1.9 2004-06-03 09:40:57 rurban Exp $');
4 Copyright (C) 2002 Johannes Große (Johannes Große)
6 This file is (not yet) 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);
33 if (PHP_OS == "Darwin") { // Mac OS X
34 $dotbin = '/sw/bin/dot'; // graphviz via Fink
35 //$dotbin = '/usr/local/bin/dot';
37 // Name of the Truetypefont - at least LucidaSansRegular.ttf is always present on OS X
38 define('VISUALWIKIFONT', 'LucidaSansRegular');
40 // The default font paths do not find your fonts, set the path here:
41 $fontpath = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/";
42 //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
44 elseif (isWindows()) {
46 define('VISUALWIKIFONT', 'Arial');
48 $dotbin = '/usr/local/bin/dot';
50 // Name of the Truetypefont - Helvetica is probably easier to read
51 //define('VISUALWIKIFONT', 'Helvetica');
52 //define('VISUALWIKIFONT', 'Times');
53 //define('VISUALWIKIFONT', 'Arial');
54 define('VISUALWIKIFONT', 'luximr'); // sf.net, sf.net can only do gif
56 // The default font paths do not find your fonts, set the path here:
57 //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
58 //$fontpath = "/usr/share/fonts/default/TrueType/";
61 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
62 define('VISUALWIKI_ALLOWOPTIONS', false);
64 require_once "lib/WikiPluginCached.php";
66 class WikiPlugin_VisualWiki
67 extends WikiPluginCached
70 * Sets plugin type to map production
72 function getPluginType() {
73 return PLUGIN_CACHED_MAP;
77 * Sets the plugin's name to VisualWiki. It can be called by
78 * <code><?plugin VisualWiki?></code>, now. This
79 * name must correspond to the filename and the class name.
85 function getVersion() {
86 return preg_replace("/[Revision: $]/", '',
91 * Sets textual description.
93 function getDescription() {
94 return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
98 * Returns default arguments. This is put into a separate
99 * function to allow its usage by both <code>getDefaultArguments</code>
100 * and <code>checkArguments</code>
102 function defaultarguments() {
103 return array('imgtype' => 'png',
106 'colorby' => 'age', // sort by 'age' or 'revtime'
107 'fillnodes' => 'off',
109 'shape' => 'ellipse',
114 'neighbour_list' => '',
115 'exclude_list' => '',
116 'include_list' => '',
123 * Sets the default arguments. WikiPlugin also regards these as
124 * the allowed arguments. Since WikiPluginCached stores an image
125 * for each different set of parameters, there can be a lot of
126 * these (large) graphs if you allow different parameters.
127 * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
128 * to allow no options to be set and use only the default paramters.
129 * This will need an disk space of about 20 Kbyte all the time.
131 function getDefaultArguments() {
132 if (VISUALWIKI_ALLOWOPTIONS)
133 return $this->defaultarguments();
139 * Substitutes each forbidden parameter value by the default value
140 * defined in <code>defaultarguments</code>.
142 function checkArguments(&$arg) {
144 $def = $this->defaultarguments();
146 if (($width < 3) || ($width > 15))
147 $arg['width'] = $def['width'];
149 if (($height < 3) || ($height > 20))
150 $arg['height'] = $def['height'];
152 if (($fontsize < 8) || ($fontsize > 24))
153 $arg['fontsize'] = $def['fontsize'];
155 if (!in_array($label, array('name', 'number')))
156 $arg['label'] = $def['label'];
158 if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
160 $arg['shape'] = $def['shape'];
162 if (!in_array($colorby, array('age', 'revtime')))
163 $arg['colorby'] = $def['colorby'];
165 if (!in_array($fillnodes, array('on', 'off')))
166 $arg['fillnodes'] = $def['fillnodes'];
168 if (($large_nb < 0) || ($large_nb > 50))
169 $arg['large_nb'] = $def['large_nb'];
171 if (($recent_nb < 0) || ($recent_nb > 50))
172 $arg['recent_nb'] = $def['recent_nb'];
174 if (($refined_nb < 0 ) || ( $refined_nb > 50))
175 $arg['refined_nb'] = $def['refined_nb'];
177 if (($backlink_nb < 0) || ($backlink_nb > 50))
178 $arg['backlink_nb'] = $def['backlink_nb'];
180 // ToDo: check if "ImageCreateFrom$imgtype"() exists.
181 if (!in_array($imgtype, $GLOBALS['CacheParams']['imgtypes']))
182 $arg['imgtype'] = $def['imgtype'];
183 if (empty($fontname))
184 $arg['fontname'] = VISUALWIKIFONT;
188 * Checks options, creates help page if necessary, calls both
189 * database access and image map production functions.
190 * @return array($map,$html)
192 function getMap($dbi, $argarray, $request) {
193 if (!VISUALWIKI_ALLOWOPTIONS)
194 $argarray = $this->defaultarguments();
195 $this->checkArguments($argarray);
196 //extract($argarray);
197 if ($argarray['help'])
198 return array($this->helpImage(), ' '); // FIXME
199 $this->createColors();
200 $this->extract_wikipages($dbi, $argarray);
201 /* ($dbi, $large, $recent, $refined, $backlink,
202 $neighbour, $excludelist, $includelist, $color); */
203 return $this->invokeDot($argarray);
204 /* ($width, $height, $color, $shape, $text); */
208 * Sets the expire time to one day (so the image producing
209 * functions are called seldomly) or to about two minutes
210 * if a help screen is created.
212 function getExpire($dbi, $argarray, $request) {
213 if ($argarray['help'])
214 return '+120'; // 2 minutes
215 return sprintf('+%d', 3*86000); // approx 3 days
219 * Sets the imagetype according to user wishes and
220 * relies on WikiPluginCached to catch illegal image
222 * (I feel unsure whether this option is reasonable in
223 * this case, because png will definitely have the
226 * @return string 'png', 'gif', 'jpeg'
228 function getImageType($dbi, $argarray, $request) {
229 return $argarray['imgtype'];
233 * This gives an alternative text description of
234 * the image map. I do not know whether it interferes
235 * with the <code>title</code> attributes in <area>
236 * tags of the image map. Perhaps this will be removed.
239 function getAlt($dbi, $argstr, $request) {
240 return $this->getDescription();
243 // ------------------------------------------------------------------------------------------
246 * Returns an image containing a usage description of the plugin.
247 * @return string image handle
249 function helpImage() {
250 $def = $this->defaultarguments();
251 $other_imgtypes = $GLOBALS['CacheParams']['imgtypes'];
252 unset ($other_imgtypes[$def['imgtype']]);
254 '<?plugin '.$this->getName() .
255 ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['CacheParams']['imgtypes']).'"',
256 'width' => ' = "width in inches"',
257 'height' => ' = "height in inches"',
258 'fontname' => ' = "font family"',
259 'fontsize' => ' = "fontsize in points"',
260 'colorby' => ' = "age|revtime|none"',
261 'fillnodes' => ' = "on|off"',
262 'shape' => ' = "ellipse(default)|box|circle|point"',
263 'label' => ' = "name|number"',
264 'large_nb' => ' = "number of largest pages to be selected"',
265 'recent_nb' => ' = "number of youngest pages"',
266 'refined_nb' => ' = "#pages with smallest time between revisions"',
267 'backlink_nb' => ' = "number of pages with most backlinks"',
268 'neighbour_list' => ' = "find pages linked from and to these pages"',
269 'exclude_list' => ' = "colon separated list of pages to be excluded"',
270 'include_list' => ' = "colon separated list" ?>'
273 foreach($helparr as $alignright => $alignleft) {
274 $length = max($length, strlen($alignright));
277 foreach($helparr as $alignright => $alignleft) {
278 $helptext .= substr(' '
279 . $alignright, -$length).$alignleft."\n";
281 return $this->text2img($helptext, 4, array(1, 0, 0),
282 array(255, 255, 255));
287 * Selects the first (smallest or biggest) WikiPages in
290 * @param number integer number of page names to be found
291 * @param category string attribute of the pages which is used
293 * @param minimum boolean true finds smallest, false finds biggest
294 * @return array list of page names found to be the best
296 function findbest($number, $category, $minimum ) {
297 // select the $number best in the category '$category'
298 $pages = &$this->pages;
299 $names = &$this->names;
303 foreach($names as $name) {
306 $selected[$name] = $pages[$name][$category];
308 //echo "<pre>$category "; var_dump($selected); "</pre>";
309 $compareto = $minimum ? 0x79999999 : -0x79999999;
312 foreach ($names as $name) {
316 if (($crit = $pages[$name][$category]) < $compareto) {
317 $selected[$name] = $crit;
318 asort($selected, SORT_NUMERIC);
319 array_pop($selected);
320 $compareto = end($selected);
322 } elseif (($crit = $pages[$name][$category]) > $compareto) {
323 $selected[$name] = $crit;
324 arsort($selected, SORT_NUMERIC);
325 array_pop($selected);
326 $compareto = end($selected);
329 //echo "<pre>$category "; var_dump($selected); "</pre>";
331 return array_keys($selected);
336 * Extracts a subset of all pages from the wiki and find their
337 * connections to other pages. Also collects some page features
338 * like size, age, revision number which are used to find the
339 * most attractive pages.
341 * @param dbi WikiDB database handle to access all Wiki pages
342 * @param LARGE integer number of largest pages which should
344 * @param RECENT integer number of the youngest pages to be included
345 * @param REFINED integer number of the pages with shortes revision
347 * @param BACKLINK integer number of the pages with most backlinks
348 * @param EXCLUDELIST string colon ':' separated list of page names which
349 * should not be displayed (like PhpWiki, for
351 * @param INCLUDELIST string colon separated list of pages which are
352 * allways included (for example your own
354 * @param COLOR string 'age', 'revtime' or 'none'; Selects which
355 * page feature is used to determine the
356 * filling color of the nodes in the graph.
359 function extract_wikipages($dbi, $argarray) {
360 // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
361 // $EXCLUDELIST, $INCLUDELIST,$COLOR
365 // FIXME: gettextify?
366 $exclude_list = explode(':', $exclude_list);
367 $include_list = explode(':', $include_list);
368 $neighbour_list = explode(':', $neighbour_list);
370 // FIXME remove INCLUDED from EXCLUDED
373 $allpages = $dbi->getAllPages();
374 $pages = &$this->pages;
376 while ($page = $allpages->next()) {
377 $name = $page->getName();
379 // skip exluded pages
380 if (in_array($name, $exclude_list)) continue;
382 // false = get links from actual page
383 // true = get links to actual page ("backlinks")
384 $backlinks = $page->getLinks(true);
386 $bconnection = array();
387 while ($blink = $backlinks->next()) {
388 array_push($bconnection, $blink->getName());
392 // include all neighbours of pages listed in $NEIGHBOUR
393 if (in_array($name,$neighbour_list)) {
394 $l = $page->getLinks(false);
396 while ($link = $l->next()) {
397 array_push($con, $link->getName());
399 $include_list = array_merge($include_list, $bconnection, $con);
405 $currev = $page->getCurrentRevision();
407 $pages[$name] = array(
408 'age' => $now-$currev->get('mtime'),
409 'revnr' => $currev->getVersion(),
411 'backlink_nb' => count($bconnection),
412 'backlinks' => $bconnection,
413 'size' => 1000 // FIXME
415 $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
420 $this->names = array_keys($pages);
422 $countpages = count($pages);
424 // now select each page matching to given parameters
425 $all_selected = array_unique(array_merge(
426 $this->findbest($recent_nb, 'age', true),
427 $this->findbest($refined_nb, 'revtime', true),
428 $x = $this->findbest($backlink_nb, 'backlink_nb', false),
429 // $this->findbest($large_nb, 'size', false),
432 foreach($all_selected as $name)
433 if (isset($pages[$name]))
434 $newpages[$name] = $pages[$name];
437 $this->pages = $newpages;
438 $pages = &$this->pages;
439 $this->names = array_keys($pages);
441 unset($all_selected);
443 $countpages = count($pages);
445 // remove dead links and collect links
447 while( list($name,$page) = each($pages) ) {
448 if (is_array($page['backlinks'])) {
449 reset($page['backlinks']);
450 while ( list($index, $link) = each( $page['backlinks'] ) ) {
451 if ( !isset($pages[$link]) || $link == $name ) {
452 unset($pages[$name]['backlinks'][$index]);
454 array_push($pages[$link]['links'],$name);
455 //array_push($this->everylink, array($link,$name));
461 if ($colorby == 'none')
463 list($oldestname) = $this->findbest(1, $colorby, false);
464 $this->oldest = $pages[$oldestname][$colorby];
465 foreach($this->names as $name)
466 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
467 } // extract_wikipages
470 * Creates the text file description of the graph needed to invoke
473 * @param filename string name of the dot file to be created
474 * @param width float width of the output graph in inches
475 * @param height float height of the graph in inches
476 * @param colorby string color sceme beeing used ('age', 'revtime',
478 * @param shape string node shape; 'ellipse', 'box', 'circle', 'point'
479 * @param label string 'name': label by name,
480 * 'number': label by unique number
481 * @return boolean error status; true=ok; false=error
483 function createDotFile($filename, $argarray) {
485 if (!$fp = fopen($filename, 'w'))
488 $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
491 $names = &$this->names;
492 $pages = &$this->pages;
494 $nametonumber = array_flip($names);
496 $dot = "digraph VisualWiki {\n" // }
497 . (!empty($fontpath) ? " fontpath=\"$fontpath\"\n" : "")
498 . " size=\"$width,$height\";\n ";
502 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
505 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
508 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
511 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
515 foreach ($names as $name) {
517 $url = rawurlencode($name);
518 // patch to allow Page/SubPage
519 $url = preg_replace('/' . urlencode(SUBPAGE_SEPARATOR) . '/',
520 SUBPAGE_SEPARATOR, $url);
521 $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
523 $dot .= " \"$nodename\" [URL=\"$url\"";
524 if ($colorby != 'none') {
525 $col = $pages[$name]['color'];
526 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
527 $col[0], $col[1], $col[2]);
531 if (!empty($pages[$name]['links'])) {
533 if ($label != 'name')
534 foreach($pages[$name]['links'] as $linkname)
535 $linkarray[] = $nametonumber[$linkname] + 1;
537 $linkarray = $pages[$name]['links'];
538 $linkstring = join('"; "', $linkarray );
540 $c = count($pages[$name]['links']);
541 $dot .= " \"$nodename\" -> "
548 if ($colorby != 'none') {
549 $dot .= "\n subgraph cluster_legend {\n"
550 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
551 . " fillcolor=lightgrey;\n"
553 . " fontname=$fontname;\n"
554 . " fontsize=$fontsize;\n"
555 . " label=\"".gettext("Legend")."\";\n";
556 $oldest= ceil($this->oldest / (24 * 3600));
559 for($i = 0; $i < $max; $i++) {
560 $time = floor($i / $max * $oldest);
561 $name = '"' . $time .' '. _("days") .'"';
562 $col = $this->getColor($i/$max);
563 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
564 $name, $fillstring, $col[0], $col[1], $col[2])
568 $dot .= ' '. join(' -> ', $legend)
576 $ok = fwrite($fp, $dot);
577 $ok = fclose($fp) && $ok; // close anyway
583 * Execute system command.
585 * @param cmd string command to be invoked
586 * @return boolean error status; true=ok; false=error
588 function execute($cmd) {
589 exec($cmd, $outarr, $returnval); // normally 127
590 $errstr = join('',$outarr);
592 trigger_error($cmd.": ".$errstr, E_USER_WARNING);
595 return empty($errstr);
599 * Produces a dot file, calls dot twice to obtain an image and a
600 * text description of active areas for hyperlinking and returns
601 * an image and an html map.
603 * @param width float width of the output graph in inches
604 * @param height float height of the graph in inches
605 * @param colorby string color sceme beeing used ('age', 'revtime',
607 * @param shape string node shape; 'ellipse', 'box', 'circle', 'point'
608 * @param label string not used anymore
610 function invokeDot($argarray) {
612 $cacheparams = $GLOBALS['CacheParams'];
613 $tempfiles = tempnam($cacheparams['cache_dir'], 'VisualWiki');
614 $gif = $argarray['imgtype'];
615 $ImageCreateFromFunc = "ImageCreateFrom$gif";
617 && $this->createDotFile($tempfiles.'.dot',$argarray)
618 && $this->execute("$dotbin -T$gif $tempfiles.dot -o $tempfiles.$gif")
619 && $this->execute("$dotbin -Timap $tempfiles.dot -o $tempfiles.map")
620 && file_exists( "$tempfiles.$gif" )
621 && file_exists( $tempfiles.'.map' )
622 && ($img = $ImageCreateFromFunc( "$tempfiles.$gif" ))
623 && ($fp = fopen($tempfiles.'.map','r'));
628 $line = fgets($fp, 1000);
629 if (substr($line, 0, 1) == '#')
631 list($shape, $url, $e1, $e2, $e3, $e4) = sscanf($line,
632 "%s %s %d,%d %d,%d");
633 if ($shape != 'rect')
636 // dot sometimes gives not allways the right order so
637 // so we have to sort a bit
642 $map->pushContent(HTML::area(array(
644 'coords' => "$x1,$y1,$x2,$y2",
646 'title' => rawurldecode($url),
650 //trigger_error("url=".$url);
653 $tempfiles.$gif: ".(file_exists("$tempfiles.$gif") ? filesize("$tempfiles.$gif"):'missing')."
654 $tempfiles.map: ".(file_exists("$tempfiles.map") ? filesize("$tempfiles.map"):'missing')."
658 // clean up tempfiles
660 foreach (array('',".$gif",".map",".dot") as $ext) {
661 if (file_exists($tempfiles.$ext))
662 unlink($tempfiles.$ext);
666 return array($img, $map);
668 return array(false, false);
672 * Prepares some rainbow colors for the nodes of the graph
673 * and stores them in an array which may be accessed with
674 * <code>getColor</code>.
676 function createColors() {
677 $predefcolors = array(
678 array('red' => 255, 'green' => 0, 'blue' => 0),
679 array('red' => 255, 'green' => 255, 'blue' => 0),
680 array('red' => 0, 'green' => 255, 'blue' => 0),
681 array('red' => 0, 'green' => 255, 'blue' => 255),
682 array('red' => 0, 'green' => 0, 'blue' => 255),
683 array('red' => 100, 'green' => 100, 'blue' => 100)
687 $numberofcolors = count($predefcolors) * $steps;
690 foreach($predefcolors as $color) {
696 for ($i = 0; $i < $steps; $i++)
697 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
698 floor(interpolate( $oldcolor['red'], $color['red'], $i/$steps )),
699 floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
700 floor(interpolate( $oldcolor['blue'], $color['blue'], $i/$steps ))
704 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
708 * Translates a value from 0.0 to 1.0 into rainbow color.
709 * red -> orange -> green -> blue -> gray
711 * @param promille float value between 0.0 and 1.0
712 * @return array(red,green,blue)
714 function getColor($promille) {
715 foreach( $this->ColorTab as $pro => $col ) {
716 if ($promille*1000 < $pro)
719 $lastcol = end($this->ColorTab);
722 } // WikiPlugin_VisualWiki
725 * Linear interpolates a value between two point a and b
727 * @return float interpolated value
730 function interpolate($a, $b, $pos) {
731 return $a + ($b - $a) * $pos;
734 // $Log: not supported by cvs2svn $
735 // Revision 1.8 2004/01/26 09:18:00 rurban
736 // * changed stored pref representation as before.
737 // the array of objects is 1) bigger and 2)
738 // less portable. If we would import packed pref
739 // objects and the object definition was changed, PHP would fail.
740 // This doesn't happen with an simple array of non-default values.
741 // * use $prefs->retrieve and $prefs->store methods, where retrieve
742 // understands the interim format of array of objects also.
743 // * simplified $prefs->get() and fixed $prefs->set()
744 // * added $user->_userid and class '_WikiUser' portability functions
745 // * fixed $user object ->_level upgrading, mostly using sessions.
746 // this fixes yesterdays problems with loosing authorization level.
747 // * fixed WikiUserNew::checkPass to return the _level
748 // * fixed WikiUserNew::isSignedIn
749 // * added explodePageList to class PageList, support sortby arg
750 // * fixed UserPreferences for WikiUserNew
751 // * fixed WikiPlugin for empty defaults array
752 // * UnfoldSubpages: added pagename arg, renamed pages arg,
753 // removed sort arg, support sortby arg
755 // Revision 1.7 2003/03/03 13:57:31 carstenklapp
756 // Added fontpath (see PhpWiki:VisualWiki), tries to be smart about which OS.
757 // (This plugin still doesn't work for me on OS X, but at least image files
758 // are actually being created now in '/tmp/cache'.)
760 // Revision 1.6 2003/01/18 22:11:45 carstenklapp
762 // Reformatting & tabs to spaces;
763 // Added copyleft, getVersion, getDescription, rcs_id.
770 // c-hanging-comment-ender-p: nil
771 // indent-tabs-mode: nil