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