]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/VisualWiki.php
New FSF address
[SourceForge/phpwiki.git] / lib / plugin / VisualWiki.php
1 <?php // -*-php-*-
2 // $Id$
3 /*
4  * Copyright (C) 2002 Johannes Große (Johannes Gro&szlig;e)
5  *
6  * This file is part of PhpWiki.
7  *
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.
12  *
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.
17  *
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.
21  */
22
23 /**
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
29  * @version 0.9
30  */
31 /* define('VISUALWIKI_ALLOWOPTIONS', true); */
32 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
33     define('VISUALWIKI_ALLOWOPTIONS', false);
34
35 require_once "lib/plugin/GraphViz.php";
36
37 class WikiPlugin_VisualWiki
38 extends WikiPlugin_GraphViz
39 {
40     /**
41      * Sets plugin type to map production
42      */
43     function getPluginType() {
44         return ($GLOBALS['request']->getArg('debug')) ? PLUGIN_CACHED_IMG_ONDEMAND
45                                                           : PLUGIN_CACHED_MAP;
46     }
47
48     /**
49      * Sets the plugin's name to VisualWiki. It can be called by
50      * <code>&lt;?plugin VisualWiki?&gt;</code>, now. This
51      * name must correspond to the filename and the class name.
52      */
53     function getName() {
54         return "VisualWiki";
55     }
56
57     /**
58      * Sets textual description.
59      */
60     function getDescription() {
61         return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
62     }
63
64     /**
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>
68      */
69     function defaultarguments() {
70         return array('imgtype'        => 'png',
71                      'width'          => false, // was 5, scale it automatically
72                      'height'         => false, // was 7, scale it automatically
73                      'colorby'        => 'age', // sort by 'age' or 'revtime'
74                      'fillnodes'      => 'off',
75                      'label'          => 'name',
76                      'shape'          => 'ellipse',
77                      'large_nb'       => 5,
78                      'recent_nb'      => 5,
79                      'refined_nb'     => 15,
80                      'backlink_nb'    => 5,
81                      'neighbour_list' => '',
82                      'exclude_list'   => '',
83                      'include_list'   => '',
84                      'fontsize'       => 9,
85                      'debug'          => false,
86                      'help'           => false );
87     }
88
89     /**
90      * Sets the default arguments. WikiPlugin also regards these as
91      * the allowed arguments. Since WikiPluginCached stores an image
92      * for each different set of parameters, there can be a lot of
93      * these (large) graphs if you allow different parameters.
94      * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
95      * to allow no options to be set and use only the default parameters.
96      * This will need an disk space of about 20 Kbyte all the time.
97      */
98     function getDefaultArguments() {
99         if (VISUALWIKI_ALLOWOPTIONS)
100             return $this->defaultarguments();
101         else
102             return array();
103     }
104
105     /**
106      * Substitutes each forbidden parameter value by the default value
107      * defined in <code>defaultarguments</code>.
108      */
109     function checkArguments(&$arg) {
110         extract($arg);
111         $def = $this->defaultarguments();
112         if (($width < 3) || ($width > 15))
113             $arg['width'] = $def['width'];
114         if (($height < 3) || ($height > 20))
115             $arg['height'] = $def['height'];
116         if (($fontsize < 8) || ($fontsize > 24))
117             $arg['fontsize'] = $def['fontsize'];
118         if (!in_array($label, array('name', 'number')))
119             $arg['label'] = $def['label'];
120
121         if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
122                                     'plaintext')))
123             $arg['shape'] = $def['shape'];
124         if (!in_array($colorby, array('age', 'revtime')))
125             $arg['colorby'] = $def['colorby'];
126         if (!in_array($fillnodes, array('on', 'off')))
127             $arg['fillnodes'] = $def['fillnodes'];
128         if (($large_nb < 0) || ($large_nb > 50))
129             $arg['large_nb'] = $def['large_nb'];
130         if (($recent_nb < 0)  || ($recent_nb > 50))
131             $arg['recent_nb'] = $def['recent_nb'];
132         if (($refined_nb < 0 ) || ( $refined_nb > 50))
133             $arg['refined_nb'] = $def['refined_nb'];
134         if (($backlink_nb < 0) || ($backlink_nb > 50))
135             $arg['backlink_nb'] = $def['backlink_nb'];
136         // ToDo: check if "ImageCreateFrom$imgtype"() exists.
137         if (!in_array($imgtype, $GLOBALS['PLUGIN_CACHED_IMGTYPES']))
138             $arg['imgtype'] = $def['imgtype'];
139         if (empty($fontname))
140             $arg['fontname'] = VISUALWIKIFONT;
141     }
142
143     /**
144      * Checks options, creates help page if necessary, calls both
145      * database access and image map production functions.
146      * @return array($map,$html)
147      */
148     function getMap($dbi, $argarray, $request) {
149         if (!VISUALWIKI_ALLOWOPTIONS)
150             $argarray = $this->defaultarguments();
151         $this->checkArguments($argarray);
152         $request->setArg('debug',$argarray['debug']);
153         //extract($argarray);
154         if ($argarray['help'])
155             return array($this->helpImage(), ' '); // FIXME
156         $this->createColors();
157         $this->extract_wikipages($dbi, $argarray);
158         /* ($dbi,  $large, $recent, $refined, $backlink,
159             $neighbour, $excludelist, $includelist, $color); */
160             $result = $this->invokeDot($argarray);
161         if (isa($result, 'HtmlElement'))
162             return array(false, $result);
163         else
164             return $result;
165         /* => ($width, $height, $color, $shape, $text); */
166     }
167
168     // ------------------------------------------------------------------------------------------
169
170     /**
171      * Returns an image containing a usage description of the plugin.
172      * @return string image handle
173      */
174     function helpImage() {
175         $def = $this->defaultarguments();
176         $other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES'];
177         unset ($other_imgtypes[$def['imgtype']]);
178         $helparr = array(
179             '<<'.$this->getName() .
180             ' img'             => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['PLUGIN_CACHED_IMGTYPES']).'"',
181             'width'            => ' = "width in inches"',
182             'height'           => ' = "height in inches"',
183             'fontname'         => ' = "font family"',
184             'fontsize'         => ' = "fontsize in points"',
185             'colorby'          => ' = "age|revtime|none"',
186             'fillnodes'        => ' = "on|off"',
187             'shape'            => ' = "ellipse(default)|box|circle|point"',
188             'label'            => ' = "name|number"',
189             'large_nb'         => ' = "number of largest pages to be selected"',
190             'recent_nb'        => ' = "number of youngest pages"',
191             'refined_nb'       => ' = "#pages with smallest time between revisions"',
192             'backlink_nb'      => ' = "number of pages with most backlinks"',
193             'neighbour_list'   => ' = "find pages linked from and to these pages"',
194             'exclude_list'     => ' = "colon separated list of pages to be excluded"',
195             'include_list'     => ' = "colon separated list"     >>'
196             );
197         $length = 0;
198         foreach($helparr as $alignright => $alignleft) {
199             $length = max($length, strlen($alignright));
200         }
201         $helptext ='';
202         foreach($helparr as $alignright => $alignleft) {
203             $helptext .= substr('                                                        '
204                                 . $alignright, -$length).$alignleft."\n";
205         }
206         return $this->text2img($helptext, 4, array(1, 0, 0),
207                                array(255, 255, 255));
208     }
209
210
211     /**
212      * Selects the first (smallest or biggest) WikiPages in
213      * a given category.
214      *
215      * @param  number   integer  number of page names to be found
216      * @param  category string   attribute of the pages which is used
217      *                           to compare them
218      * @param  minimum  boolean  true finds smallest, false finds biggest
219      * @return array             list of page names found to be the best
220      */
221     function findbest($number, $category, $minimum ) {
222         // select the $number best in the category '$category'
223         $pages = &$this->pages;
224         $names = &$this->names;
225
226         $selected = array();
227         $i = 0;
228         foreach($names as $name) {
229             if ($i++>=$number)
230                 break;
231             $selected[$name] = $pages[$name][$category];
232         }
233         //echo "<pre>$category "; var_dump($selected); "</pre>";
234         $compareto = $minimum ? 0x79999999 : -0x79999999;
235
236         $i = 0;
237         foreach ($names as $name) {
238             if ($i++<$number)
239                 continue;
240             if ($minimum) {
241                 if (($crit = $pages[$name][$category]) < $compareto) {
242                     $selected[$name] = $crit;
243                     asort($selected, SORT_NUMERIC);
244                     array_pop($selected);
245                     $compareto = end($selected);
246                 }
247             } elseif (($crit = $pages[$name][$category]) > $compareto)  {
248                 $selected[$name] = $crit;
249                 arsort($selected, SORT_NUMERIC);
250                 array_pop($selected);
251                 $compareto = end($selected);
252             }
253         }
254         //echo "<pre>$category "; var_dump($selected); "</pre>";
255
256         return array_keys($selected);
257     }
258
259
260     /**
261     * Extracts a subset of all pages from the wiki and find their
262     * connections to other pages. Also collects some page features
263     * like size, age, revision number which are used to find the
264     * most attractive pages.
265     *
266     * @param  dbi         WikiDB   database handle to access all Wiki pages
267     * @param  LARGE       integer  number of largest pages which should
268     *                              be included
269     * @param  RECENT      integer  number of the youngest pages to be included
270     * @param  REFINED     integer  number of the pages with shortes revision
271     *                              interval
272     * @param  BACKLINK    integer  number of the pages with most backlinks
273     * @param  EXCLUDELIST string   colon ':' separated list of page names which
274     *                              should not be displayed (like PhpWiki, for
275     *                              example)
276     * @param  INCLUDELIST string   colon separated list of pages which are
277     *                              always included (for example your own
278     *                              page :)
279     * @param  COLOR       string   'age', 'revtime' or 'none'; Selects which
280     *                              page feature is used to determine the
281     *                              filling color of the nodes in the graph.
282     * @return void
283     */
284     function extract_wikipages($dbi, $argarray) {
285         // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
286         // $EXCLUDELIST, $INCLUDELIST,$COLOR
287         $now = time();
288
289         extract($argarray);
290         // FIXME: gettextify?
291         $exclude_list   = $exclude_list ? explode(':', $exclude_list) : array();
292         $include_list   = $include_list ? explode(':', $include_list) : array();
293         $neighbour_list = $neighbour_list ? explode(':', $neighbour_list) : array();
294
295         // remove INCLUDED from EXCLUDED, includes override excludes.
296         if ($exclude_list and $include_list) {
297                 $diff = array_diff($exclude_list, $include_list);
298                 if ($diff)
299                     $exclude_list = $diff;
300         }
301
302         // collect all pages
303         $allpages = $dbi->getAllPages(false, false, false, $exclude_list);
304         $pages = &$this->pages;
305         $countpages = 0;
306         while ($page = $allpages->next()) {
307             $name = $page->getName();
308
309             // skip excluded pages
310             if (in_array($name, $exclude_list)) {
311                     $page->free();
312                 continue;
313             }
314
315             // false = get links from actual page
316             // true  = get links to actual page ("backlinks")
317             $backlinks = $page->getLinks(true);
318             unset($bconnection);
319             $bconnection = array();
320             while ($blink = $backlinks->next()) {
321                 array_push($bconnection, $blink->getName());
322             }
323             $backlinks->free();
324             unset($backlinks);
325
326             // include all neighbours of pages listed in $NEIGHBOUR
327             if (in_array($name, $neighbour_list)) {
328                 $ln = $page->getLinks(false);
329                 $con = array();
330                 while ($link = $ln->next()) {
331                     array_push($con, $link->getName());
332                 }
333                 $include_list = array_merge($include_list, $bconnection, $con);
334                 $ln->free();
335                 unset($l);
336                 unset($con);
337             }
338
339             unset($rev);
340             $rev = $page->getCurrentRevision();
341
342             $pages[$name] = array(
343                 'age'         => $now - $rev->get('mtime'),
344                 'revnr'       => $rev->getVersion(),
345                 'links'       => array(),
346                 'backlink_nb' => count($bconnection),
347                 'backlinks'   => $bconnection,
348                 'size'        => 1000 // FIXME
349                 );
350             $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
351
352             unset($page);
353         }
354         $allpages->free();
355         unset($allpages);
356         $this->names = array_keys($pages);
357
358         $countpages = count($pages);
359
360         // now select each page matching to given parameters
361         $all_selected = array_unique(array_merge(
362             $this->findbest($recent_nb,   'age',         true),
363             $this->findbest($refined_nb,  'revtime',     true),
364             $x = $this->findbest($backlink_nb, 'backlink_nb', false),
365 //          $this->findbest($large_nb,    'size',        false),
366             $include_list));
367
368         foreach($all_selected as $name)
369             if (isset($pages[$name]))
370                 $newpages[$name] = $pages[$name];
371         unset($this->names);
372         unset($this->pages);
373         $this->pages = $newpages;
374         $pages = &$this->pages;
375         $this->names = array_keys($pages);
376         unset($newpages);
377         unset($all_selected);
378
379         $countpages = count($pages);
380
381         // remove dead links and collect links
382         reset($pages);
383         while( list($name, $page) = each($pages) ) {
384             if (is_array($page['backlinks'])) {
385                 reset($page['backlinks']);
386                 while ( list($index, $link) = each( $page['backlinks'] ) ) {
387                     if ( !isset($pages[$link]) || $link == $name ) {
388                         unset($pages[$name]['backlinks'][$index]);
389                     } else {
390                         array_push($pages[$link]['links'],$name);
391                         //array_push($this->everylink, array($link,$name));
392                     }
393                 }
394             }
395         }
396
397         if ($colorby == 'none')
398             return;
399         list($oldestname) = $this->findbest(1, $colorby, false);
400         $this->oldest = $pages[$oldestname][$colorby];
401         foreach($this->names as $name)
402             $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
403     }
404
405     /**
406      * Creates the text file description of the graph needed to invoke
407      * <code>dot</code>.
408      *
409      * @param filename  string  name of the dot file to be created
410      * @param width     float   width of the output graph in inches
411      * @param height    float   height of the graph in inches
412      * @param colorby   string  color sceme beeing used ('age', 'revtime',
413      *                                                   'none')
414      * @param shape     string  node shape; 'ellipse', 'box', 'circle', 'point'
415      * @param label     string  'name': label by name,
416      *                          'number': label by unique number
417      * @return boolean          error status; true=ok; false=error
418      */
419     function createDotFile($filename, $argarray) {
420         extract($argarray);
421         if (!$fp = fopen($filename, 'w'))
422             return false;
423
424         $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
425
426         $ok = true;
427         $names = &$this->names;
428         $pages = &$this->pages;
429         if ($names)
430             $nametonumber = array_flip($names);
431
432         $dot = "digraph VisualWiki {\n" // }
433             . (!empty($fontpath) ? "    fontpath=\"$fontpath\"\n" : "");
434         if ($width and $height)
435             $dot .= "    size=\"$width,$height\";\n    ";
436
437
438         switch ($shape) {
439         case 'point':
440             $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
441             break;
442         case 'box':
443             $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
444             break;
445         case 'circle':
446             $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
447             break;
448         default :
449             $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
450         }
451         $dot .= "\n";
452         $i = 0;
453         foreach ($names as $name) {
454
455             $url = rawurlencode($name);
456             // patch to allow Page/SubPage
457             $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, $url);
458             $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
459
460             $dot .= "    \"$nodename\" [URL=\"$url\"";
461             if ($colorby != 'none') {
462                 $col = $pages[$name]['color'];
463                 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
464                                 $col[0], $col[1], $col[2]);
465             }
466             $dot .= "];\n";
467
468             if (!empty($pages[$name]['links'])) {
469                 unset($linkarray);
470                 if ($label != 'name')
471                     foreach($pages[$name]['links'] as $linkname)
472                         $linkarray[] = $nametonumber[$linkname] + 1;
473                 else
474                     $linkarray = $pages[$name]['links'];
475                 $linkstring = join('"; "', $linkarray );
476
477                 $c = count($pages[$name]['links']);
478                 $dot .= "        \"$nodename\" -> "
479                      . ($c>1?'{':'')
480                      . "\"$linkstring\";"
481                      . ($c>1?'}':'')
482                      . "\n";
483             }
484         }
485         if ($colorby != 'none') {
486             $dot .= "\n    subgraph cluster_legend {\n"
487                  . "         node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
488                  . "         fillcolor=lightgrey;\n"
489                  . "         style=filled;\n"
490                  . "         fontname=$fontname;\n"
491                  . "         fontsize=$fontsize;\n"
492                  . "         label=\"".gettext("Legend")."\";\n";
493             $oldest= ceil($this->oldest / (24 * 3600));
494             $max = 5;
495             $legend = array();
496             for($i = 0; $i < $max; $i++) {
497                 $time = floor($i / $max * $oldest);
498                 $name = '"' . $time .' '. _("days") .'"';
499                 $col = $this->getColor($i/$max);
500                 $dot .= sprintf('       %s [%scolor="#%02X%02X%02X"];',
501                                 $name, $fillstring, $col[0], $col[1], $col[2])
502                     . "\n";
503                 $legend[] = $name;
504             }
505             $dot .= '        '. join(' -> ', $legend)
506                 . ";\n    }\n";
507         }
508
509         // {
510         $dot .= "}\n";
511         $this->source = $dot;
512         // write a temp file
513         $ok = fwrite($fp, $dot);
514         $ok = fclose($fp) && $ok;  // close anyway
515
516         return $ok;
517     }
518
519
520     /**
521      * static workaround on broken Cache or broken dot executable,
522      * called only if debug=static.
523      *
524      * @access private
525      * @param  url      string  url pointing to the image part of the map
526      * @param  map      string  &lt;area&gt; tags defining active
527      *                          regions in the map
528      * @param  dbi      WikiDB  database abstraction class
529      * @param  argarray array   complete (!) arguments to produce
530      *                          image. It is not necessary to call
531      *                          WikiPlugin->getArgs anymore.
532      * @param  request  Request ???
533      * @return          string  html output
534      */
535     function embedImg($url,&$dbi,$argarray,&$request) {
536         if (!VISUALWIKI_ALLOWOPTIONS)
537             $argarray = $this->defaultarguments();
538         $this->checkArguments($argarray);
539         //extract($argarray);
540         if ($argarray['help'])
541             return array($this->helpImage(), ' '); // FIXME
542         $this->createColors();
543         $this->extract_wikipages($dbi, $argarray);
544         list($imagehandle, $content['html']) = $this->invokeDot($argarray);
545         // write to uploads and produce static url
546         $file_dir = getUploadFilePath();
547         $upload_dir = getUploadDataPath();
548         $tmpfile = tempnam($file_dir,"VisualWiki").".".$argarray['imgtype'];
549         WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile);
550         ImageDestroy($imagehandle);
551         return WikiPluginCached::embedMap(1,$upload_dir.basename($tmpfile),$content['html'],
552                                           $dbi,$argarray,$request);
553     }
554
555     /**
556      * Prepares some rainbow colors for the nodes of the graph
557      * and stores them in an array which may be accessed with
558      * <code>getColor</code>.
559      */
560     function createColors() {
561         $predefcolors = array(
562              array('red' => 255, 'green' =>   0, 'blue' =>   0),
563              array('red' => 255, 'green' => 255, 'blue' =>   0),
564              array('red' =>   0, 'green' => 255, 'blue' =>   0),
565              array('red' =>   0, 'green' => 255, 'blue' => 255),
566              array('red' =>   0, 'green' =>   0, 'blue' => 255),
567              array('red' => 100, 'green' => 100, 'blue' => 100)
568              );
569
570         $steps = 2;
571         $numberofcolors = count($predefcolors) * $steps;
572
573         $promille = -1;
574         foreach($predefcolors as $color) {
575             if ($promille < 0) {
576                 $oldcolor = $color;
577                 $promille = 0;
578                 continue;
579             }
580             for ($i = 0; $i < $steps; $i++)
581                 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
582                     floor(interpolate( $oldcolor['red'],   $color['red'],   $i/$steps )),
583                     floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
584                     floor(interpolate( $oldcolor['blue'],  $color['blue'],  $i/$steps ))
585                 );
586             $oldcolor = $color;
587         }
588 //echo"<pre>";  var_dump($this->ColorTab); echo "</pre>";
589     }
590
591     /**
592      * Translates a value from 0.0 to 1.0 into rainbow color.
593      * red -&gt; orange -&gt; green -&gt; blue -&gt; gray
594      *
595      * @param promille float value between 0.0 and 1.0
596      * @return array(red,green,blue)
597      */
598     function getColor($promille) {
599         foreach( $this->ColorTab as $pro => $col ) {
600             if ($promille*1000 < $pro)
601                 return $col;
602         }
603         $lastcol = end($this->ColorTab);
604         return $lastcol;
605     }
606 }
607
608 /**
609  * Linear interpolates a value between two point a and b
610  * at a value pos.
611  * @return float  interpolated value
612  */
613 function interpolate($a, $b, $pos) {
614     return $a + ($b - $a) * $pos;
615 }
616
617 // Local Variables:
618 // mode: php
619 // tab-width: 8
620 // c-basic-offset: 4
621 // c-hanging-comment-ender-p: nil
622 // indent-tabs-mode: nil
623 // End:
624 ?>