2 rcs_id('$Id: VisualWiki.php,v 1.11 2004-09-06 10:10:27 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';
49 // $dotbin = '/home/groups/p/ph/phpwiki/bin/dot';
51 // Name of the Truetypefont - Helvetica is probably easier to read
52 //define('VISUALWIKIFONT', 'Helvetica');
53 //define('VISUALWIKIFONT', 'Times');
54 //define('VISUALWIKIFONT', 'Arial');
55 define('VISUALWIKIFONT', 'luximr'); // sf.net, sf.net can only do gif
57 // The default font paths do not find your fonts, set the path here:
58 //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
59 //$fontpath = "/usr/share/fonts/default/TrueType/";
62 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
63 define('VISUALWIKI_ALLOWOPTIONS', false);
65 require_once "lib/WikiPluginCached.php";
67 class WikiPlugin_VisualWiki
68 extends WikiPluginCached
71 * Sets plugin type to map production
73 function getPluginType() {
74 return PLUGIN_CACHED_MAP;
78 * Sets the plugin's name to VisualWiki. It can be called by
79 * <code><?plugin VisualWiki?></code>, now. This
80 * name must correspond to the filename and the class name.
86 function getVersion() {
87 return preg_replace("/[Revision: $]/", '',
88 "\$Revision: 1.11 $");
92 * Sets textual description.
94 function getDescription() {
95 return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
99 * Returns default arguments. This is put into a separate
100 * function to allow its usage by both <code>getDefaultArguments</code>
101 * and <code>checkArguments</code>
103 function defaultarguments() {
104 return array('imgtype' => 'png',
107 'colorby' => 'age', // sort by 'age' or 'revtime'
108 'fillnodes' => 'off',
110 'shape' => 'ellipse',
115 'neighbour_list' => '',
116 'exclude_list' => '',
117 'include_list' => '',
124 * Sets the default arguments. WikiPlugin also regards these as
125 * the allowed arguments. Since WikiPluginCached stores an image
126 * for each different set of parameters, there can be a lot of
127 * these (large) graphs if you allow different parameters.
128 * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
129 * to allow no options to be set and use only the default paramters.
130 * This will need an disk space of about 20 Kbyte all the time.
132 function getDefaultArguments() {
133 if (VISUALWIKI_ALLOWOPTIONS)
134 return $this->defaultarguments();
140 * Substitutes each forbidden parameter value by the default value
141 * defined in <code>defaultarguments</code>.
143 function checkArguments(&$arg) {
145 $def = $this->defaultarguments();
147 if (($width < 3) || ($width > 15))
148 $arg['width'] = $def['width'];
150 if (($height < 3) || ($height > 20))
151 $arg['height'] = $def['height'];
153 if (($fontsize < 8) || ($fontsize > 24))
154 $arg['fontsize'] = $def['fontsize'];
156 if (!in_array($label, array('name', 'number')))
157 $arg['label'] = $def['label'];
159 if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
161 $arg['shape'] = $def['shape'];
163 if (!in_array($colorby, array('age', 'revtime')))
164 $arg['colorby'] = $def['colorby'];
166 if (!in_array($fillnodes, array('on', 'off')))
167 $arg['fillnodes'] = $def['fillnodes'];
169 if (($large_nb < 0) || ($large_nb > 50))
170 $arg['large_nb'] = $def['large_nb'];
172 if (($recent_nb < 0) || ($recent_nb > 50))
173 $arg['recent_nb'] = $def['recent_nb'];
175 if (($refined_nb < 0 ) || ( $refined_nb > 50))
176 $arg['refined_nb'] = $def['refined_nb'];
178 if (($backlink_nb < 0) || ($backlink_nb > 50))
179 $arg['backlink_nb'] = $def['backlink_nb'];
181 // ToDo: check if "ImageCreateFrom$imgtype"() exists.
182 if (!in_array($imgtype, $GLOBALS['PLUGIN_CACHED_IMGTYPES']))
183 $arg['imgtype'] = $def['imgtype'];
184 if (empty($fontname))
185 $arg['fontname'] = VISUALWIKIFONT;
189 * Checks options, creates help page if necessary, calls both
190 * database access and image map production functions.
191 * @return array($map,$html)
193 function getMap($dbi, $argarray, $request) {
194 if (!VISUALWIKI_ALLOWOPTIONS)
195 $argarray = $this->defaultarguments();
196 $this->checkArguments($argarray);
197 //extract($argarray);
198 if ($argarray['help'])
199 return array($this->helpImage(), ' '); // FIXME
200 $this->createColors();
201 $this->extract_wikipages($dbi, $argarray);
202 /* ($dbi, $large, $recent, $refined, $backlink,
203 $neighbour, $excludelist, $includelist, $color); */
204 return $this->invokeDot($argarray);
205 /* ($width, $height, $color, $shape, $text); */
209 * Sets the expire time to one day (so the image producing
210 * functions are called seldomly) or to about two minutes
211 * if a help screen is created.
213 function getExpire($dbi, $argarray, $request) {
214 if ($argarray['help'])
215 return '+120'; // 2 minutes
216 return sprintf('+%d', 3*86000); // approx 3 days
220 * Sets the imagetype according to user wishes and
221 * relies on WikiPluginCached to catch illegal image
223 * (I feel unsure whether this option is reasonable in
224 * this case, because png will definitely have the
227 * @return string 'png', 'gif', 'jpeg'
229 function getImageType($dbi, $argarray, $request) {
230 return $argarray['imgtype'];
234 * This gives an alternative text description of
235 * the image map. I do not know whether it interferes
236 * with the <code>title</code> attributes in <area>
237 * tags of the image map. Perhaps this will be removed.
240 function getAlt($dbi, $argstr, $request) {
241 return $this->getDescription();
244 // ------------------------------------------------------------------------------------------
247 * Returns an image containing a usage description of the plugin.
248 * @return string image handle
250 function helpImage() {
251 $def = $this->defaultarguments();
252 $other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
253 unset ($other_imgtypes[$def['imgtype']]);
255 '<?plugin '.$this->getName() .
256 ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['PLUGIN_CACHED_IMGTYPES']).'"',
257 'width' => ' = "width in inches"',
258 'height' => ' = "height in inches"',
259 'fontname' => ' = "font family"',
260 'fontsize' => ' = "fontsize in points"',
261 'colorby' => ' = "age|revtime|none"',
262 'fillnodes' => ' = "on|off"',
263 'shape' => ' = "ellipse(default)|box|circle|point"',
264 'label' => ' = "name|number"',
265 'large_nb' => ' = "number of largest pages to be selected"',
266 'recent_nb' => ' = "number of youngest pages"',
267 'refined_nb' => ' = "#pages with smallest time between revisions"',
268 'backlink_nb' => ' = "number of pages with most backlinks"',
269 'neighbour_list' => ' = "find pages linked from and to these pages"',
270 'exclude_list' => ' = "colon separated list of pages to be excluded"',
271 'include_list' => ' = "colon separated list" ?>'
274 foreach($helparr as $alignright => $alignleft) {
275 $length = max($length, strlen($alignright));
278 foreach($helparr as $alignright => $alignleft) {
279 $helptext .= substr(' '
280 . $alignright, -$length).$alignleft."\n";
282 return $this->text2img($helptext, 4, array(1, 0, 0),
283 array(255, 255, 255));
288 * Selects the first (smallest or biggest) WikiPages in
291 * @param number integer number of page names to be found
292 * @param category string attribute of the pages which is used
294 * @param minimum boolean true finds smallest, false finds biggest
295 * @return array list of page names found to be the best
297 function findbest($number, $category, $minimum ) {
298 // select the $number best in the category '$category'
299 $pages = &$this->pages;
300 $names = &$this->names;
304 foreach($names as $name) {
307 $selected[$name] = $pages[$name][$category];
309 //echo "<pre>$category "; var_dump($selected); "</pre>";
310 $compareto = $minimum ? 0x79999999 : -0x79999999;
313 foreach ($names as $name) {
317 if (($crit = $pages[$name][$category]) < $compareto) {
318 $selected[$name] = $crit;
319 asort($selected, SORT_NUMERIC);
320 array_pop($selected);
321 $compareto = end($selected);
323 } elseif (($crit = $pages[$name][$category]) > $compareto) {
324 $selected[$name] = $crit;
325 arsort($selected, SORT_NUMERIC);
326 array_pop($selected);
327 $compareto = end($selected);
330 //echo "<pre>$category "; var_dump($selected); "</pre>";
332 return array_keys($selected);
337 * Extracts a subset of all pages from the wiki and find their
338 * connections to other pages. Also collects some page features
339 * like size, age, revision number which are used to find the
340 * most attractive pages.
342 * @param dbi WikiDB database handle to access all Wiki pages
343 * @param LARGE integer number of largest pages which should
345 * @param RECENT integer number of the youngest pages to be included
346 * @param REFINED integer number of the pages with shortes revision
348 * @param BACKLINK integer number of the pages with most backlinks
349 * @param EXCLUDELIST string colon ':' separated list of page names which
350 * should not be displayed (like PhpWiki, for
352 * @param INCLUDELIST string colon separated list of pages which are
353 * allways included (for example your own
355 * @param COLOR string 'age', 'revtime' or 'none'; Selects which
356 * page feature is used to determine the
357 * filling color of the nodes in the graph.
360 function extract_wikipages($dbi, $argarray) {
361 // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
362 // $EXCLUDELIST, $INCLUDELIST,$COLOR
366 // FIXME: gettextify?
367 $exclude_list = explode(':', $exclude_list);
368 $include_list = explode(':', $include_list);
369 $neighbour_list = explode(':', $neighbour_list);
371 // FIXME remove INCLUDED from EXCLUDED
374 $allpages = $dbi->getAllPages();
375 $pages = &$this->pages;
377 while ($page = $allpages->next()) {
378 $name = $page->getName();
380 // skip exluded pages
381 if (in_array($name, $exclude_list)) continue;
383 // false = get links from actual page
384 // true = get links to actual page ("backlinks")
385 $backlinks = $page->getLinks(true);
387 $bconnection = array();
388 while ($blink = $backlinks->next()) {
389 array_push($bconnection, $blink->getName());
393 // include all neighbours of pages listed in $NEIGHBOUR
394 if (in_array($name,$neighbour_list)) {
395 $l = $page->getLinks(false);
397 while ($link = $l->next()) {
398 array_push($con, $link->getName());
400 $include_list = array_merge($include_list, $bconnection, $con);
406 $currev = $page->getCurrentRevision();
408 $pages[$name] = array(
409 'age' => $now-$currev->get('mtime'),
410 'revnr' => $currev->getVersion(),
412 'backlink_nb' => count($bconnection),
413 'backlinks' => $bconnection,
414 'size' => 1000 // FIXME
416 $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
421 $this->names = array_keys($pages);
423 $countpages = count($pages);
425 // now select each page matching to given parameters
426 $all_selected = array_unique(array_merge(
427 $this->findbest($recent_nb, 'age', true),
428 $this->findbest($refined_nb, 'revtime', true),
429 $x = $this->findbest($backlink_nb, 'backlink_nb', false),
430 // $this->findbest($large_nb, 'size', false),
433 foreach($all_selected as $name)
434 if (isset($pages[$name]))
435 $newpages[$name] = $pages[$name];
438 $this->pages = $newpages;
439 $pages = &$this->pages;
440 $this->names = array_keys($pages);
442 unset($all_selected);
444 $countpages = count($pages);
446 // remove dead links and collect links
448 while( list($name,$page) = each($pages) ) {
449 if (is_array($page['backlinks'])) {
450 reset($page['backlinks']);
451 while ( list($index, $link) = each( $page['backlinks'] ) ) {
452 if ( !isset($pages[$link]) || $link == $name ) {
453 unset($pages[$name]['backlinks'][$index]);
455 array_push($pages[$link]['links'],$name);
456 //array_push($this->everylink, array($link,$name));
462 if ($colorby == 'none')
464 list($oldestname) = $this->findbest(1, $colorby, false);
465 $this->oldest = $pages[$oldestname][$colorby];
466 foreach($this->names as $name)
467 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
468 } // extract_wikipages
471 * Creates the text file description of the graph needed to invoke
474 * @param filename string name of the dot file to be created
475 * @param width float width of the output graph in inches
476 * @param height float height of the graph in inches
477 * @param colorby string color sceme beeing used ('age', 'revtime',
479 * @param shape string node shape; 'ellipse', 'box', 'circle', 'point'
480 * @param label string 'name': label by name,
481 * 'number': label by unique number
482 * @return boolean error status; true=ok; false=error
484 function createDotFile($filename, $argarray) {
486 if (!$fp = fopen($filename, 'w'))
489 $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
492 $names = &$this->names;
493 $pages = &$this->pages;
495 $nametonumber = array_flip($names);
497 $dot = "digraph VisualWiki {\n" // }
498 . (!empty($fontpath) ? " fontpath=\"$fontpath\"\n" : "")
499 . " size=\"$width,$height\";\n ";
503 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
506 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
509 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
512 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
516 foreach ($names as $name) {
518 $url = rawurlencode($name);
519 // patch to allow Page/SubPage
520 $url = preg_replace('/' . urlencode(SUBPAGE_SEPARATOR) . '/',
521 SUBPAGE_SEPARATOR, $url);
522 $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
524 $dot .= " \"$nodename\" [URL=\"$url\"";
525 if ($colorby != 'none') {
526 $col = $pages[$name]['color'];
527 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
528 $col[0], $col[1], $col[2]);
532 if (!empty($pages[$name]['links'])) {
534 if ($label != 'name')
535 foreach($pages[$name]['links'] as $linkname)
536 $linkarray[] = $nametonumber[$linkname] + 1;
538 $linkarray = $pages[$name]['links'];
539 $linkstring = join('"; "', $linkarray );
541 $c = count($pages[$name]['links']);
542 $dot .= " \"$nodename\" -> "
549 if ($colorby != 'none') {
550 $dot .= "\n subgraph cluster_legend {\n"
551 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
552 . " fillcolor=lightgrey;\n"
554 . " fontname=$fontname;\n"
555 . " fontsize=$fontsize;\n"
556 . " label=\"".gettext("Legend")."\";\n";
557 $oldest= ceil($this->oldest / (24 * 3600));
560 for($i = 0; $i < $max; $i++) {
561 $time = floor($i / $max * $oldest);
562 $name = '"' . $time .' '. _("days") .'"';
563 $col = $this->getColor($i/$max);
564 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
565 $name, $fillstring, $col[0], $col[1], $col[2])
569 $dot .= ' '. join(' -> ', $legend)
577 $ok = fwrite($fp, $dot);
578 $ok = fclose($fp) && $ok; // close anyway
584 * Execute system command.
586 * @param cmd string command to be invoked
587 * @return boolean error status; true=ok; false=error
589 function execute($cmd) {
590 exec($cmd, $outarr, $returnval); // normally 127
591 $errstr = join('',$outarr);
593 trigger_error($cmd.": ".$errstr, E_USER_WARNING);
596 return empty($errstr);
600 * Produces a dot file, calls dot twice to obtain an image and a
601 * text description of active areas for hyperlinking and returns
602 * an image and an html map.
604 * @param width float width of the output graph in inches
605 * @param height float height of the graph in inches
606 * @param colorby string color sceme beeing used ('age', 'revtime',
608 * @param shape string node shape; 'ellipse', 'box', 'circle', 'point'
609 * @param label string not used anymore
611 function invokeDot($argarray) {
613 //$cacheparams = $GLOBALS['CacheParams'];
614 $tempfiles = $this->tempnam('VisualWiki');
615 $gif = $argarray['imgtype'];
616 $ImageCreateFromFunc = "ImageCreateFrom$gif";
618 && $this->createDotFile($tempfiles.'.dot',$argarray)
619 && $this->execute("$dotbin -T$gif $tempfiles.dot -o $tempfiles.$gif")
620 && $this->execute("$dotbin -Timap $tempfiles.dot -o $tempfiles.map")
621 && file_exists( "$tempfiles.$gif" )
622 && file_exists( $tempfiles.'.map' )
623 && ($img = $ImageCreateFromFunc( "$tempfiles.$gif" ))
624 && ($fp = fopen($tempfiles.'.map','r'));
629 $line = fgets($fp, 1000);
630 if (substr($line, 0, 1) == '#')
632 list($shape, $url, $e1, $e2, $e3, $e4) = sscanf($line,
633 "%s %s %d,%d %d,%d");
634 if ($shape != 'rect')
637 // dot sometimes gives not allways the right order so
638 // so we have to sort a bit
643 $map->pushContent(HTML::area(array(
645 'coords' => "$x1,$y1,$x2,$y2",
647 'title' => rawurldecode($url),
651 //trigger_error("url=".$url);
654 $tempfiles.$gif: ".(file_exists("$tempfiles.$gif") ? filesize("$tempfiles.$gif"):'missing')."
655 $tempfiles.map: ".(file_exists("$tempfiles.map") ? filesize("$tempfiles.map"):'missing')."
659 // clean up tempfiles
660 if ($ok or !$argarray['debug'])
661 foreach (array('',".$gif",".map",".dot") as $ext) {
662 if (file_exists($tempfiles.$ext))
663 unlink($tempfiles.$ext);
667 return array($img, $map);
669 return array(false, false);
673 * Prepares some rainbow colors for the nodes of the graph
674 * and stores them in an array which may be accessed with
675 * <code>getColor</code>.
677 function createColors() {
678 $predefcolors = array(
679 array('red' => 255, 'green' => 0, 'blue' => 0),
680 array('red' => 255, 'green' => 255, 'blue' => 0),
681 array('red' => 0, 'green' => 255, 'blue' => 0),
682 array('red' => 0, 'green' => 255, 'blue' => 255),
683 array('red' => 0, 'green' => 0, 'blue' => 255),
684 array('red' => 100, 'green' => 100, 'blue' => 100)
688 $numberofcolors = count($predefcolors) * $steps;
691 foreach($predefcolors as $color) {
697 for ($i = 0; $i < $steps; $i++)
698 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
699 floor(interpolate( $oldcolor['red'], $color['red'], $i/$steps )),
700 floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
701 floor(interpolate( $oldcolor['blue'], $color['blue'], $i/$steps ))
705 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
709 * Translates a value from 0.0 to 1.0 into rainbow color.
710 * red -> orange -> green -> blue -> gray
712 * @param promille float value between 0.0 and 1.0
713 * @return array(red,green,blue)
715 function getColor($promille) {
716 foreach( $this->ColorTab as $pro => $col ) {
717 if ($promille*1000 < $pro)
720 $lastcol = end($this->ColorTab);
723 } // WikiPlugin_VisualWiki
726 * Linear interpolates a value between two point a and b
728 * @return float interpolated value
731 function interpolate($a, $b, $pos) {
732 return $a + ($b - $a) * $pos;
735 // $Log: not supported by cvs2svn $
736 // Revision 1.10 2004/06/19 10:06:38 rurban
737 // Moved lib/plugincache-config.php to config/*.ini
738 // use PLUGIN_CACHED_* constants instead of global $CacheParams
740 // Revision 1.9 2004/06/03 09:40:57 rurban
741 // WikiPluginCache improvements
743 // Revision 1.8 2004/01/26 09:18:00 rurban
744 // * changed stored pref representation as before.
745 // the array of objects is 1) bigger and 2)
746 // less portable. If we would import packed pref
747 // objects and the object definition was changed, PHP would fail.
748 // This doesn't happen with an simple array of non-default values.
749 // * use $prefs->retrieve and $prefs->store methods, where retrieve
750 // understands the interim format of array of objects also.
751 // * simplified $prefs->get() and fixed $prefs->set()
752 // * added $user->_userid and class '_WikiUser' portability functions
753 // * fixed $user object ->_level upgrading, mostly using sessions.
754 // this fixes yesterdays problems with loosing authorization level.
755 // * fixed WikiUserNew::checkPass to return the _level
756 // * fixed WikiUserNew::isSignedIn
757 // * added explodePageList to class PageList, support sortby arg
758 // * fixed UserPreferences for WikiUserNew
759 // * fixed WikiPlugin for empty defaults array
760 // * UnfoldSubpages: added pagename arg, renamed pages arg,
761 // removed sort arg, support sortby arg
763 // Revision 1.7 2003/03/03 13:57:31 carstenklapp
764 // Added fontpath (see PhpWiki:VisualWiki), tries to be smart about which OS.
765 // (This plugin still doesn't work for me on OS X, but at least image files
766 // are actually being created now in '/tmp/cache'.)
768 // Revision 1.6 2003/01/18 22:11:45 carstenklapp
770 // Reformatting & tabs to spaces;
771 // Added copyleft, getVersion, getDescription, rcs_id.
778 // c-hanging-comment-ender-p: nil
779 // indent-tabs-mode: nil