3 * Copyright (C) 2002 Johannes Große
4 * Copyright (C) 2004,2007 Reini Urban
6 * This file is part of PhpWiki.
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.
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.
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.
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.
29 require_once 'lib/WikiPlugin.php';
30 // require_once "lib/plugincache-config.php"; // replaced by config.ini settings!
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?)
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=
46 * An extension of the WikiPlugin class to allow image output and
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>
57 * @author Johannes Große, Reini Urban
59 class WikiPluginCached extends WikiPlugin
64 * Produces URL and id number from plugin arguments which later on,
65 * will allow to find a cached image or to reconstruct the complete
66 * plugin call to recreate the image.
68 * @param cache object the cache object used to store the images
69 * @param argarray array all parameters (including those set to
70 * default values) of the plugin call to be
73 * @return array(id,url)
75 * TODO: check if args is needed at all (on lost cache)
77 function genUrl($cache, $argarray)
80 //$cacheparams = $GLOBALS['CacheParams'];
82 $plugincall = serialize(array(
83 'pluginname' => $this->getName(),
84 'arguments' => $argarray));
85 $id = $cache->generateId($plugincall);
86 $plugincall_arg = rawurlencode($plugincall);
87 //$plugincall_arg = md5($plugincall);
88 // will not work if plugin has to recreate content and cache is lost
90 $url = DATA_PATH . '/getimg.php?';
91 if (($lastchar = substr($url, -1)) == '/') {
92 $url = substr($url, 0, -1);
94 if (strlen($plugincall_arg) > PLUGIN_CACHED_MAXARGLEN) {
95 // we can't send the data as URL so we just send the id
96 if (!$request->getSessionVar('imagecache' . $id)) {
97 $request->setSessionVar('imagecache' . $id, $plugincall);
99 $plugincall_arg = false; // not needed anymore
102 if ($lastchar == '?') {
103 // this indicates that a direct call of the image creation
104 // script is wished ($url is assumed to link to the script)
105 $url .= "id=$id" . ($plugincall_arg ? '&args=' . $plugincall_arg : '');
107 // Not yet supported.
108 // We are supposed to use the indirect 404 ErrorDocument method
109 // ($url is assumed to be the url of the image in
110 // cache_dir and the image creation script is referred to in the
111 // ErrorDocument 404 directive.)
112 $url .= '/' . PLUGIN_CACHED_FILENAME_PREFIX . $id . '.img'
113 . ($plugincall_arg ? '?args=' . $plugincall_arg : '');
115 if ($request->getArg("start_debug") and (DEBUG & _DEBUG_REMOTE))
116 $url .= "&start_debug=1";
117 return array($id, $url);
121 * Replaces the abstract run method of WikiPlugin to implement
122 * a cache check which can avoid redundant runs.
123 * <b>Do not override this method in a subclass. Instead you may
124 * rename your run method to getHtml, getImage or getMap.
125 * Have a close look on the arguments and required return values,
129 * @param dbi WikiDB database abstraction class
130 * @param argstr string plugin arguments in the call from PhpWiki
131 * @param request Request ???
132 * @param string basepage Pagename to use to interpret links [/relative] page names.
133 * @return string HTML output to be printed to browser
139 function run($dbi, $argstr, &$request, $basepage)
141 $cache = $this->newCache();
142 //$cacheparams = $GLOBALS['CacheParams'];
144 $sortedargs = $this->getArgs($argstr, $request);
145 if (is_array($sortedargs))
147 $this->_args =& $sortedargs;
148 $this->_type = $this->getPluginType();
149 $this->_static = false;
150 if ($this->_type & PLUGIN_CACHED_STATIC
151 or $request->getArg('action') == 'pdf'
152 ) // htmldoc doesn't grok subrequests
154 $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC;
155 $this->_static = true;
158 // ---------- embed static image, no getimg.php? url -----------------
159 if (0 and $this->_static) {
160 //$content = $cache->get($id, 'imagecache');
162 if ($this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html')) {
163 // save the image in uploads
164 return $this->embedImg($content['url'], $dbi, $sortedargs, $request);
166 // copy the cached image into uploads if older
171 list($id, $url) = $this->genUrl($cache, $sortedargs);
172 // ---------- don't check cache: html and img gen. -----------------
173 // override global PLUGIN_CACHED_USECACHE for a plugin
174 if ($this->getPluginType() & PLUGIN_CACHED_IMG_ONDEMAND) {
175 if ($this->_static and $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'))
176 $url = $content['url'];
177 return $this->embedImg($url, $dbi, $sortedargs, $request);
181 $content = $cache->get($id, 'imagecache');
182 switch ($this->_type) {
183 case PLUGIN_CACHED_HTML:
184 if (!$content || !$content['html']) {
186 $content['html'] = $this->getHtml($dbi, $sortedargs, $request, $basepage);
187 if ($errortext = $this->getError()) {
188 $this->printError($errortext, 'html');
194 case PLUGIN_CACHED_IMG_INLINE:
195 if (PLUGIN_CACHED_USECACHE && (!$content || !$content['image'])) { // new
196 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
197 if ($this->_static) $url = $content['url'];
198 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
199 } elseif (!empty($content['url']) && $this->_static) { // already in cache
200 $content['html'] = $this->embedImg($content['url'], $dbi, $sortedargs, $request);
201 } elseif (!empty($content['image']) && $this->_static) { // copy from cache to upload
202 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
203 $url = $content['url'];
204 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
207 case PLUGIN_CACHED_MAP:
208 if (!$content || !$content['image'] || !$content['html']) {
209 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
210 if ($this->_static) $url = $content['url'];
211 $content['html'] = $do_save
212 ? $this->embedMap($id, $url, $content['html'], $dbi, $sortedargs, $request)
216 case PLUGIN_CACHED_SVG:
217 if (!$content || !$content['html']) {
218 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
219 if ($this->_static) $url = $content['url'];
220 $args = array(); //width+height => object args
221 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
222 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
223 $content['html'] = $do_save
224 ? $this->embedObject($url, 'image/svg+xml', $args,
225 HTML::embed(array_merge(
226 array('src' => $url, 'type' => 'image/svg+xml'),
231 case PLUGIN_CACHED_SVG_PNG:
232 if (!$content || !$content['html']) {
233 $do_save_svg = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
234 if ($this->_static) $url = $content['url'];
235 // hack alert! somehow we should know which argument will produce the secondary image (PNG)
237 $args[$this->pngArg()] = $content['imagetype']; // default type: PNG or GIF
238 $do_save = $this->produceImage($pngcontent, $this, $dbi, $args, $request, $content['imagetype']);
239 $args = array(); //width+height => object args
240 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
241 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
242 $content['html'] = $do_save_svg
243 ? $this->embedObject($url, 'image/svg+xml', $args,
244 $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request))
250 $content['args'] = md5($this->_pi);
251 $expire = $this->getExpire($dbi, $content['args'], $request);
252 $cache->save($id, $content, $expire, 'imagecache');
254 if ($content['html'])
255 return $content['html'];
259 /* --------------------- virtual or abstract functions ----------- */
262 * Sets the type of the plugin to html, image or map
266 * @return int determines the plugin to produce either html,
267 * an image or an image map; uses on of the
268 * following predefined values
270 * <li>PLUGIN_CACHED_HTML</li>
271 * <li>PLUGIN_CACHED_IMG_INLINE</li>
272 * <li>PLUGIN_CACHED_IMG_ONDEMAND</li>
273 * <li>PLUGIN_CACHED_MAP</li>
276 function getPluginType()
278 return PLUGIN_CACHED_IMG_ONDEMAND;
282 * Creates an image handle from the given user arguments.
283 * This method is only called if the return value of
284 * <code>getPluginType</code> is set to
285 * PLUGIN_CACHED_IMG_INLINE or PLUGIN_CACHED_IMG_ONDEMAND.
287 * @access protected pure virtual
288 * @param dbi WikiDB database abstraction class
289 * @param argarray array complete (!) arguments to produce
290 * image. It is not necessary to call
291 * WikiPlugin->getArgs anymore.
292 * @param request Request ???
293 * @return imagehandle image handle if successful
294 * false if an error occured
296 function getImage($dbi, $argarray, $request)
298 trigger_error('WikiPluginCached::getImage: pure virtual function in file '
299 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
304 * Sets the life time of a cache entry in seconds.
305 * Expired entries are not used anymore.
306 * During a garbage collection each expired entry is
307 * removed. If removing all expired entries is not
308 * sufficient, the expire time is ignored and removing
309 * is determined by the last "touch" of the entry.
311 * @access protected virtual
312 * @param dbi WikiDB database abstraction class
313 * @param argarray array complete (!) arguments. It is
314 * not necessary to call
315 * WikiPlugin->getArgs anymore.
316 * @param request Request ???
317 * @return string format: '+seconds'
320 function getExpire($dbi, $argarray, $request)
322 return '0'; // persist forever
326 * Decides the image type of an image output.
327 * Always used unless plugin type is PLUGIN_CACHED_HTML.
329 * @access protected virtual
330 * @param dbi WikiDB database abstraction class
331 * @param argarray array complete (!) arguments. It is
332 * not necessary to call
333 * WikiPlugin->getArgs anymore.
334 * @param request Request ???
335 * @return string 'png', 'jpeg' or 'gif'
337 function getImageType(&$dbi, $argarray, &$request)
339 if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
340 return $argarray['imgtype'];
346 * Produces the alt text for an image.
347 * <code> <img src=... alt="getAlt(...)"> </code>
349 * @access protected virtual
350 * @param dbi WikiDB database abstraction class
351 * @param argarray array complete (!) arguments. It is
352 * not necessary to call
353 * WikiPlugin->getArgs anymore.
354 * @param request Request ???
355 * @return string "alt" description of the image
357 function getAlt($dbi, $argarray, $request)
359 return '<?plugin ' . $this->getName() . ' ' . $this->glueArgs($argarray) . '?>';
363 * Creates HTML output to be cached.
364 * This method is only called if the plugin_type is set to
365 * PLUGIN_CACHED_HTML.
367 * @access protected pure virtual
368 * @param dbi WikiDB database abstraction class
369 * @param argarray array complete (!) arguments to produce
370 * image. It is not necessary to call
371 * WikiPlugin->getArgs anymore.
372 * @param request Request ???
373 * @param string $basepage Pagename to use to interpret links [/relative] page names.
374 * @return string html to be printed in place of the plugin command
375 * false if an error occured
377 function getHtml($dbi, $argarray, $request, $basepage)
379 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
380 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
384 * Creates HTML output to be cached.
385 * This method is only called if the plugin_type is set to
386 * PLUGIN_CACHED_HTML.
388 * @access protected pure virtual
389 * @param dbi WikiDB database abstraction class
390 * @param argarray array complete (!) arguments to produce
391 * image. It is not necessary to call
392 * WikiPlugin->getArgs anymore.
393 * @param request Request ???
394 * @return array(html,handle) html for the map interior (to be specific,
395 * only <area;> tags defining hot spots)
396 * handle is an imagehandle to the corresponding
398 * array(false,false) if an error occured
400 function getMap($dbi, $argarray, $request)
402 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
403 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
406 /* --------------------- produce Html ----------------------------- */
409 * Creates an HTML map hyperlinked to the image specified
410 * by url and containing the hotspots given by map.
413 * @param id string unique id for the plugin call
414 * @param url string url pointing to the image part of the map
415 * @param map string <area> tags defining active
417 * @param dbi WikiDB database abstraction class
418 * @param argarray array complete (!) arguments to produce
419 * image. It is not necessary to call
420 * WikiPlugin->getArgs anymore.
421 * @param request Request ???
422 * @return string html output
424 function embedMap($id, $url, $map, &$dbi, $argarray, &$request)
426 // id is not unique if the same map is produced twice
427 $key = substr($id, 0, 8) . substr(microtime(), 0, 6);
428 return HTML(HTML::map(array('name' => $key), $map),
431 // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
432 'usemap' => '#' . $key))
437 * Creates an HTML <img> tag hyperlinking to the specified
438 * url and produces an alternative text for non-graphical
442 * @param url string url pointing to the image part of the map
443 * @param map string <area> tags defining active
445 * @param dbi WikiDB database abstraction class
446 * @param argarray array complete (!) arguments to produce
447 * image. It is not necessary to call
448 * WikiPlugin->getArgs anymore.
449 * @param request Request ???
450 * @return string html output
452 function embedImg($url, $dbi, $argarray, $request)
454 return HTML::img(array(
456 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request))));
461 <object type="audio/x-wav" standby="Loading Audio" data="example.wav">
462 <param name="src" value="example.wav" valuetype="data"></param>
463 <param name="autostart" value="false" valuetype="data"></param>
464 <param name="controls" value="ControlPanel" valuetype="data"></param>
465 <a href="example.wav">Example Audio File</a>
467 * See http://www.protocol7.com/svg-wiki/?EmbedingSvgInHTML
468 <object data="sample.svgz" type="image/svg+xml"
469 width="400" height="300">
470 <embed src="sample.svgz" type="image/svg+xml"
471 width="400" height="300" />
472 <p>Alternate Content like <img src="" /></p>
475 // how to handle alternate images? always provide alternate static images?
476 function embedObject($url, $type, $args = false, $params = false)
478 if (!$args) $args = array();
479 $object = HTML::object(array_merge($args, array('src' => $url, 'type' => $type)));
481 $object->pushContent($params);
485 // --------------------------------------------------------------------------
486 // ---------------------- static member functions ---------------------------
487 // --------------------------------------------------------------------------
490 * Creates one static PEAR Cache object and returns copies afterwards.
491 * FIXME: There should be references returned
493 * @access static protected
494 * @return Cache copy of the cache object
500 if (!is_object($staticcache)) {
501 if (!class_exists('Cache')) {
502 // uuh, pear not in include_path! should print a warning.
503 // search some possible pear paths.
504 $pearFinder = new PearFileFinder;
505 if ($lib = $pearFinder->findFile('Cache.php', 'missing_ok'))
507 else // fall back to our own copy
508 require_once 'lib/pear/Cache.php';
510 $cacheparams = array();
511 foreach (explode(':', 'database:cache_dir:filename_prefix:highwater:lowwater'
512 . ':maxlifetime:maxarglen:usecache:force_syncmap') as $key) {
513 $cacheparams[$key] = constant('PLUGIN_CACHED_' . strtoupper($key));
515 $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES);
516 $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams);
517 $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME;
519 if (!PLUGIN_CACHED_USECACHE) {
520 $staticcache->setCaching(false);
523 return $staticcache; // FIXME: use references ?
527 * Determines whether a needed image type may is available
528 * from the GD library and gives an alternative otherwise.
530 * @access public static
531 * @param wish string one of 'png', 'gif', 'jpeg', 'jpg'
532 * @return string the image type to be used ('png', 'gif', 'jpeg')
533 * 'html' in case of an error
536 function decideImgType($wish)
538 if ($wish == 'html') return $wish;
539 if ($wish == 'jpg') {
543 $supportedtypes = array();
544 // Todo: swf, pdf, ...
551 /* // these do work but not with the ImageType bitmask
557 if (function_exists('ImageTypes')) {
558 $presenttypes = ImageTypes();
559 foreach ($imagetypes as $imgtype => $bitmask)
560 if ($presenttypes && $bitmask)
561 array_push($supportedtypes, $imgtype);
563 foreach ($imagetypes as $imgtype => $bitmask)
564 if (function_exists("Image" . $imgtype))
565 array_push($supportedtypes, $imgtype);
567 if (in_array($wish, $supportedtypes))
569 elseif (!empty($supportedtypes))
570 return reset($supportedtypes); else
576 * Writes an image into a file or to the browser.
577 * Note that there is no check if the image can
580 * @access public static
581 * @param imgtype string 'png', 'gif' or 'jpeg'
582 * @param imghandle string image handle containing the image
583 * @param imgfile string file name of the image to be produced
585 * @see decideImageType
587 function writeImage($imgtype, $imghandle, $imgfile = false)
589 if ($imgtype != 'html') {
590 $func = "Image" . strtoupper($imgtype);
592 $func($imghandle, $imgfile);
600 * Sends HTTP Header for some predefined file types.
601 * There is no parameter check.
603 * @access public static
604 * @param doctype string 'gif', 'png', 'jpeg', 'html'
607 function writeHeader($doctype)
609 static $IMAGEHEADER = array(
610 'gif' => 'Content-type: image/gif',
611 'png' => 'Content-type: image/png',
612 'jpeg' => 'Content-type: image/jpeg',
613 'xbm' => 'Content-type: image/xbm',
614 'xpm' => 'Content-type: image/xpm',
615 'gd' => 'Content-type: image/gd',
616 'gd2' => 'Content-type: image/gd2',
617 'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such.
618 'html' => 'Content-type: text/html');
619 // Todo: swf, pdf, svg, svgz
620 Header($IMAGEHEADER[$doctype]);
624 * Converts argument array to a string of format option="value".
625 * This should only be used for displaying plugin options for
626 * the quoting of arguments is not safe, yet.
628 * @access public static
629 * @param argarray array contains all arguments to be converted
630 * @return string concated arguments
632 function glueArgs($argarray)
634 if (!empty($argarray)) {
636 while (list($key, $value) = each($argarray)) {
637 $argstr .= $key . '=' . '"' . $value . '" ';
638 // FIXME: How are values quoted? Can a value contain '"'?
639 // TODO: rawurlencode(value)
641 return substr($argstr, 0, strlen($argstr) - 1);
646 // ---------------------- FetchImageFromCache ------------------------------
649 * Extracts the cache entry id from the url and the plugin call
650 * parameters if available.
652 * @access private static
653 * @param id string return value. Image is stored under this id.
654 * @param plugincall string return value. Only returned if present in url.
655 * Contains all parameters to reconstruct
657 * @param cache Cache PEAR Cache object
658 * @param request Request ???
659 * @param errorformat string format which should be used to
660 * output errors ('html', 'png', 'gif', 'jpeg')
661 * @return boolean false if an error occurs, true otherwise.
662 * Param id and param plugincall are
663 * also return values.
665 function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat)
667 $id = $request->getArg('id');
668 $plugincall = rawurldecode($request->getArg('args'));
672 // This should never happen, so do not gettextify.
673 $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters.";
674 $this->printError($errorformat, $errortext);
677 $id = $cache->generateId($plugincall);
684 * Extracts the parameters necessary to reconstruct the plugin
685 * call needed to produce the requested image.
687 * @access static private
688 * @param plugincall string reference to serialized array containing both
689 * name and parameters of the plugin call
690 * @param request Request ???
691 * @return boolean false if an error occurs, true otherwise.
694 function checkCall2(&$plugincall, $request)
696 // if plugincall wasn't sent by URL, it must have been
697 // stored in a session var instead and we can retreive it from there
699 if (!$plugincall = $request->getSessionVar('imagecache' . $id)) {
700 // I think this is the only error which may occur
701 // without having written bad code. So gettextify it.
702 $errortext = sprintf(
703 gettext("There is no image creation data available to id '%s'. Please reload referring page."),
705 $this->printError($errorformat, $errortext);
709 $plugincall = unserialize($plugincall);
714 * Creates an image or image map depending on the plugin type.
715 * @access static private
716 * @param content array reference to created array which overwrite the keys
717 * 'image', 'imagetype' and possibly 'html'
718 * @param plugin WikiPluginCached plugin which is called to create image or map
719 * @param dbi WikiDB handle to database
720 * @param argarray array Contains all arguments needed by plugin
721 * @param request Request ????
722 * @param errorformat string outputs errors in 'png', 'gif', 'jpg' or 'html'
723 * @return boolean error status; true=ok; false=error
725 function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat)
727 $plugin->resetError();
728 $content['html'] = $imagehandle = false;
729 if ($plugin->getPluginType() == PLUGIN_CACHED_MAP) {
730 list($imagehandle, $content['html']) = $plugin->getMap($dbi, $argarray, $request);
732 $imagehandle = $plugin->getImage($dbi, $argarray, $request);
735 $content['imagetype']
736 = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request));
737 $errortext = $plugin->getError();
739 if (!$imagehandle || $errortext) {
741 $errortext = "'<?plugin " . $plugin->getName() . ' '
742 . $this->glueArgs($argarray) . " ?>' returned no image, "
743 . " although no error was reported.";
745 $this->printError($errorformat, $errortext);
749 // image handle -> image data
750 if (!empty($this->_static)) {
751 $ext = "." . $content['imagetype'];
752 if (is_string($imagehandle) and file_exists($imagehandle)) {
753 if (preg_match("/.(\w+)$/", $imagehandle, $m)) {
757 $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext);
758 if (!strstr(basename($tmpfile), $ext)) {
762 $tmpfile = getUploadFilePath() . basename($tmpfile);
763 if (is_string($imagehandle) and file_exists($imagehandle)) {
764 rename($imagehandle, $tmpfile);
767 $tmpfile = $this->tempnam();
769 if (is_resource($imagehandle)) {
770 $this->writeImage($content['imagetype'], $imagehandle, $tmpfile);
771 ImageDestroy($imagehandle);
773 } elseif (is_string($imagehandle)) {
774 $content['file'] = getUploadFilePath() . basename($tmpfile);
775 $content['url'] = getUploadDataPath() . basename($tmpfile);
778 if (file_exists($tmpfile)) {
779 $fp = fopen($tmpfile, 'rb');
780 $content['image'] = fread($fp, filesize($tmpfile));
782 if (!empty($this->_static)) {
783 // on static it is in "uploads/" but in wikicached also
784 $content['file'] = $tmpfile;
785 $content['url'] = getUploadDataPath() . basename($tmpfile);
789 if ($content['image'])
795 function staticUrl($tmpfile)
797 $content['file'] = $tmpfile;
798 $content['url'] = getUploadDataPath() . basename($tmpfile);
802 function tempnam($prefix = "")
804 if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) {
808 $ext = isWindows() ? ".tmp" : "";
810 $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR)
811 : PLUGIN_CACHED_CACHE_DIR,
812 $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
814 if ($ext != ".tmp") unlink($temp);
815 $temp = preg_replace("/\.tmp$/", $ext, $temp);
823 * Main function for obtaining images from cache or generating on-the-fly
824 * from parameters sent by url or session vars.
826 * @access static public
827 * @param dbi WikiDB handle to database
828 * @param request Request ???
829 * @param errorformat string outputs errors in 'png', 'gif', 'jpeg' or 'html'
831 function fetchImageFromCache($dbi, $request, $errorformat = 'png')
833 $cache = $this->newCache();
834 $errorformat = $this->decideImgType($errorformat);
836 if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false;
838 $content = $cache->get($id, 'imagecache');
840 if (!empty($content['image'])) {
841 $this->writeHeader($content['imagetype']);
842 print $content['image'];
845 if (!empty($content['html'])) {
846 print $content['html'];
850 if (!empty($content['file']) && !empty($content['url']) && file_exists($content['file'])) {
851 print $this->embedImg($content['url'], $dbi, array(), $request);
855 // re-produce image. At first, we need the plugincall parameters.
856 // Cached args with matching id override given args to shorten getimg.php?id=md5
857 if (!empty($content['args']))
858 $plugincall['arguments'] = $content['args'];
859 if (!$this->checkCall2($plugincall, $request)) return false;
861 $pluginname = $plugincall['pluginname'];
862 $argarray = $plugincall['arguments'];
864 $loader = new WikiPluginLoader;
865 $plugin = $loader->getPlugin($pluginname);
867 // cache empty, but image maps have to be created _inline_
868 // so ask user to reload wiki page instead
869 if (($plugin->getPluginType() & PLUGIN_CACHED_MAP) && PLUGIN_CACHED_FORCE_SYNCMAP) {
870 $errortext = _("Image map expired. Reload wiki page to recreate its html part.");
871 $this->printError($errorformat, $errortext);
874 if (!$this->produceImage($content, $plugin, $dbi, $argarray,
875 $request, $errorformat)
879 $expire = $plugin->getExpire($dbi, $argarray, $request);
881 if ($content['image']) {
882 $cache->save($id, $content, $expire, 'imagecache');
883 $this->writeHeader($content['imagetype']);
884 print $content['image'];
888 $errortext = "Could not create image file from imagehandle.";
889 $this->printError($errorformat, $errortext);
891 } // FetchImageFromCache
893 // -------------------- error handling ----------------------------
896 * Resets buffer containing all error messages. This is allways
897 * done before invoking any abstract creation routines like
898 * <code>getImage</code>.
903 function resetError()
905 $this->_errortext = '';
909 * Returns all accumulated error messages.
912 * @return string error messages printed with <code>complain</code>.
916 return $this->_errortext;
920 * Collects the error messages in a string for later output
921 * by WikiPluginCached. This should be used for any errors
922 * that occur during data (html,image,map) creation.
925 * @param addtext string errormessage to be printed (separate
926 * multiple lines with '\n')
929 function complain($addtext)
931 $this->_errortext .= $addtext;
935 * Outputs the error as image if possible or as html text
936 * if wished or html header has already been sent.
938 * @access static protected
939 * @param imgtype string 'png', 'gif', 'jpeg' or 'html'
940 * @param errortext string guess what?
943 function printError($imgtype, $errortext)
945 $imgtype = $this->decideImgType($imgtype);
947 $talkedallready = ob_get_contents() || headers_sent();
948 if (($imgtype == 'html') || $talkedallready) {
949 if (is_object($errortext))
950 $errortext = $errortext->asXml();
951 trigger_error($errortext, E_USER_WARNING);
953 $red = array(255, 0, 0);
954 $grey = array(221, 221, 221);
955 if (is_object($errortext))
956 $errortext = $errortext->asString();
957 $im = $this->text2img($errortext, 2, $red, $grey);
959 trigger_error($errortext, E_USER_WARNING);
962 $this->writeHeader($imgtype);
963 $this->writeImage($imgtype, $im);
969 * Basic text to image converter for error handling which allows
970 * multiple line output.
971 * It will only output the first 25 lines of 80 characters. Both
972 * values may be smaller if the chosen font is to big for there
973 * is further restriction to 600 pixel in width and 350 in height.
975 * @access static public
976 * @param txt string multi line text to be converted
977 * @param fontnr integer number (1-5) telling gd which internal font to use;
978 * I recommend font 2 for errors and 4 for help texts.
979 * @param textcol array text color as a list of the rgb components; array(red,green,blue)
980 * @param bgcol array background color; array(red,green,blue)
981 * @return string image handle for gd routines
983 function text2img($txt, $fontnr, $textcol, $bgcol)
985 // basic (!) output for error handling
988 if ($fontnr < 1 || $fontnr > 5) {
991 if (!is_array($textcol) || !is_array($bgcol)) {
992 $textcol = array(0, 0, 0);
993 $bgcol = array(255, 255, 255);
995 foreach (array_merge($textcol, $bgcol) as $component) {
996 if ($component < 0 || $component > 255) {
997 $textcol = array(0, 0, 0);
998 $bgcol = array(255, 255, 255);
1003 // prepare Parameters
1005 // set maximum values
1012 if (function_exists('ImageFontWidth')) {
1013 $charx = ImageFontWidth($fontnr);
1014 $chary = ImageFontHeight($fontnr);
1020 $marginy = floor($chary / 2);
1022 $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2 * $marginx) / $charx));
1023 $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2 * $marginy) / $chary));
1029 $len = strlen($txt);
1030 $npos = strpos($txt, "\n");
1032 if ($npos === false) {
1033 $breaklen = min($IMAGESIZE['cols'], $len);
1035 $breaklen = min($npos + 1, $IMAGESIZE['cols']);
1037 $lines[$y] = chop(substr($txt, 0, $breaklen));
1038 $wx = max($wx, strlen($lines[$y++]));
1039 $txt = substr($txt, $breaklen);
1040 } while ($txt && ($y < $IMAGESIZE['rows']));
1042 // recalculate image size
1043 $IMAGESIZE['rows'] = $y;
1044 $IMAGESIZE['cols'] = $wx;
1046 $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2 * $marginx;
1047 $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2 * $marginy;
1049 // create blank image
1050 $im = @ImageCreate($IMAGESIZE['width'], $IMAGESIZE['height']);
1052 $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]);
1053 $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]);
1055 ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width'] - 1, $IMAGESIZE['height'] - 1, $bg);
1058 foreach ($lines as $nr => $textstr) {
1059 ImageString($im, $fontnr, $marginx, $marginy + $nr * $chary,
1065 function newFilterThroughCmd($input, $commandLine)
1067 $descriptorspec = array(
1068 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1069 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
1070 2 => array("pipe", "w"), // stdout is a pipe that the child will write to
1073 $process = proc_open("$commandLine", $descriptorspec, $pipes);
1074 if (is_resource($process)) {
1075 // $pipes now looks like this:
1076 // 0 => writeable handle connected to child stdin
1077 // 1 => readable handle connected to child stdout
1078 // 2 => readable handle connected to child stderr
1079 fwrite($pipes[0], $input);
1082 while (!feof($pipes[1])) {
1083 $buf .= fgets($pipes[1], 1024);
1087 while (!feof($pipes[2])) {
1088 $stderr .= fgets($pipes[2], 1024);
1091 // It is important that you close any pipes before calling
1092 // proc_close in order to avoid a deadlock
1093 $return_value = proc_close($process);
1094 if (empty($buf)) printXML($this->error($stderr));
1099 // run "echo $source | $commandLine" and return result
1100 function filterThroughCmd($source, $commandLine)
1102 return $this->newFilterThroughCmd($source, $commandLine);
1106 * Execute system command and wait until the outfile $until exists.
1108 * @param cmd string command to be invoked
1109 * @param until string expected output filename
1110 * @return boolean error status; true=ok; false=error
1112 function execute($cmd, $until = false)
1114 // cmd must redirect stderr to stdout though!
1115 $errstr = exec($cmd); //, $outarr, $returnval); // normally 127
1116 //$errstr = join('',$outarr);
1117 $ok = empty($errstr);
1119 trigger_error("\n" . $cmd . " failed: $errstr", E_USER_WARNING);
1120 } elseif ($GLOBALS['request']->getArg('debug'))
1121 trigger_error("\n" . $cmd . ": success\n", E_USER_NOTICE);
1125 while (!file_exists($until) and $loop > 0) {
1134 return file_exists($until);
1143 // c-basic-offset: 4
1144 // c-hanging-comment-ender-p: nil
1145 // indent-tabs-mode: nil