]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/VisualWiki.php
WikiPluginCache improvements
[SourceForge/phpwiki.git] / lib / plugin / VisualWiki.php
1 <?php // -*-php-*-
2 rcs_id('$Id: VisualWiki.php,v 1.9 2004-06-03 09:40:57 rurban Exp $');
3 /*
4  Copyright (C) 2002 Johannes Große (Johannes Gro&szlig;e)
5
6  This file is (not yet) 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
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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.8
30  */
31 define('VISUALWIKI_ALLOWOPTIONS', true);
32 global $dotbin;
33 if (PHP_OS == "Darwin") { // Mac OS X
34     $dotbin = '/sw/bin/dot'; // graphviz via Fink
35     //$dotbin = '/usr/local/bin/dot';
36
37     // Name of the Truetypefont - at least LucidaSansRegular.ttf is always present on OS X
38     define('VISUALWIKIFONT', 'LucidaSansRegular');
39
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/";
43 }
44 elseif (isWindows()) {
45   $dotbin = 'dot';
46   define('VISUALWIKIFONT', 'Arial');
47 } else { // other os
48     $dotbin = '/usr/local/bin/dot';
49
50     // Name of the Truetypefont - Helvetica is probably easier to read
51     //define('VISUALWIKIFONT', 'Helvetica');
52     //define('VISUALWIKIFONT', 'Times');
53     //define('VISUALWIKIFONT', 'Arial');
54     define('VISUALWIKIFONT', 'luximr'); // sf.net, sf.net can only do gif
55
56     // The default font paths do not find your fonts, set the path here:
57     //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/";
58     //$fontpath = "/usr/share/fonts/default/TrueType/";
59 }
60
61 if (!defined('VISUALWIKI_ALLOWOPTIONS'))
62     define('VISUALWIKI_ALLOWOPTIONS', false);
63
64 require_once "lib/WikiPluginCached.php";
65
66 class WikiPlugin_VisualWiki
67 extends WikiPluginCached
68 {
69     /**
70      * Sets plugin type to map production
71      */
72     function getPluginType() {
73         return PLUGIN_CACHED_MAP;
74     }
75
76     /**
77      * Sets the plugin's name to VisualWiki. It can be called by
78      * <code>&lt;?plugin VisualWiki?&gt;</code>, now. This
79      * name must correspond to the filename and the class name.
80      */
81     function getName() {
82         return "VisualWiki";
83     }
84
85     function getVersion() {
86         return preg_replace("/[Revision: $]/", '',
87                             "\$Revision: 1.9 $");
88     }
89
90     /**
91      * Sets textual description.
92      */
93     function getDescription() {
94         return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz.");
95     }
96
97     /**
98      * Returns default arguments. This is put into a separate
99      * function to allow its usage by both <code>getDefaultArguments</code>
100      * and <code>checkArguments</code>
101      */
102     function defaultarguments() {
103         return array('imgtype'        => 'png',
104                      'width'          => 5,
105                      'height'         => 7,
106                      'colorby'        => 'age', // sort by 'age' or 'revtime'
107                      'fillnodes'      => 'off',
108                      'label'          => 'name',
109                      'shape'          => 'ellipse',
110                      'large_nb'       => 5,
111                      'recent_nb'      => 5,
112                      'refined_nb'     => 15,
113                      'backlink_nb'    => 5,
114                      'neighbour_list' => '',
115                      'exclude_list'   => '',
116                      'include_list'   => '',
117                      'fontsize'       => 10,
118                      'debug'          => false,
119                      'help'           => false );
120     }
121
122     /**
123      * Sets the default arguments. WikiPlugin also regards these as
124      * the allowed arguments. Since WikiPluginCached stores an image
125      * for each different set of parameters, there can be a lot of
126      * these (large) graphs if you allow different parameters.
127      * Set <code>VISUALWIKI_ALLOWOPTIONS</code> to <code>false</code>
128      * to allow no options to be set and use only the default paramters.
129      * This will need an disk space of about 20 Kbyte all the time.
130      */
131     function getDefaultArguments() {
132         if (VISUALWIKI_ALLOWOPTIONS)
133             return $this->defaultarguments();
134         else
135             return array();
136     }
137
138     /**
139      * Substitutes each forbidden parameter value by the default value
140      * defined in <code>defaultarguments</code>.
141      */
142     function checkArguments(&$arg) {
143         extract($arg);
144         $def = $this->defaultarguments();
145
146         if (($width < 3) || ($width > 15))
147             $arg['width'] = $def['width'];
148
149         if (($height < 3) || ($height > 20))
150             $arg['height'] = $def['height'];
151
152         if (($fontsize < 8) || ($fontsize > 24))
153             $arg['fontsize'] = $def['fontsize'];
154
155         if (!in_array($label, array('name', 'number')))
156             $arg['label'] = $def['label'];
157
158         if (!in_array($shape, array('ellipse', 'box', 'point', 'circle',
159                                     'plaintext')))
160             $arg['shape'] = $def['shape'];
161
162         if (!in_array($colorby, array('age', 'revtime')))
163             $arg['colorby'] = $def['colorby'];
164
165         if (!in_array($fillnodes, array('on', 'off')))
166             $arg['fillnodes'] = $def['fillnodes'];
167
168         if (($large_nb < 0) || ($large_nb > 50))
169             $arg['large_nb'] = $def['large_nb'];
170
171         if (($recent_nb < 0)  || ($recent_nb > 50))
172             $arg['recent_nb'] = $def['recent_nb'];
173
174         if (($refined_nb < 0 ) || ( $refined_nb > 50))
175             $arg['refined_nb'] = $def['refined_nb'];
176
177         if (($backlink_nb < 0) || ($backlink_nb > 50))
178             $arg['backlink_nb'] = $def['backlink_nb'];
179
180         // ToDo: check if "ImageCreateFrom$imgtype"() exists.
181         if (!in_array($imgtype, $GLOBALS['CacheParams']['imgtypes']))
182             $arg['imgtype'] = $def['imgtype'];
183         if (empty($fontname))
184             $arg['fontname'] = VISUALWIKIFONT;
185     }
186
187     /**
188      * Checks options, creates help page if necessary, calls both
189      * database access and image map production functions.
190      * @return array($map,$html)
191      */
192     function getMap($dbi, $argarray, $request) {
193         if (!VISUALWIKI_ALLOWOPTIONS)
194             $argarray = $this->defaultarguments();
195         $this->checkArguments($argarray);
196         //extract($argarray);
197         if ($argarray['help'])
198             return array($this->helpImage(), ' '); // FIXME
199         $this->createColors();
200         $this->extract_wikipages($dbi, $argarray);
201         /* ($dbi,  $large, $recent, $refined, $backlink,
202             $neighbour, $excludelist, $includelist, $color); */
203         return $this->invokeDot($argarray);
204         /* ($width, $height, $color, $shape, $text); */
205     }
206
207     /**
208      * Sets the expire time to one day (so the image producing
209      * functions are called seldomly) or to about two minutes
210      * if a help screen is created.
211      */
212     function getExpire($dbi, $argarray, $request) {
213         if ($argarray['help'])
214             return '+120'; // 2 minutes
215         return sprintf('+%d', 3*86000); // approx 3 days
216     }
217
218     /**
219      * Sets the imagetype according to user wishes and
220      * relies on WikiPluginCached to catch illegal image
221      * formats.
222      * (I feel unsure whether this option is reasonable in
223      *  this case, because png will definitely have the
224      *  best results.)
225      *
226      * @return string 'png', 'gif', 'jpeg'
227      */
228     function getImageType($dbi, $argarray, $request) {
229         return $argarray['imgtype'];
230     }
231
232     /**
233      * This gives an alternative text description of
234      * the image map. I do not know whether it interferes
235      * with the <code>title</code> attributes in &lt;area&gt;
236      * tags of the image map. Perhaps this will be removed.
237      * @return string
238      */
239     function getAlt($dbi, $argstr, $request) {
240         return $this->getDescription();
241     }
242
243     // ------------------------------------------------------------------------------------------
244
245     /**
246      * Returns an image containing a usage description of the plugin.
247      * @return string image handle
248      */
249     function helpImage() {
250         $def = $this->defaultarguments();
251         $other_imgtypes = $GLOBALS['CacheParams']['imgtypes'];
252         unset ($other_imgtypes[$def['imgtype']]);
253         $helparr = array(
254             '<?plugin '.$this->getName() .
255             ' img'             => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['CacheParams']['imgtypes']).'"',
256             'width'            => ' = "width in inches"',
257             'height'           => ' = "height in inches"',
258             'fontname'         => ' = "font family"',
259             'fontsize'         => ' = "fontsize in points"',
260             'colorby'          => ' = "age|revtime|none"',
261             'fillnodes'        => ' = "on|off"',
262             'shape'            => ' = "ellipse(default)|box|circle|point"',
263             'label'            => ' = "name|number"',
264             'large_nb'         => ' = "number of largest pages to be selected"',
265             'recent_nb'        => ' = "number of youngest pages"',
266             'refined_nb'       => ' = "#pages with smallest time between revisions"',
267             'backlink_nb'      => ' = "number of pages with most backlinks"',
268             'neighbour_list'   => ' = "find pages linked from and to these pages"',
269             'exclude_list'     => ' = "colon separated list of pages to be excluded"',
270             'include_list'     => ' = "colon separated list"     ?>'
271             );
272         $length = 0;
273         foreach($helparr as $alignright => $alignleft) {
274             $length = max($length, strlen($alignright));
275         }
276         $helptext ='';
277         foreach($helparr as $alignright => $alignleft) {
278             $helptext .= substr('                                                        '
279                                 . $alignright, -$length).$alignleft."\n";
280         }
281         return $this->text2img($helptext, 4, array(1, 0, 0),
282                                array(255, 255, 255));
283     }
284
285
286     /**
287      * Selects the first (smallest or biggest) WikiPages in
288      * a given category.
289      *
290      * @param  number   integer  number of page names to be found
291      * @param  category string   attribute of the pages which is used
292      *                           to compare them
293      * @param  minimum  boolean  true finds smallest, false finds biggest
294      * @return array             list of page names found to be the best
295      */
296     function findbest($number, $category, $minimum ) {
297         // select the $number best in the category '$category'
298         $pages = &$this->pages;
299         $names = &$this->names;
300
301         $selected = array();
302         $i = 0;
303         foreach($names as $name) {
304             if ($i++>=$number)
305                 break;
306             $selected[$name] = $pages[$name][$category];
307         }
308         //echo "<pre>$category "; var_dump($selected); "</pre>";
309         $compareto = $minimum ? 0x79999999 : -0x79999999;
310
311         $i = 0;
312         foreach ($names as $name) {
313             if ($i++<$number)
314                 continue;
315             if ($minimum) {
316                 if (($crit = $pages[$name][$category]) < $compareto) {
317                     $selected[$name] = $crit;
318                     asort($selected, SORT_NUMERIC);
319                     array_pop($selected);
320                     $compareto = end($selected);
321                 }
322             } elseif (($crit = $pages[$name][$category]) > $compareto)  {
323                 $selected[$name] = $crit;
324                 arsort($selected, SORT_NUMERIC);
325                 array_pop($selected);
326                 $compareto = end($selected);
327             }
328         }
329         //echo "<pre>$category "; var_dump($selected); "</pre>";
330
331         return array_keys($selected);
332     }
333
334
335     /**
336     * Extracts a subset of all pages from the wiki and find their
337     * connections to other pages. Also collects some page features
338     * like size, age, revision number which are used to find the
339     * most attractive pages.
340     *
341     * @param  dbi         WikiDB   database handle to access all Wiki pages
342     * @param  LARGE       integer  number of largest pages which should
343     *                              be included
344     * @param  RECENT      integer  number of the youngest pages to be included
345     * @param  REFINED     integer  number of the pages with shortes revision
346     *                              interval
347     * @param  BACKLINK    integer  number of the pages with most backlinks
348     * @param  EXCLUDELIST string   colon ':' separated list of page names which
349     *                              should not be displayed (like PhpWiki, for
350     *                              example)
351     * @param  INCLUDELIST string   colon separated list of pages which are
352     *                              allways included (for example your own
353     *                              page :)
354     * @param  COLOR       string   'age', 'revtime' or 'none'; Selects which
355     *                              page feature is used to determine the
356     *                              filling color of the nodes in the graph.
357     * @return void
358     */
359     function extract_wikipages($dbi, $argarray) {
360         // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR,
361         // $EXCLUDELIST, $INCLUDELIST,$COLOR
362         $now = time();
363
364         extract($argarray);
365         // FIXME: gettextify?
366         $exclude_list   = explode(':', $exclude_list);
367         $include_list   = explode(':', $include_list);
368         $neighbour_list = explode(':', $neighbour_list);
369
370         // FIXME remove INCLUDED from EXCLUDED
371
372         // collect all pages
373         $allpages = $dbi->getAllPages();
374         $pages = &$this->pages;
375         $countpages = 0;
376         while ($page = $allpages->next()) {
377             $name = $page->getName();
378
379             // skip exluded pages
380             if (in_array($name, $exclude_list)) continue;
381
382             // false = get links from actual page
383             // true  = get links to actual page ("backlinks")
384             $backlinks = $page->getLinks(true);
385             unset($bconnection);
386             $bconnection = array();
387             while ($blink = $backlinks->next()) {
388                 array_push($bconnection, $blink->getName());
389             }
390             unset($backlinks);
391
392             // include all neighbours of pages listed in $NEIGHBOUR
393             if (in_array($name,$neighbour_list)) {
394                 $l = $page->getLinks(false);
395                 $con = array();
396                 while ($link = $l->next()) {
397                     array_push($con, $link->getName());
398                 }
399                 $include_list = array_merge($include_list, $bconnection, $con);
400                 unset($l);
401                 unset($con);
402             }
403
404             unset($currev);
405             $currev = $page->getCurrentRevision();
406
407             $pages[$name] = array(
408                 'age'         => $now-$currev->get('mtime'),
409                 'revnr'       => $currev->getVersion(),
410                 'links'       => array(),
411                 'backlink_nb' => count($bconnection),
412                 'backlinks'   => $bconnection,
413                 'size'        => 1000 // FIXME
414                 );
415             $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']);
416
417             unset($page);
418         }
419         unset($allpages);
420         $this->names = array_keys($pages);
421
422         $countpages = count($pages);
423
424         // now select each page matching to given parameters
425         $all_selected = array_unique(array_merge(
426             $this->findbest($recent_nb,   'age',         true),
427             $this->findbest($refined_nb,  'revtime',     true),
428             $x = $this->findbest($backlink_nb, 'backlink_nb', false),
429 //            $this->findbest($large_nb,    'size',        false),
430             $include_list));
431
432         foreach($all_selected as $name)
433             if (isset($pages[$name]))
434                 $newpages[$name] = $pages[$name];
435         unset($this->names);
436         unset($this->pages);
437         $this->pages = $newpages;
438         $pages = &$this->pages;
439         $this->names = array_keys($pages);
440         unset($newpages);
441         unset($all_selected);
442
443         $countpages = count($pages);
444
445         // remove dead links and collect links
446         reset($pages);
447         while( list($name,$page) = each($pages) ) {
448             if (is_array($page['backlinks'])) {
449                 reset($page['backlinks']);
450                 while ( list($index, $link) = each( $page['backlinks'] ) ) {
451                     if ( !isset($pages[$link]) || $link == $name ) {
452                         unset($pages[$name]['backlinks'][$index]);
453                     } else {
454                         array_push($pages[$link]['links'],$name);
455                         //array_push($this->everylink, array($link,$name));
456                     }
457                 }
458             }
459         }
460
461         if ($colorby == 'none')
462             return;
463         list($oldestname) = $this->findbest(1, $colorby, false);
464         $this->oldest = $pages[$oldestname][$colorby];
465         foreach($this->names as $name)
466             $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest);
467     } // extract_wikipages
468
469     /**
470      * Creates the text file description of the graph needed to invoke
471      * <code>dot</code>.
472      *
473      * @param filename  string  name of the dot file to be created
474      * @param width     float   width of the output graph in inches
475      * @param height    float   height of the graph in inches
476      * @param colorby   string  color sceme beeing used ('age', 'revtime',
477      *                                                   'none')
478      * @param shape     string  node shape; 'ellipse', 'box', 'circle', 'point'
479      * @param label     string  'name': label by name,
480      *                          'number': label by unique number
481      * @return boolean          error status; true=ok; false=error
482      */
483     function createDotFile($filename, $argarray) {
484         extract($argarray);
485         if (!$fp = fopen($filename, 'w'))
486             return false;
487
488         $fillstring = ($fillnodes == 'on') ? 'style=filled,' : '';
489
490         $ok = true;
491         $names = &$this->names;
492         $pages = &$this->pages;
493
494         $nametonumber = array_flip($names);
495
496         $dot = "digraph VisualWiki {\n" // }
497              . (!empty($fontpath) ? "    fontpath=\"$fontpath\"\n" : "")
498              . "    size=\"$width,$height\";\n    ";
499
500         switch ($shape) {
501         case 'point':
502             $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n";
503             break;
504         case 'box':
505             $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n";
506             break;
507         case 'circle':
508             $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n";
509             break;
510         default :
511             $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ;
512         }
513         $dot .= "\n";
514         $i = 0;
515         foreach ($names as $name) {
516
517             $url = rawurlencode($name);
518             // patch to allow Page/SubPage
519             $url = preg_replace('/' . urlencode(SUBPAGE_SEPARATOR) . '/',
520                                 SUBPAGE_SEPARATOR, $url);
521             $nodename = ($label != 'name' ? $nametonumber[$name] + 1 : $name);
522
523             $dot .= "    \"$nodename\" [URL=\"$url\"";
524             if ($colorby != 'none') {
525                 $col = $pages[$name]['color'];
526                 $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring,
527                                 $col[0], $col[1], $col[2]);
528             }
529             $dot .= "];\n";
530
531             if (!empty($pages[$name]['links'])) {
532                 unset($linkarray);
533                 if ($label != 'name')
534                     foreach($pages[$name]['links'] as $linkname)
535                         $linkarray[] = $nametonumber[$linkname] + 1;
536                 else
537                     $linkarray = $pages[$name]['links'];
538                 $linkstring = join('"; "', $linkarray );
539
540                 $c = count($pages[$name]['links']);
541                 $dot .= "        \"$nodename\" -> "
542                      . ($c>1?'{':'')
543                      . "\"$linkstring\";"
544                      . ($c>1?'}':'')
545                      . "\n";
546             }
547         }
548         if ($colorby != 'none') {
549             $dot .= "\n    subgraph cluster_legend {\n"
550                  . "         node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n"
551                  . "         fillcolor=lightgrey;\n"
552                  . "         style=filled;\n"
553                  . "         fontname=$fontname;\n"
554                  . "         fontsize=$fontsize;\n"
555                  . "         label=\"".gettext("Legend")."\";\n";
556             $oldest= ceil($this->oldest / (24 * 3600));
557             $max = 5;
558             $legend = array();
559             for($i = 0; $i < $max; $i++) {
560                 $time = floor($i / $max * $oldest);
561                 $name = '"' . $time .' '. _("days") .'"';
562                 $col = $this->getColor($i/$max);
563                 $dot .= sprintf('       %s [%scolor="#%02X%02X%02X"];',
564                                 $name, $fillstring, $col[0], $col[1], $col[2])
565                     . "\n";
566                 $legend[] = $name;
567             }
568             $dot .= '        '. join(' -> ', $legend)
569                  . ";\n    }\n";
570
571         }
572
573         // {
574         $dot .= "}\n";
575
576         $ok = fwrite($fp, $dot);
577         $ok = fclose($fp) && $ok;  // close anyway
578
579         return $ok;
580     }
581
582     /**
583      * Execute system command.
584      *
585      * @param  cmd string   command to be invoked
586      * @return     boolean  error status; true=ok; false=error
587      */
588     function execute($cmd) {
589         exec($cmd, $outarr, $returnval); // normally 127
590         $errstr = join('',$outarr);
591         if (!empty($errstr))
592             trigger_error($cmd.": ".$errstr, E_USER_WARNING);
593         if (!isWindows())
594             usleep(1000);
595         return empty($errstr);
596     }
597
598     /**
599      * Produces a dot file, calls dot twice to obtain an image and a
600      * text description of active areas for hyperlinking and returns
601      * an image and an html map.
602      *
603      * @param width     float   width of the output graph in inches
604      * @param height    float   height of the graph in inches
605      * @param colorby   string  color sceme beeing used ('age', 'revtime',
606      *                                                   'none')
607      * @param shape     string  node shape; 'ellipse', 'box', 'circle', 'point'
608      * @param label     string  not used anymore
609      */
610     function invokeDot($argarray) {
611         global $dotbin;
612         $cacheparams = $GLOBALS['CacheParams'];
613         $tempfiles = tempnam($cacheparams['cache_dir'], 'VisualWiki');
614         $gif = $argarray['imgtype'];
615         $ImageCreateFromFunc = "ImageCreateFrom$gif";
616         $ok =  $tempfiles
617             && $this->createDotFile($tempfiles.'.dot',$argarray)
618             && $this->execute("$dotbin -T$gif $tempfiles.dot -o $tempfiles.$gif")
619             && $this->execute("$dotbin -Timap $tempfiles.dot -o $tempfiles.map")
620             && file_exists( "$tempfiles.$gif" )
621             && file_exists( $tempfiles.'.map' )
622             && ($img = $ImageCreateFromFunc( "$tempfiles.$gif" ))
623             && ($fp = fopen($tempfiles.'.map','r'));
624
625         $map = HTML();
626         if ($ok) {
627             while (!feof($fp)) {
628                 $line = fgets($fp, 1000);
629                 if (substr($line, 0, 1) == '#')
630                     continue;
631                 list($shape, $url, $e1, $e2, $e3, $e4) = sscanf($line,
632                                                                 "%s %s %d,%d %d,%d");
633                 if ($shape != 'rect')
634                     continue;
635
636                 // dot sometimes gives not allways the right order so
637                 // so we have to sort a bit
638                 $x1 = min($e1, $e3);
639                 $x2 = max($e1, $e3);
640                 $y1 = min($e2, $e4);
641                 $y2 = max($e2, $e4);
642                 $map->pushContent(HTML::area(array(
643                             'shape'  => 'rect',
644                             'coords' => "$x1,$y1,$x2,$y2",
645                             'href'   => $url,
646                             'title'  => rawurldecode($url),
647                             'alt' => $url)));
648                 }
649             fclose($fp);
650 //trigger_error("url=".$url);
651         } else {
652             trigger_error("
653 $tempfiles.$gif: ".(file_exists("$tempfiles.$gif") ? filesize("$tempfiles.$gif"):'missing')."
654 $tempfiles.map: ".(file_exists("$tempfiles.map") ? filesize("$tempfiles.map"):'missing')."
655 ",E_USER_WARNING);
656         }
657
658         // clean up tempfiles
659         if ($ok or !$debug)
660         foreach (array('',".$gif",".map",".dot") as $ext) {
661             if (file_exists($tempfiles.$ext))
662                 unlink($tempfiles.$ext);
663         }
664
665         if ($ok)
666             return array($img, $map);
667         else
668             return array(false, false);
669     } // invokeDot
670
671     /**
672      * Prepares some rainbow colors for the nodes of the graph
673      * and stores them in an array which may be accessed with
674      * <code>getColor</code>.
675      */
676     function createColors() {
677         $predefcolors = array(
678              array('red' => 255, 'green' =>   0, 'blue' =>   0),
679              array('red' => 255, 'green' => 255, 'blue' =>   0),
680              array('red' =>   0, 'green' => 255, 'blue' =>   0),
681              array('red' =>   0, 'green' => 255, 'blue' => 255),
682              array('red' =>   0, 'green' =>   0, 'blue' => 255),
683              array('red' => 100, 'green' => 100, 'blue' => 100)
684              );
685
686         $steps = 2;
687         $numberofcolors = count($predefcolors) * $steps;
688
689         $promille = -1;
690         foreach($predefcolors as $color) {
691             if ($promille < 0) {
692                 $oldcolor = $color;
693                 $promille = 0;
694                 continue;
695             }
696             for ($i = 0; $i < $steps; $i++)
697                 $this->ColorTab[++$promille / $numberofcolors * 1000] = array(
698                     floor(interpolate( $oldcolor['red'],   $color['red'],   $i/$steps )),
699                     floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )),
700                     floor(interpolate( $oldcolor['blue'],  $color['blue'],  $i/$steps ))
701                 );
702             $oldcolor = $color;
703         }
704 //echo"<pre>";  var_dump($this->ColorTab); echo "</pre>";
705     }
706
707     /**
708      * Translates a value from 0.0 to 1.0 into rainbow color.
709      * red -&gt; orange -&gt; green -&gt; blue -&gt; gray
710      *
711      * @param promille float value between 0.0 and 1.0
712      * @return array(red,green,blue)
713      */
714     function getColor($promille) {
715         foreach( $this->ColorTab as $pro => $col ) {
716             if ($promille*1000 < $pro)
717                 return $col;
718         }
719         $lastcol = end($this->ColorTab);
720         return $lastcol;
721     } // getColor
722 } // WikiPlugin_VisualWiki
723
724 /**
725  * Linear interpolates a value between two point a and b
726  * at a value pos.
727  * @return float  interpolated value
728  */
729
730 function interpolate($a, $b, $pos) {
731     return $a + ($b - $a) * $pos;
732 }
733
734 // $Log: not supported by cvs2svn $
735 // Revision 1.8  2004/01/26 09:18:00  rurban
736 // * changed stored pref representation as before.
737 //   the array of objects is 1) bigger and 2)
738 //   less portable. If we would import packed pref
739 //   objects and the object definition was changed, PHP would fail.
740 //   This doesn't happen with an simple array of non-default values.
741 // * use $prefs->retrieve and $prefs->store methods, where retrieve
742 //   understands the interim format of array of objects also.
743 // * simplified $prefs->get() and fixed $prefs->set()
744 // * added $user->_userid and class '_WikiUser' portability functions
745 // * fixed $user object ->_level upgrading, mostly using sessions.
746 //   this fixes yesterdays problems with loosing authorization level.
747 // * fixed WikiUserNew::checkPass to return the _level
748 // * fixed WikiUserNew::isSignedIn
749 // * added explodePageList to class PageList, support sortby arg
750 // * fixed UserPreferences for WikiUserNew
751 // * fixed WikiPlugin for empty defaults array
752 // * UnfoldSubpages: added pagename arg, renamed pages arg,
753 //   removed sort arg, support sortby arg
754 //
755 // Revision 1.7  2003/03/03 13:57:31  carstenklapp
756 // Added fontpath (see PhpWiki:VisualWiki), tries to be smart about which OS.
757 // (This plugin still doesn't work for me on OS X, but at least image files
758 // are actually being created now in '/tmp/cache'.)
759 //
760 // Revision 1.6  2003/01/18 22:11:45  carstenklapp
761 // Code cleanup:
762 // Reformatting & tabs to spaces;
763 // Added copyleft, getVersion, getDescription, rcs_id.
764 //
765
766 // Local Variables:
767 // mode: php
768 // tab-width: 8
769 // c-basic-offset: 4
770 // c-hanging-comment-ender-p: nil
771 // indent-tabs-mode: nil
772 // End:
773 ?>