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