]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPluginCached.php
Add () for new WikiPluginLoader
[SourceForge/phpwiki.git] / lib / WikiPluginCached.php
1 <?php
2 /*
3  * Copyright (C) 2002 Johannes Große
4  * Copyright (C) 2004,2007 Reini Urban
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  * You should set up the options in config/config.ini at Part seven:
25  * $ pear install http://pear.php.net/get/Cache
26  * This file belongs to WikiPluginCached.
27  */
28
29 require_once 'lib/WikiPlugin.php';
30 // require_once "lib/plugincache-config.php"; // replaced by config.ini settings!
31
32 // types:
33 define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation)
34 define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images
35 define('PLUGIN_CACHED_MAP', 2); // area maps
36 define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object
37 define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback
38 define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object
39 define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?)
40 define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?)
41 // boolean tests:
42 define('PLUGIN_CACHED_IMG_ONDEMAND', 64); // don't cache
43 define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id=
44
45 /**
46  * An extension of the WikiPlugin class to allow image output and
47  * cacheing.
48  * There are several abstract functions to be overloaded.
49  * Have a look at the example files
50  * <ul><li>plugin/TexToPng.php</li>
51  *     <li>plugin/CacheTest.php (extremely simple example)</li>
52  *     <li>plugin/RecentChangesCached.php</li>
53  *     <li>plugin/VisualWiki.php</li>
54  *     <li>plugin/Ploticus.php</li>
55  * </ul>
56  *
57  * @author  Johannes Große, Reini Urban
58  */
59 class WikiPluginCached extends WikiPlugin
60 {
61     var $_static;
62
63     /**
64      * Produces URL and id number from plugin arguments which later on,
65      * will allow to find a cached image or to reconstruct the complete
66      * plugin call to recreate the image.
67      *
68      * @param cache    object the cache object used to store the images
69      * @param argarray array  all parameters (including those set to
70      *                        default values) of the plugin call to be
71      *                        prepared
72      * @access private
73      * @return array(id,url)
74      *
75      * TODO: check if args is needed at all (on lost cache)
76      */
77     function genUrl($cache, $argarray)
78     {
79         global $request;
80         //$cacheparams = $GLOBALS['CacheParams'];
81
82         $plugincall = serialize(array(
83             'pluginname' => $this->getName(),
84             'arguments' => $argarray));
85         $id = $cache->generateId($plugincall);
86         $plugincall_arg = rawurlencode($plugincall);
87         //$plugincall_arg = md5($plugincall);
88         // will not work if plugin has to recreate content and cache is lost
89
90         $url = DATA_PATH . '/getimg.php?';
91         if (($lastchar = substr($url, -1)) == '/') {
92             $url = substr($url, 0, -1);
93         }
94         if (strlen($plugincall_arg) > PLUGIN_CACHED_MAXARGLEN) {
95             // we can't send the data as URL so we just send the id
96             if (!$request->getSessionVar('imagecache' . $id)) {
97                 $request->setSessionVar('imagecache' . $id, $plugincall);
98             }
99             $plugincall_arg = false; // not needed anymore
100         }
101
102         if ($lastchar == '?') {
103             // this indicates that a direct call of the image creation
104             // script is wished ($url is assumed to link to the script)
105             $url .= "id=$id" . ($plugincall_arg ? '&args=' . $plugincall_arg : '');
106         } else {
107             // Not yet supported.
108             // We are supposed to use the indirect 404 ErrorDocument method
109             // ($url is assumed to be the url of the image in
110             //  cache_dir and the image creation script is referred to in the
111             //  ErrorDocument 404 directive.)
112             $url .= '/' . PLUGIN_CACHED_FILENAME_PREFIX . $id . '.img'
113                 . ($plugincall_arg ? '?args=' . $plugincall_arg : '');
114         }
115         if ($request->getArg("start_debug") and (DEBUG & _DEBUG_REMOTE))
116             $url .= "&start_debug=1";
117         return array($id, $url);
118     } // genUrl
119
120     /**
121      * Replaces the abstract run method of WikiPlugin to implement
122      * a cache check which can avoid redundant runs.
123      * <b>Do not override this method in a subclass. Instead you may
124      * rename your run method to getHtml, getImage or getMap.
125      * Have a close look on the arguments and required return values,
126      * however. </b>
127      *
128      * @access protected
129      * @param  dbi       WikiDB  database abstraction class
130      * @param  argstr    string  plugin arguments in the call from PhpWiki
131      * @param  request   Request ???
132      * @param  string    basepage Pagename to use to interpret links [/relative] page names.
133      * @return string HTML output to be printed to browser
134      *
135      * @see #getHtml
136      * @see #getImage
137      * @see #getMap
138      */
139     function run($dbi, $argstr, &$request, $basepage)
140     {
141         $cache = $this->newCache();
142         //$cacheparams = $GLOBALS['CacheParams'];
143
144         $sortedargs = $this->getArgs($argstr, $request);
145         if (is_array($sortedargs))
146             ksort($sortedargs);
147         $this->_args =& $sortedargs;
148         $this->_type = $this->getPluginType();
149         $this->_static = false;
150         if ($this->_type & PLUGIN_CACHED_STATIC
151             or $request->getArg('action') == 'pdf'
152         ) // htmldoc doesn't grok subrequests
153         {
154             $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC;
155             $this->_static = true;
156         }
157
158         // ---------- embed static image, no getimg.php? url -----------------
159         if (0 and $this->_static) {
160             //$content = $cache->get($id, 'imagecache');
161             $content = array();
162             if ($this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html')) {
163                 // save the image in uploads
164                 return $this->embedImg($content['url'], $dbi, $sortedargs, $request);
165             } else {
166                 // copy the cached image into uploads if older
167                 return HTML();
168             }
169         }
170
171         list($id, $url) = $this->genUrl($cache, $sortedargs);
172         // ---------- don't check cache: html and img gen. -----------------
173         // override global PLUGIN_CACHED_USECACHE for a plugin
174         if ($this->getPluginType() & PLUGIN_CACHED_IMG_ONDEMAND) {
175             if ($this->_static and $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'))
176                 $url = $content['url'];
177             return $this->embedImg($url, $dbi, $sortedargs, $request);
178         }
179
180         $do_save = false;
181         $content = $cache->get($id, 'imagecache');
182         switch ($this->_type) {
183             case PLUGIN_CACHED_HTML:
184                 if (!$content || !$content['html']) {
185                     $this->resetError();
186                     $content['html'] = $this->getHtml($dbi, $sortedargs, $request, $basepage);
187                     if ($errortext = $this->getError()) {
188                         $this->printError($errortext, 'html');
189                         return HTML();
190                     }
191                     $do_save = true;
192                 }
193                 break;
194             case PLUGIN_CACHED_IMG_INLINE:
195                 if (PLUGIN_CACHED_USECACHE && (!$content || !$content['image'])) { // new
196                     $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
197                     if ($this->_static) $url = $content['url'];
198                     $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
199                 } elseif (!empty($content['url']) && $this->_static) { // already in cache
200                     $content['html'] = $this->embedImg($content['url'], $dbi, $sortedargs, $request);
201                 } elseif (!empty($content['image']) && $this->_static) { // copy from cache to upload
202                     $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
203                     $url = $content['url'];
204                     $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
205                 }
206                 break;
207             case PLUGIN_CACHED_MAP:
208                 if (!$content || !$content['image'] || !$content['html']) {
209                     $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
210                     if ($this->_static) $url = $content['url'];
211                     $content['html'] = $do_save
212                         ? $this->embedMap($id, $url, $content['html'], $dbi, $sortedargs, $request)
213                         : false;
214                 }
215                 break;
216             case PLUGIN_CACHED_SVG:
217                 if (!$content || !$content['html']) {
218                     $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
219                     if ($this->_static) $url = $content['url'];
220                     $args = array(); //width+height => object args
221                     if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
222                     if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
223                     $content['html'] = $do_save
224                         ? $this->embedObject($url, 'image/svg+xml', $args,
225                             HTML::embed(array_merge(
226                                 array('src' => $url, 'type' => 'image/svg+xml'),
227                                 $args)))
228                         : false;
229                 }
230                 break;
231             case PLUGIN_CACHED_SVG_PNG:
232                 if (!$content || !$content['html']) {
233                     $do_save_svg = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
234                     if ($this->_static) $url = $content['url'];
235                     // hack alert! somehow we should know which argument will produce the secondary image (PNG)
236                     $args = $sortedargs;
237                     $args[$this->pngArg()] = $content['imagetype']; // default type: PNG or GIF
238                     $do_save = $this->produceImage($pngcontent, $this, $dbi, $args, $request, $content['imagetype']);
239                     $args = array(); //width+height => object args
240                     if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
241                     if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
242                     $content['html'] = $do_save_svg
243                         ? $this->embedObject($url, 'image/svg+xml', $args,
244                             $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request))
245                         : false;
246                 }
247                 break;
248         }
249         if ($do_save) {
250             $content['args'] = md5($this->_pi);
251             $expire = $this->getExpire($dbi, $content['args'], $request);
252             $cache->save($id, $content, $expire, 'imagecache');
253         }
254         if ($content['html'])
255             return $content['html'];
256         return HTML();
257     } // run
258
259     /* --------------------- virtual or abstract functions ----------- */
260
261     /**
262      * Sets the type of the plugin to html, image or map
263      * production
264      *
265      * @access protected
266      * @return int determines the plugin to produce either html,
267      *             an image or an image map; uses on of the
268      *             following predefined values
269      *             <ul>
270      *             <li>PLUGIN_CACHED_HTML</li>
271      *             <li>PLUGIN_CACHED_IMG_INLINE</li>
272      *             <li>PLUGIN_CACHED_IMG_ONDEMAND</li>
273      *             <li>PLUGIN_CACHED_MAP</li>
274      *             </ul>
275      */
276     function getPluginType()
277     {
278         return PLUGIN_CACHED_IMG_ONDEMAND;
279     }
280
281     /**
282      * Creates an image handle from the given user arguments.
283      * This method is only called if the return value of
284      * <code>getPluginType</code> is set to
285      * PLUGIN_CACHED_IMG_INLINE or PLUGIN_CACHED_IMG_ONDEMAND.
286      *
287      * @access protected pure virtual
288      * @param  dbi       WikiDB       database abstraction class
289      * @param  argarray  array        complete (!) arguments to produce
290      *                                image. It is not necessary to call
291      *                                WikiPlugin->getArgs anymore.
292      * @param  request   Request      ???
293      * @return imagehandle image handle if successful
294      *                                false if an error occured
295      */
296     function getImage($dbi, $argarray, $request)
297     {
298         trigger_error('WikiPluginCached::getImage: pure virtual function in file '
299             . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
300         return false;
301     }
302
303     /**
304      * Sets the life time of a cache entry in seconds.
305      * Expired entries are not used anymore.
306      * During a garbage collection each expired entry is
307      * removed. If removing all expired entries is not
308      * sufficient, the expire time is ignored and removing
309      * is determined by the last "touch" of the entry.
310      *
311      * @access protected virtual
312      * @param  dbi       WikiDB       database abstraction class
313      * @param  argarray  array        complete (!) arguments. It is
314      *                                not necessary to call
315      *                                WikiPlugin->getArgs anymore.
316      * @param  request   Request      ???
317      * @return string format: '+seconds'
318      *                                '0' never expires
319      */
320     function getExpire($dbi, $argarray, $request)
321     {
322         return '0'; // persist forever
323     }
324
325     /**
326      * Decides the image type of an image output.
327      * Always used unless plugin type is PLUGIN_CACHED_HTML.
328      *
329      * @access protected virtual
330      * @param  dbi       WikiDB       database abstraction class
331      * @param  argarray  array        complete (!) arguments. It is
332      *                                not necessary to call
333      *                                WikiPlugin->getArgs anymore.
334      * @param  request   Request      ???
335      * @return string 'png', 'jpeg' or 'gif'
336      */
337     function getImageType(&$dbi, $argarray, &$request)
338     {
339         if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
340             return $argarray['imgtype'];
341         else
342             return 'png';
343     }
344
345     /**
346      * Produces the alt text for an image.
347      * <code> &lt;img src=... alt="getAlt(...)"&gt; </code>
348      *
349      * @access protected virtual
350      * @param  dbi       WikiDB       database abstraction class
351      * @param  argarray  array        complete (!) arguments. It is
352      *                                not necessary to call
353      *                                WikiPlugin->getArgs anymore.
354      * @param  request   Request      ???
355      * @return string "alt" description of the image
356      */
357     function getAlt($dbi, $argarray, $request)
358     {
359         return '<?plugin ' . $this->getName() . ' ' . $this->glueArgs($argarray) . '?>';
360     }
361
362     /**
363      * Creates HTML output to be cached.
364      * This method is only called if the plugin_type is set to
365      * PLUGIN_CACHED_HTML.
366      *
367      * @access protected pure virtual
368      * @param  dbi       WikiDB       database abstraction class
369      * @param  argarray  array        complete (!) arguments to produce
370      *                                image. It is not necessary to call
371      *                                WikiPlugin->getArgs anymore.
372      * @param  request   Request      ???
373      * @param  string $basepage Pagename to use to interpret links [/relative] page names.
374      * @return string html to be printed in place of the plugin command
375      *                                false if an error occured
376      */
377     function getHtml($dbi, $argarray, $request, $basepage)
378     {
379         trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
380             . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
381     }
382
383     /**
384      * Creates HTML output to be cached.
385      * This method is only called if the plugin_type is set to
386      * PLUGIN_CACHED_HTML.
387      *
388      * @access protected pure virtual
389      * @param  dbi       WikiDB       database abstraction class
390      * @param  argarray  array        complete (!) arguments to produce
391      *                                image. It is not necessary to call
392      *                                WikiPlugin->getArgs anymore.
393      * @param  request   Request      ???
394      * @return array(html,handle) html for the map interior (to be specific,
395      *                                only &lt;area;&gt; tags defining hot spots)
396      *                                handle is an imagehandle to the corresponding
397      *                                image.
398      *                                array(false,false) if an error occured
399      */
400     function getMap($dbi, $argarray, $request)
401     {
402         trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
403             . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
404     }
405
406     /* --------------------- produce Html ----------------------------- */
407
408     /**
409      * Creates an HTML map hyperlinked to the image specified
410      * by url and containing the hotspots given by map.
411      *
412      * @access private
413      * @param  id       string  unique id for the plugin call
414      * @param  url      string  url pointing to the image part of the map
415      * @param  map      string  &lt;area&gt; tags defining active
416      *                          regions in the map
417      * @param  dbi      WikiDB  database abstraction class
418      * @param  argarray array   complete (!) arguments to produce
419      *                          image. It is not necessary to call
420      *                          WikiPlugin->getArgs anymore.
421      * @param  request  Request ???
422      * @return string html output
423      */
424     function embedMap($id, $url, $map, &$dbi, $argarray, &$request)
425     {
426         // id is not unique if the same map is produced twice
427         $key = substr($id, 0, 8) . substr(microtime(), 0, 6);
428         return HTML(HTML::map(array('name' => $key), $map),
429             HTML::img(array(
430                 'src' => $url,
431                 //  'alt'    => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
432                 'usemap' => '#' . $key))
433         );
434     }
435
436     /**
437      * Creates an HTML &lt;img&gt; tag hyperlinking to the specified
438      * url and produces an alternative text for non-graphical
439      * browsers.
440      *
441      * @access private
442      * @param  url      string  url pointing to the image part of the map
443      * @param  map      string  &lt;area&gt; tags defining active
444      *                          regions in the map
445      * @param  dbi      WikiDB  database abstraction class
446      * @param  argarray array   complete (!) arguments to produce
447      *                          image. It is not necessary to call
448      *                          WikiPlugin->getArgs anymore.
449      * @param  request  Request ???
450      * @return string html output
451      */
452     function embedImg($url, $dbi, $argarray, $request)
453     {
454         return HTML::img(array(
455             'src' => $url,
456             'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request))));
457     }
458
459     /**
460      * svg?, swf, ...
461     <object type="audio/x-wav" standby="Loading Audio" data="example.wav">
462     <param name="src" value="example.wav" valuetype="data"></param>
463     <param name="autostart" value="false" valuetype="data"></param>
464     <param name="controls" value="ControlPanel" valuetype="data"></param>
465     <a href="example.wav">Example Audio File</a>
466     </object>
467      * See http://www.protocol7.com/svg-wiki/?EmbedingSvgInHTML
468     <object data="sample.svgz" type="image/svg+xml"
469     width="400" height="300">
470     <embed src="sample.svgz" type="image/svg+xml"
471     width="400" height="300" />
472     <p>Alternate Content like <img src="" /></p>
473     </object>
474      */
475     // how to handle alternate images? always provide alternate static images?
476     function embedObject($url, $type, $args = false, $params = false)
477     {
478         if (!$args) $args = array();
479         $object = HTML::object(array_merge($args, array('src' => $url, 'type' => $type)));
480         if ($params)
481             $object->pushContent($params);
482         return $object;
483     }
484
485 // --------------------------------------------------------------------------
486 // ---------------------- static member functions ---------------------------
487 // --------------------------------------------------------------------------
488
489     /**
490      * Creates one static PEAR Cache object and returns copies afterwards.
491      * FIXME: There should be references returned
492      *
493      * @access static protected
494      * @return Cache copy of the cache object
495      */
496     function newCache()
497     {
498         static $staticcache;
499
500         if (!is_object($staticcache)) {
501             if (!class_exists('Cache')) {
502                 // uuh, pear not in include_path! should print a warning.
503                 // search some possible pear paths.
504                 $pearFinder = new PearFileFinder;
505                 if ($lib = $pearFinder->findFile('Cache.php', 'missing_ok'))
506                     require_once($lib);
507                 else // fall back to our own copy
508                     require_once 'lib/pear/Cache.php';
509             }
510             $cacheparams = array();
511             foreach (explode(':', 'database:cache_dir:filename_prefix:highwater:lowwater'
512                 . ':maxlifetime:maxarglen:usecache:force_syncmap') as $key) {
513                 $cacheparams[$key] = constant('PLUGIN_CACHED_' . strtoupper($key));
514             }
515             $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES);
516             $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams);
517             $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME;
518
519             if (!PLUGIN_CACHED_USECACHE) {
520                 $staticcache->setCaching(false);
521             }
522         }
523         return $staticcache; // FIXME: use references ?
524     }
525
526     /**
527      * Determines whether a needed image type may is available
528      * from the GD library and gives an alternative otherwise.
529      *
530      * @access  public static
531      * @param   wish   string one of 'png', 'gif', 'jpeg', 'jpg'
532      * @return string the image type to be used ('png', 'gif', 'jpeg')
533      *                        'html' in case of an error
534      */
535
536     function decideImgType($wish)
537     {
538         if ($wish == 'html') return $wish;
539         if ($wish == 'jpg') {
540             $wish = 'jpeg';
541         }
542
543         $supportedtypes = array();
544         // Todo: swf, pdf, ...
545         $imagetypes = array(
546             'png' => IMG_PNG,
547             'gif' => IMG_GIF,
548             'jpeg' => IMG_JPEG,
549             'wbmp' => IMG_WBMP,
550             'xpm' => IMG_XPM,
551             /* // these do work but not with the ImageType bitmask
552             'gd'    => IMG_GD,
553             'gd2'   => IMG_GD,
554             'xbm'   => IMG_XBM,
555             */
556         );
557         if (function_exists('ImageTypes')) {
558             $presenttypes = ImageTypes();
559             foreach ($imagetypes as $imgtype => $bitmask)
560                 if ($presenttypes && $bitmask)
561                     array_push($supportedtypes, $imgtype);
562         } else {
563             foreach ($imagetypes as $imgtype => $bitmask)
564                 if (function_exists("Image" . $imgtype))
565                     array_push($supportedtypes, $imgtype);
566         }
567         if (in_array($wish, $supportedtypes))
568             return $wish;
569         elseif (!empty($supportedtypes))
570             return reset($supportedtypes); else
571             return 'html';
572
573     } // decideImgType
574
575     /**
576      * Writes an image into a file or to the browser.
577      * Note that there is no check if the image can
578      * be written.
579      *
580      * @access  public static
581      * @param   imgtype   string 'png', 'gif' or 'jpeg'
582      * @param   imghandle string image handle containing the image
583      * @param   imgfile   string file name of the image to be produced
584      * @return void
585      * @see     decideImageType
586      */
587     function writeImage($imgtype, $imghandle, $imgfile = false)
588     {
589         if ($imgtype != 'html') {
590             $func = "Image" . strtoupper($imgtype);
591             if ($imgfile) {
592                 $func($imghandle, $imgfile);
593             } else {
594                 $func($imghandle);
595             }
596         }
597     } // writeImage
598
599     /**
600      * Sends HTTP Header for some predefined file types.
601      * There is no parameter check.
602      *
603      * @access  public static
604      * @param   doctype string 'gif', 'png', 'jpeg', 'html'
605      * @return void
606      */
607     function writeHeader($doctype)
608     {
609         static $IMAGEHEADER = array(
610             'gif' => 'Content-type: image/gif',
611             'png' => 'Content-type: image/png',
612             'jpeg' => 'Content-type: image/jpeg',
613             'xbm' => 'Content-type: image/xbm',
614             'xpm' => 'Content-type: image/xpm',
615             'gd' => 'Content-type: image/gd',
616             'gd2' => 'Content-type: image/gd2',
617             'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such.
618             'html' => 'Content-type: text/html');
619         // Todo: swf, pdf, svg, svgz
620         Header($IMAGEHEADER[$doctype]);
621     }
622
623     /**
624      * Converts argument array to a string of format option="value".
625      * This should only be used for displaying plugin options for
626      * the quoting of arguments is not safe, yet.
627      *
628      * @access public static
629      * @param  argarray array   contains all arguments to be converted
630      * @return string concated arguments
631      */
632     function glueArgs($argarray)
633     {
634         if (!empty($argarray)) {
635             $argstr = '';
636             while (list($key, $value) = each($argarray)) {
637                 $argstr .= $key . '=' . '"' . $value . '" ';
638                 // FIXME: How are values quoted? Can a value contain '"'?
639                 // TODO: rawurlencode(value)
640             }
641             return substr($argstr, 0, strlen($argstr) - 1);
642         }
643         return '';
644     } // glueArgs
645
646     // ---------------------- FetchImageFromCache ------------------------------
647
648     /**
649      * Extracts the cache entry id from the url and the plugin call
650      * parameters if available.
651      *
652      * @access private static
653      * @param  id           string   return value. Image is stored under this id.
654      * @param  plugincall   string   return value. Only returned if present in url.
655      *                               Contains all parameters to reconstruct
656      *                               plugin call.
657      * @param  cache        Cache    PEAR Cache object
658      * @param  request      Request  ???
659      * @param  errorformat  string   format which should be used to
660      *                               output errors ('html', 'png', 'gif', 'jpeg')
661      * @return boolean false if an error occurs, true otherwise.
662      *                               Param id and param plugincall are
663      *                               also return values.
664      */
665     function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat)
666     {
667         $id = $request->getArg('id');
668         $plugincall = rawurldecode($request->getArg('args'));
669
670         if (!$id) {
671             if (!$plugincall) {
672                 // This should never happen, so do not gettextify.
673                 $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters.";
674                 $this->printError($errorformat, $errortext);
675                 return false;
676             } else {
677                 $id = $cache->generateId($plugincall);
678             }
679         }
680         return true;
681     } // checkCall1
682
683     /**
684      * Extracts the parameters necessary to reconstruct the plugin
685      * call needed to produce the requested image.
686      *
687      * @access static private
688      * @param  plugincall string   reference to serialized array containing both
689      *                             name and parameters of the plugin call
690      * @param  request    Request  ???
691      * @return boolean false if an error occurs, true otherwise.
692      *
693      */
694     function checkCall2(&$plugincall, $request)
695     {
696         // if plugincall wasn't sent by URL, it must have been
697         // stored in a session var instead and we can retreive it from there
698         if (!$plugincall) {
699             if (!$plugincall = $request->getSessionVar('imagecache' . $id)) {
700                 // I think this is the only error which may occur
701                 // without having written bad code. So gettextify it.
702                 $errortext = sprintf(
703                     gettext("There is no image creation data available to id “%s”. Please reload referring page."),
704                     $id);
705                 $this->printError($errorformat, $errortext);
706                 return false;
707             }
708         }
709         $plugincall = unserialize($plugincall);
710         return true;
711     } // checkCall2
712
713     /**
714      * Creates an image or image map depending on the plugin type.
715      * @access static private
716      * @param  content array             reference to created array which overwrite the keys
717      *                                   'image', 'imagetype' and possibly 'html'
718      * @param  plugin  WikiPluginCached  plugin which is called to create image or map
719      * @param  dbi     WikiDB            handle to database
720      * @param  argarray array            Contains all arguments needed by plugin
721      * @param  request Request           ????
722      * @param  errorformat string        outputs errors in 'png', 'gif', 'jpg' or 'html'
723      * @return boolean error status; true=ok; false=error
724      */
725     function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat)
726     {
727         $plugin->resetError();
728         $content['html'] = $imagehandle = false;
729         if ($plugin->getPluginType() == PLUGIN_CACHED_MAP) {
730             list($imagehandle, $content['html']) = $plugin->getMap($dbi, $argarray, $request);
731         } else {
732             $imagehandle = $plugin->getImage($dbi, $argarray, $request);
733         }
734
735         $content['imagetype']
736             = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request));
737         $errortext = $plugin->getError();
738
739         if (!$imagehandle || $errortext) {
740             if (!$errortext) {
741                 $errortext = "'<?plugin " . $plugin->getName() . ' '
742                     . $this->glueArgs($argarray) . " ?>' returned no image, "
743                     . " although no error was reported.";
744             }
745             $this->printError($errorformat, $errortext);
746             return false;
747         }
748
749         // image handle -> image data
750         if (!empty($this->_static)) {
751             $ext = "." . $content['imagetype'];
752             if (is_string($imagehandle) and file_exists($imagehandle)) {
753                 if (preg_match("/.(\w+)$/", $imagehandle, $m)) {
754                     $ext = "." . $m[1];
755                 }
756             }
757             $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext);
758             if (!strstr(basename($tmpfile), $ext)) {
759                 unlink($tmpfile);
760                 $tmpfile .= $ext;
761             }
762             $tmpfile = getUploadFilePath() . basename($tmpfile);
763             if (is_string($imagehandle) and file_exists($imagehandle)) {
764                 rename($imagehandle, $tmpfile);
765             }
766         } else {
767             $tmpfile = $this->tempnam();
768         }
769         if (is_resource($imagehandle)) {
770             $this->writeImage($content['imagetype'], $imagehandle, $tmpfile);
771             ImageDestroy($imagehandle);
772             sleep(0.2);
773         } elseif (is_string($imagehandle)) {
774             $content['file'] = getUploadFilePath() . basename($tmpfile);
775             $content['url'] = getUploadDataPath() . basename($tmpfile);
776             return true;
777         }
778         if (file_exists($tmpfile)) {
779             $fp = fopen($tmpfile, 'rb');
780             $content['image'] = fread($fp, filesize($tmpfile));
781             fclose($fp);
782             if (!empty($this->_static)) {
783                 // on static it is in "uploads/" but in wikicached also
784                 $content['file'] = $tmpfile;
785                 $content['url'] = getUploadDataPath() . basename($tmpfile);
786                 return true;
787             }
788             unlink($tmpfile);
789             if ($content['image'])
790                 return true;
791         }
792         return false;
793     }
794
795     function staticUrl($tmpfile)
796     {
797         $content['file'] = $tmpfile;
798         $content['url'] = getUploadDataPath() . basename($tmpfile);
799         return $content;
800     }
801
802     function tempnam($prefix = "")
803     {
804         if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) {
805             $prefix = $m[1];
806             $ext = "." . $m[2];
807         } else {
808             $ext = isWindows() ? ".tmp" : "";
809         }
810         $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR)
811                 : PLUGIN_CACHED_CACHE_DIR,
812             $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
813         if (isWindows()) {
814             if ($ext != ".tmp") unlink($temp);
815             $temp = preg_replace("/\.tmp$/", $ext, $temp);
816         } else {
817             $temp .= $ext;
818         }
819         return $temp;
820     }
821
822     /**
823      * Main function for obtaining images from cache or generating on-the-fly
824      * from parameters sent by url or session vars.
825      *
826      * @access static public
827      * @param  dbi     WikiDB            handle to database
828      * @param  request Request           ???
829      * @param  errorformat string        outputs errors in 'png', 'gif', 'jpeg' or 'html'
830      */
831     function fetchImageFromCache($dbi, $request, $errorformat = 'png')
832     {
833         $cache = $this->newCache();
834         $errorformat = $this->decideImgType($errorformat);
835         // get id
836         if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false;
837         // check cache
838         $content = $cache->get($id, 'imagecache');
839
840         if (!empty($content['image'])) {
841             $this->writeHeader($content['imagetype']);
842             print $content['image'];
843             return true;
844         }
845         if (!empty($content['html'])) {
846             print $content['html'];
847             return true;
848         }
849         // static version?
850         if (!empty($content['file']) && !empty($content['url']) && file_exists($content['file'])) {
851             print $this->embedImg($content['url'], $dbi, array(), $request);
852             return true;
853         }
854
855         // re-produce image. At first, we need the plugincall parameters.
856         // Cached args with matching id override given args to shorten getimg.php?id=md5
857         if (!empty($content['args']))
858             $plugincall['arguments'] = $content['args'];
859         if (!$this->checkCall2($plugincall, $request)) return false;
860
861         $pluginname = $plugincall['pluginname'];
862         $argarray = $plugincall['arguments'];
863
864         $loader = new WikiPluginLoader();
865         $plugin = $loader->getPlugin($pluginname);
866
867         // cache empty, but image maps have to be created _inline_
868         // so ask user to reload wiki page instead
869         if (($plugin->getPluginType() & PLUGIN_CACHED_MAP) && PLUGIN_CACHED_FORCE_SYNCMAP) {
870             $errortext = _("Image map expired. Reload wiki page to recreate its html part.");
871             $this->printError($errorformat, $errortext);
872         }
873
874         if (!$this->produceImage($content, $plugin, $dbi, $argarray,
875             $request, $errorformat)
876         )
877             return false;
878
879         $expire = $plugin->getExpire($dbi, $argarray, $request);
880
881         if ($content['image']) {
882             $cache->save($id, $content, $expire, 'imagecache');
883             $this->writeHeader($content['imagetype']);
884             print $content['image'];
885             return true;
886         }
887
888         $errortext = "Could not create image file from imagehandle.";
889         $this->printError($errorformat, $errortext);
890         return false;
891     } // FetchImageFromCache
892
893     // -------------------- error handling ----------------------------
894
895     /**
896      * Resets buffer containing all error messages. This is allways
897      * done before invoking any abstract creation routines like
898      * <code>getImage</code>.
899      *
900      * @access private
901      * @return void
902      */
903     function resetError()
904     {
905         $this->_errortext = '';
906     }
907
908     /**
909      * Returns all accumulated error messages.
910      *
911      * @access protected
912      * @return string error messages printed with <code>complain</code>.
913      */
914     function getError()
915     {
916         return $this->_errortext;
917     }
918
919     /**
920      * Collects the error messages in a string for later output
921      * by WikiPluginCached. This should be used for any errors
922      * that occur during data (html,image,map) creation.
923      *
924      * @access protected
925      * @param  addtext string errormessage to be printed (separate
926      *                        multiple lines with '\n')
927      * @return void
928      */
929     function complain($addtext)
930     {
931         $this->_errortext .= $addtext;
932     }
933
934     /**
935      * Outputs the error as image if possible or as html text
936      * if wished or html header has already been sent.
937      *
938      * @access static protected
939      * @param  imgtype string 'png', 'gif', 'jpeg' or 'html'
940      * @param  errortext string guess what?
941      * @return void
942      */
943     function printError($imgtype, $errortext)
944     {
945         $imgtype = $this->decideImgType($imgtype);
946
947         $talkedallready = ob_get_contents() || headers_sent();
948         if (($imgtype == 'html') || $talkedallready) {
949             if (is_object($errortext))
950                 $errortext = $errortext->asXml();
951             trigger_error($errortext, E_USER_WARNING);
952         } else {
953             $red = array(255, 0, 0);
954             $grey = array(221, 221, 221);
955             if (is_object($errortext))
956                 $errortext = $errortext->asString();
957             $im = $this->text2img($errortext, 2, $red, $grey);
958             if (!$im) {
959                 trigger_error($errortext, E_USER_WARNING);
960                 return;
961             }
962             $this->writeHeader($imgtype);
963             $this->writeImage($imgtype, $im);
964             ImageDestroy($im);
965         }
966     } // printError
967
968     /**
969      * Basic text to image converter for error handling which allows
970      * multiple line output.
971      * It will only output the first 25 lines of 80 characters. Both
972      * values may be smaller if the chosen font is to big for there
973      * is further restriction to 600 pixel in width and 350 in height.
974      *
975      * @access static public
976      * @param  txt     string  multi line text to be converted
977      * @param  fontnr  integer number (1-5) telling gd which internal font to use;
978      *                         I recommend font 2 for errors and 4 for help texts.
979      * @param  textcol array   text color as a list of the rgb components; array(red,green,blue)
980      * @param  bgcol   array   background color; array(red,green,blue)
981      * @return string image handle for gd routines
982      */
983     function text2img($txt, $fontnr, $textcol, $bgcol)
984     {
985         // basic (!) output for error handling
986
987         // check parameters
988         if ($fontnr < 1 || $fontnr > 5) {
989             $fontnr = 2;
990         }
991         if (!is_array($textcol) || !is_array($bgcol)) {
992             $textcol = array(0, 0, 0);
993             $bgcol = array(255, 255, 255);
994         }
995         foreach (array_merge($textcol, $bgcol) as $component) {
996             if ($component < 0 || $component > 255) {
997                 $textcol = array(0, 0, 0);
998                 $bgcol = array(255, 255, 255);
999                 break;
1000             }
1001         }
1002
1003         // prepare Parameters
1004
1005         // set maximum values
1006         $IMAGESIZE = array(
1007             'cols' => 80,
1008             'rows' => 25,
1009             'width' => 600,
1010             'height' => 350);
1011
1012         if (function_exists('ImageFontWidth')) {
1013             $charx = ImageFontWidth($fontnr);
1014             $chary = ImageFontHeight($fontnr);
1015         } else {
1016             $charx = 10;
1017             $chary = 10;
1018         }
1019         $marginx = $charx;
1020         $marginy = floor($chary / 2);
1021
1022         $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2 * $marginx) / $charx));
1023         $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2 * $marginy) / $chary));
1024
1025         // split lines
1026         $y = 0;
1027         $wx = 0;
1028         do {
1029             $len = strlen($txt);
1030             $npos = strpos($txt, "\n");
1031
1032             if ($npos === false) {
1033                 $breaklen = min($IMAGESIZE['cols'], $len);
1034             } else {
1035                 $breaklen = min($npos + 1, $IMAGESIZE['cols']);
1036             }
1037             $lines[$y] = chop(substr($txt, 0, $breaklen));
1038             $wx = max($wx, strlen($lines[$y++]));
1039             $txt = substr($txt, $breaklen);
1040         } while ($txt && ($y < $IMAGESIZE['rows']));
1041
1042         // recalculate image size
1043         $IMAGESIZE['rows'] = $y;
1044         $IMAGESIZE['cols'] = $wx;
1045
1046         $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2 * $marginx;
1047         $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2 * $marginy;
1048
1049         // create blank image
1050         $im = @ImageCreate($IMAGESIZE['width'], $IMAGESIZE['height']);
1051
1052         $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]);
1053         $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]);
1054
1055         ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width'] - 1, $IMAGESIZE['height'] - 1, $bg);
1056
1057         // write text lines
1058         foreach ($lines as $nr => $textstr) {
1059             ImageString($im, $fontnr, $marginx, $marginy + $nr * $chary,
1060                 $textstr, $col);
1061         }
1062         return $im;
1063     } // text2img
1064
1065     function newFilterThroughCmd($input, $commandLine)
1066     {
1067         $descriptorspec = array(
1068             0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1069             1 => array("pipe", "w"), // stdout is a pipe that the child will write to
1070             2 => array("pipe", "w"), // stdout is a pipe that the child will write to
1071         );
1072
1073         $process = proc_open("$commandLine", $descriptorspec, $pipes);
1074         if (is_resource($process)) {
1075             // $pipes now looks like this:
1076             // 0 => writeable handle connected to child stdin
1077             // 1 => readable  handle connected to child stdout
1078             // 2 => readable  handle connected to child stderr
1079             fwrite($pipes[0], $input);
1080             fclose($pipes[0]);
1081             $buf = "";
1082             while (!feof($pipes[1])) {
1083                 $buf .= fgets($pipes[1], 1024);
1084             }
1085             fclose($pipes[1]);
1086             $stderr = '';
1087             while (!feof($pipes[2])) {
1088                 $stderr .= fgets($pipes[2], 1024);
1089             }
1090             fclose($pipes[2]);
1091             // It is important that you close any pipes before calling
1092             // proc_close in order to avoid a deadlock
1093             proc_close($process);
1094             if (empty($buf)) printXML($this->error($stderr));
1095             return $buf;
1096         }
1097         return '';
1098     }
1099
1100     // run "echo $source | $commandLine" and return result
1101     function filterThroughCmd($source, $commandLine)
1102     {
1103         return $this->newFilterThroughCmd($source, $commandLine);
1104     }
1105
1106     /**
1107      * Execute system command and wait until the outfile $until exists.
1108      *
1109      * @param  cmd   string   command to be invoked
1110      * @param  until string   expected output filename
1111      * @return boolean error status; true=ok; false=error
1112      */
1113     function execute($cmd, $until = false)
1114     {
1115         // cmd must redirect stderr to stdout though!
1116         $errstr = exec($cmd); //, $outarr, $returnval); // normally 127
1117         //$errstr = join('',$outarr);
1118         $ok = empty($errstr);
1119         if (!$ok) {
1120             trigger_error("\n" . $cmd . " failed: $errstr", E_USER_WARNING);
1121         } elseif ($GLOBALS['request']->getArg('debug'))
1122             trigger_error("\n" . $cmd . ": success\n", E_USER_NOTICE);
1123         if (!isWindows()) {
1124             if ($until) {
1125                 $loop = 100000;
1126                 while (!file_exists($until) and $loop > 0) {
1127                     $loop -= 100;
1128                     usleep(100);
1129                 }
1130             } else {
1131                 usleep(5000);
1132             }
1133         }
1134         if ($until)
1135             return file_exists($until);
1136         return $ok;
1137     }
1138
1139 }
1140
1141 // Local Variables:
1142 // mode: php
1143 // tab-width: 8
1144 // c-basic-offset: 4
1145 // c-hanging-comment-ender-p: nil
1146 // indent-tabs-mode: nil
1147 // End: