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