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