1 <?php rcs_id('$Id: VisualWiki.php,v 1.2 2002-08-18 13:14:10 rurban Exp $');
3 Copyright (C) 2002 Johannes Große (Johannes Große)
5 This file is (not yet) part of PhpWiki.
7 PhpWiki is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 PhpWiki is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with PhpWiki; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * Produces graphical site map of PhpWiki
24 * Example for an image map creating plugin. It produces a graphical
25 * sitemap of PhpWiki by calling the <code>dot</code> commandline tool
26 * from graphviz (http://www.graphviz.org).
27 * @author Johannes Große
30 define('VISUALWIKI_ALLOWOPTIONS',true);
31 // Name of the Truetypefont - Helvetica is probably easier to read
32 //define('VISUALWIKIFONT','Helvetica');
33 //define('VISUALWIKIFONT','Times');
34 define('VISUALWIKIFONT','Arial');
35 $dotbin = '/usr/local/bin/dot';
37 if (!defined('VISUALWIKI_ALLOWOPTIONS')) define('VISUALWIKI_ALLOWOPTIONS',false);
39 require_once "lib/WikiPluginCached.php";
41 class WikiPlugin_VisualWiki extends WikiPluginCached {
42 // ToDo: check if "ImageCreateFrom$imgtype"() exists.
45 * Sets plugin type to map production
47 function getPluginType() {
48 return PLUGIN_CACHED_MAP;
52 * Sets the plugin's name to VisualWiki. It can be called by
53 * <code><?plugin VisualWiki?></code>, now. This
54 * name must correspond to the filename and the class name.
61 * Sets textual description.
63 function getDescription() {
64 return 'Visualizes the Wiki structure in a graph.';
68 * Returns default arguments. This is put into a separate
69 * function to allow its usage by both <code>getDefaultArguments</code>
70 * and <code>checkArguments</code>
72 function defaultarguments() {
73 return array('imgtype' => 'png',
84 'neighbour_list' => '',
92 * Sets the default arguments. WikiPlugin also regards these as
93 * the allowed arguments. Since WikiPluginCached stores an image
94 * for each different set of parameters, there can be a lot of
95 * these (large) graphs if you allow different parameters.
96 * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
97 * to allow no options to be set and use only the default paramters.
98 * This will need an disk space of about 20 Kbyte all the time.
100 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) {
113 $def = $this->defaultarguments();
114 if (($width<3) ||($width>15)) $arg['width'] = $def['width'];
115 if (($height<3) ||($height>20)) $arg['height'] = $def['height'];
116 if (($fontsize<8) ||($fontsize>24)) $arg['fontsize'] = $def['fontsize'];
117 if (!in_array($label,array('name','number')))
118 $arg['label'] = $def['label'];
119 if (!in_array($shape,array('ellipse','box','point','circle','plaintext')))
120 $arg['shape'] = $def['shape'];
121 if (!in_array($colorby,array('age','revtime')))
122 $arg['colorby'] = $def['colorby'];
123 if (!in_array($fillnodes,array('on','off')))
124 $arg['fillnodes'] = $def['fillnodes'];
125 if (($large_nb<0) ||($large_nb>50)) $arg['large_nb'] = $def['large_nb'];
126 if (($recent_nb<0) ||($recent_nb>50)) $arg['recent_nb'] = $def['recent_nb'];
127 if (($refined_nb<0) ||($refined_nb>50)) $arg['refined_nb'] = $def['refined_nb'];
128 if (($backlink_nb<0)||($backlink_nb>50)) $arg['backlink_nb'] = $def['backlink_nb'];
129 if (!in_array($imgtype,$GLOBALS['CacheParams']['imgtypes']))
130 $arg['imgtype'] = $def['imgtype'];
131 if (empty($fontname)) $arg['fontname'] = VISUALWIKIFONT;
135 * Checks options, creates help page if necessary, calls both
136 * database access and image map production functions.
137 * @return array($map,$html)
139 function getMap($dbi, $argarray, $request) {
140 if (!VISUALWIKI_ALLOWOPTIONS)
141 $argarray = $this->defaultarguments();
142 $this->checkArguments($argarray);
143 //extract($argarray);
144 if ($argarray['help'])
145 return array($this->helpImage(), ' '); // FIXME
146 $this->createColors();
147 $this->extract_wikipages($dbi, $argarray);
148 /* ($dbi, $large, $recent, $refined, $backlink,
149 $neighbour, $excludelist, $includelist,$color );*/
150 return $this->invokeDot($argarray);
151 /*($width,$height,$color,$shape,$text);*/
155 * Sets the expire time to one day (so the image producing
156 * functions are called seldomly) or to about two minutes
157 * if a help screen is created.
159 function getExpire($dbi, $argarray, $request) {
160 if ($argarray['help'])
161 return '+120'; // 2 minutes
162 return sprintf('+%d',3*86000); // approx 3 days
166 * Sets the imagetype according to user wishes and
167 * relies on WikiPluginCached to catch illegal image
169 * (I feel unsure whether this option is reasonable in
170 * this case, because png will definitely have the
173 * @return string 'png', 'gif', 'jpeg'
175 function getImageType($dbi, $argarray, $request) {
176 return $argarray['imgtype'];
180 * This gives an alternative text description of
181 * the image map. I do not know whether it interferes
182 * with the <code>title</code> attributes in <area>
183 * tags of the image map. Perhaps this will be removed.
186 function getAlt($dbi, $argstr, $request) {
187 return $this->getDescription();
190 // ------------------------------------------------------------------------------------------
193 * Returns an image containing a usage description of the plugin.
194 * @return string image handle
196 function helpImage() {
197 $def = $this->defaultarguments();
198 $other_imgtypes = $GLOBALS['CacheParams']['imgtypes'];
199 unset ($other_imgtypes[$def['imgtype']]);
201 '<?plugin '.$this->getName() .
202 ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['CacheParams']['imgtypes']).'"',
203 'width' => ' = "width in inches"',
204 'height' => ' = "height in inches"',
205 'fontname' => ' = "font family"',
206 'fontsize' => ' = "fontsize in points"',
207 'colorby' => ' = "age|revtime|none"',
208 'fillnodes' => ' = "on|off"',
209 'shape' => ' = "ellipse(default)|box|circle|point"',
210 'label' => ' = "name|number"',
211 'large_nb' => ' = "number of largest pages to be selected"',
212 'recent_nb' => ' = "number of youngest pages"',
213 'refined_nb' => ' = "#pages with smallest time between revisions"',
214 'backlink_nb' => ' = "number of pages with most backlinks"',
215 'neighbour_list' => ' = "find pages linked from and to these pages"',
216 'exclude_list' => ' = "colon separated list of pages to be excluded"',
217 'include_list' => ' = "colon separated list" ?>'
220 foreach($helparr as $alignright => $alignleft) {
221 $length = max($length, strlen($alignright));
224 foreach($helparr as $alignright => $alignleft) {
225 $helptext .= substr(' '
226 . $alignright, -$length).$alignleft."\n";
228 return $this->text2img($helptext,4,array(1,0,0), array(255,255,255));
233 * Selects the first (smallest or biggest) WikiPages in
236 * @param number integer number of page names to be found
237 * @param category string attribute of the pages which is used
239 * @param minimum boolean true finds smallest, false finds biggest
240 * @return array list of page names found to be the best
242 function findbest($number, $category, $minimum ) {
243 // select the $number best in the category '$category'
244 $pages = &$this->pages;
245 $names = &$this->names;
249 foreach($names as $name) {
250 if ($i++>=$number) break;
251 $selected[$name] = $pages[$name][$category];
253 //echo "<pre>$category "; var_dump($selected); "</pre>";
254 $compareto = $minimum ? 0x79999999 : -0x79999999;
257 foreach ($names as $name) {
258 if ($i++<$number) continue;
260 if (($crit = $pages[$name][$category]) < $compareto) {
261 $selected[$name] = $crit;
262 asort($selected,SORT_NUMERIC);
263 array_pop($selected);
264 $compareto = end($selected);
266 } elseif (($crit = $pages[$name][$category]) > $compareto) {
267 $selected[$name] = $crit;
268 arsort($selected,SORT_NUMERIC);
269 array_pop($selected);
270 $compareto = end($selected);
273 //echo "<pre>$category "; var_dump($selected); "</pre>";
275 return array_keys($selected);
280 * Extracts a subset of all pages from the wiki and find their
281 * connections to other pages. Also collects some page features
282 * like size, age, revision number which are used to find the
283 * most attractive pages.
285 * @param dbi WikiDB database handle to access all Wiki pages
286 * @param LARGE integer number of largest pages which should
288 * @param RECENT integer number of the youngest pages to be included
289 * @param REFINED integer number of the pages with shortes revision interval
290 * @param BACKLINK integer number of the pages with most backlinks
291 * @param EXCLUDELIST string colon ':' separated list of page names which
292 * should not be displayed (like PhpWiki, for example)
293 * @param INCLUDELIST string colon separated list of pages which are allways
294 * included (for example your own page :)
295 * @param COLOR string 'age', 'revtime' or 'none'; Selects which page
296 * feature is used to determine the filling color of
297 * the nodes in the graph.
300 function extract_wikipages($dbi, $argarray) {
301 // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR, $EXCLUDELIST, $INCLUDELIST,$COLOR
305 // FIXME: gettextify?
306 $exclude_list = explode(':',$exclude_list);
307 $include_list = explode(':',$include_list);
308 $neighbour_list = explode(':',$neighbour_list);
310 // FIXME remove INCLUDED from EXCLUDED
313 $allpages = $dbi->getAllPages();
314 $pages = &$this->pages;
316 while ($page = $allpages->next()) {
317 $name = $page->getName();
319 // skip exluded pages
320 if (in_array($name,$exclude_list)) continue;
322 // false = get links from actual page
323 // true = get links to actual page ("backlinks")
324 $backlinks = $page->getLinks(true);
326 $bconnection = array();
327 while ($blink = $backlinks->next()) {
328 array_push($bconnection, $blink->getName());
332 // include all neighbours of pages listed in $NEIGHBOUR
333 if (in_array($name,$neighbour_list)) {
334 $l = $page->getLinks(false);
336 while ($link = $l->next()) {
337 array_push($con, $link->getName());
339 $include_list = array_merge($include_list,$bconnection,$con);
345 $currev = $page->getCurrentRevision();
347 $pages[$name] = array(
348 'age' => $now-$currev->get('mtime'),
349 'revnr' => $currev->getVersion(),
351 'backlink_nb' => count($bconnection),
352 'backlinks' => $bconnection,
353 'size' => 1000 // FIXME
355 $pages[$name]['revtime'] = $pages[$name]['age']/($pages[$name]['revnr']);
360 $this->names = array_keys($pages);
362 $countpages = count($pages);
364 // now select each page matching to given parameters
365 $all_selected = array_unique(array_merge(
366 $this->findbest($recent_nb, 'age', true),
367 $this->findbest($refined_nb, 'revtime', true),
368 $x=$this->findbest($backlink_nb, 'backlink_nb', false),
369 // $this->findbest($large_nb, 'size', false),
372 foreach($all_selected as $name)
373 if (isset($pages[$name]))
374 $newpages[$name] = $pages[$name];
377 $this->pages = $newpages;
378 $pages = &$this->pages;
379 $this->names = array_keys($pages);
381 unset($all_selected);
383 $countpages = count($pages);
385 // remove dead links and collect links
387 while( list($name,$page) = each($pages) ) {
388 if (is_array($page['backlinks'])) {
389 reset($page['backlinks']);
390 while ( list($index, $link) = each( $page['backlinks'] ) ) {
391 if ( !isset($pages[$link]) || $link == $name ) {
392 unset($pages[$name]['backlinks'][$index]);
394 array_push($pages[$link]['links'],$name);
395 //array_push($this->everylink, array($link,$name));
401 if ($colorby=='none') return;
402 list($oldestname) = $this->findbest(1, $colorby, false);
403 $this->oldest = $pages[$oldestname][$colorby];
404 foreach($this->names as $name)
405 $pages[$name]['color'] = $this->getColor($pages[$name][$colorby]/$this->oldest);
406 } // extract_wikipages
409 * Creates the text file description of the graph needed to invoke
412 * @param filename string name of the dot file to be created
413 * @param width float width of the output graph in inches
414 * @param height float height of the graph in inches
415 * @param colorby string color sceme beeing used ('age','revtime','none')
416 * @param shape string node shape; 'ellipse','box','circle','point'
417 * @param label string 'name': label by name, 'number': label by unique number
418 * @return boolean error status; true=ok; false=error
420 function createDotFile($filename,$argarray) {
422 if (!$fp=fopen($filename, 'w'))
425 $fillstring = ($fillnodes=='on')?'style=filled,':'';
428 $names = &$this->names;
429 $pages = &$this->pages;
431 $nametonumber = array_flip($names);
433 $dot = "digraph VisualWiki {\n" // }
434 . " size=\"$width,$height\";\n ";
438 $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
441 $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
444 $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
447 $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
451 foreach ($names as $name) {
453 $url = rawurlencode($name);
454 // patch to allow page/subpage as with the Calender plugin
455 $url = preg_replace('/%2F/','/',$url);
456 $nodename = ($label!='name'?$nametonumber[$name]+1:$name);
458 $dot .= " \"$nodename\" [URL=\"$url\"";
459 if ($colorby != 'none') {
460 $col = $pages[$name]['color'];
461 $dot .= sprintf(',%scolor="#%02X%02X%02X"',$fillstring, $col[0],$col[1],$col[2]);
465 if (!empty($pages[$name]['links'])) {
468 foreach($pages[$name]['links'] as $linkname)
469 $linkarray[] = $nametonumber[$linkname]+1;
471 $linkarray = $pages[$name]['links'];
472 $linkstring = join('"; "', $linkarray );
474 $c = count($pages[$name]['links']);
475 $dot .= " \"$nodename\" -> "
482 if ($colorby!='none') {
483 $dot .= "\n subgraph cluster_legend {\n"
484 . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
485 . " fillcolor=lightgrey;\n"
487 . " fontname=$fontname;\n"
488 . " fontsize=$fontsize;\n"
489 . " label=\"".gettext("Legend")."\";\n";
490 $oldest= ceil($this->oldest/(24*3600));
493 for($i=0;$i<$max;$i++) {
494 $time = floor($i/$max*$oldest);
495 $name = '"'.$time.' '.gettext('days').'"';
496 $col = $this->getColor($i/$max);
497 $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];',
498 $name, $fillstring,$col[0],$col[1],$col[2]) . "\n";
501 $dot .= ' '. join(' -> ', $legend)
509 $ok = fwrite($fp, $dot);
510 $ok = fclose($fp) && $ok; // close anyway
516 * Execute system command.
518 * @param cmd string command to be invoked
519 * @return boolean error status; true=ok; false=error
521 function execute($cmd) {
522 exec($cmd, $errortxt, $returnval);
523 return ($returnval == 0);
527 * Produces a dot file, calls dot twice to obtain an image and a
528 * text description of active areas for hyperlinking and returns
529 * an image and an html map.
531 * @param width float width of the output graph in inches
532 * @param height float height of the graph in inches
533 * @param colorby string color sceme beeing used ('age','revtime','none')
534 * @param shape string node shape; 'ellipse','box','circle','point'
535 * @param label string not used anymore
537 function invokeDot($argarray) {
538 $cacheparams = $GLOBALS['CacheParams'];
539 $tempfiles = tempnam($cacheparams['cache_dir'],'VisualWiki');
540 $gif = $argarray['imgtype'];
541 $ImageCreateFromFunc = "ImageCreateFrom$gif";
543 && $this->createDotFile($tempfiles.'.dot',$argarray)
544 && $this->execute("$dotbin -T$gif $tempfiles.dot -o $tempfiles.$gif")
545 && $this->execute("$dotbin -Timap $tempfiles.dot -o $tempfiles.map")
546 && file_exists( "$tempfiles.$gif" )
547 && file_exists( $tempfiles.'.map' )
548 && ($img = $ImageCreateFromFunc( "$tempfiles.$gif" ))
549 && ($fp = fopen($tempfiles.'.map','r'));
554 $line = fgets($fp,1000);
555 if (substr($line,0,1)=='#') continue;
556 list($shape,$url,$e1,$e2,$e3,$e4) = sscanf($line,"%s %s %d,%d %d,%d");
558 if ($shape!='rect') continue;
560 // dot sometimes gives not allways the right order so
561 // so we have to sort a bit
566 $map->pushContent(HTML::area( array(
568 'coords' => "$x1,$y1,$x2,$y2",
570 'title' => rawurldecode($url) )));
575 // clean up tempfiles
576 if ($ok and isset($_GET['debug']) and $tempfiles) {
578 unlink("$tempfiles.$gif");
579 unlink($tempfiles.'.map');
580 unlink($tempfiles.'.dot');
584 return array($img,$map);
586 return array(false,false);
590 * Prepares some rainbow colors for the nodes of the graph
591 * and stores them in an array which may be accessed with
592 * <code>getColor</code>.
594 function createColors() {
595 $predefcolors = array(
596 array('red' => 255, 'green' => 0, 'blue' => 0),
597 array('red' => 255, 'green' => 255, 'blue' => 0),
598 array('red' => 0, 'green' => 255, 'blue' => 0),
599 array('red' => 0, 'green' => 255, 'blue' => 255),
600 array('red' => 0, 'green' => 0, 'blue' => 255),
601 array('red' => 100, 'green' => 100, 'blue' => 100)
605 $numberofcolors = count($predefcolors)*$steps;
608 foreach($predefcolors as $color) {
609 if ($promille < 0) { $oldcolor = $color; $promille=0; continue; }
610 for ($i=0; $i<$steps; $i++)
611 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
612 floor(interpolate( $oldcolor['red'], $color['red'], $i/$steps )),
613 floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
614 floor(interpolate( $oldcolor['blue'], $color['blue'], $i/$steps ))
618 //echo"<pre>"; var_dump($this->ColorTab); echo "</pre>";
622 * Translates a value from 0.0 to 1.0 into rainbow color.
623 * red -> orange -> green -> blue -> gray
625 * @param promille float value between 0.0 and 1.0
626 * @return array(red,green,blue)
628 function getColor($promille) {
629 foreach( $this->ColorTab as $pro => $col ) {
630 if ($promille*1000 < $pro)
633 $lastcol = end($this->ColorTab);
636 } // WikiPlugin_VisualWiki
639 * Linear interpolates a value between two point a and b
641 * @return float interpolated value
644 function interpolate($a, $b, $pos) {
645 return $a + ($b-$a)*$pos;