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