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
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.
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
72 * @return array(id,url)
74 * TODO: check if args is needed at all (on lost cache)
76 function genUrl($cache, $argarray) {
78 //$cacheparams = $GLOBALS['CacheParams'];
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
88 $url = DATA_PATH . '/getimg.php?';
89 if (($lastchar = substr($url,-1)) == '/') {
90 $url = substr($url, 0, -1);
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);
97 $plugincall_arg = false; // not needed anymore
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 : '');
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 : '');
113 if ($request->getArg("start_debug") and (DEBUG & _DEBUG_REMOTE))
114 $url .= "&start_debug=1";
115 return array($id, $url);
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,
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
137 function run ($dbi, $argstr, &$request, $basepage) {
138 $cache = $this->newCache();
139 //$cacheparams = $GLOBALS['CacheParams'];
141 $sortedargs = $this->getArgs($argstr, $request);
142 if (is_array($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
150 $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC;
151 $this->_static = true;
154 // ---------- embed static image, no getimg.php? url -----------------
155 if (0 and $this->_static) {
156 //$content = $cache->get($id, 'imagecache');
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);
162 // copy the cached image into uploads if older
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);
177 $content = $cache->get($id, 'imagecache');
178 switch ($this->_type) {
179 case PLUGIN_CACHED_HTML:
180 if (!$content || !$content['html']) {
182 $content['html'] = $this->getHtml($dbi, $sortedargs, $request, $basepage);
183 if ($errortext = $this->getError()) {
184 $this->printError($errortext, 'html');
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;
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)
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'),
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)
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))
246 $content['args'] = md5($this->_pi);
247 $expire = $this->getExpire($dbi, $content['args'], $request);
248 $cache->save($id, $content, $expire, 'imagecache');
250 if ($content['html'])
251 return $content['html'];
255 /* --------------------- virtual or abstract functions ----------- */
258 * Sets the type of the plugin to html, image or map
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
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>
272 function getPluginType() {
273 return PLUGIN_CACHED_IMG_ONDEMAND;
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.
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
291 function getImage($dbi,$argarray,$request) {
292 trigger_error('WikiPluginCached::getImage: pure virtual function in file '
293 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
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.
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'
314 function getExpire($dbi,$argarray,$request) {
315 return '0'; // persist forever
319 * Decides the image type of an image output.
320 * Always used unless plugin type is PLUGIN_CACHED_HTML.
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'
330 function getImageType(&$dbi, $argarray, &$request) {
331 if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
332 return $argarray['imgtype'];
338 * Produces the alt text for an image.
339 * <code> <img src=... alt="getAlt(...)"> </code>
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
349 function getAlt($dbi,$argarray,$request) {
350 return '<?plugin '.$this->getName().' '.$this->glueArgs($argarray).'?>';
354 * Creates HTML output to be cached.
355 * This method is only called if the plugin_type is set to
356 * PLUGIN_CACHED_HTML.
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
368 function getHtml($dbi, $argarray, $request, $basepage) {
369 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
370 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
374 * Creates HTML output to be cached.
375 * This method is only called if the plugin_type is set to
376 * PLUGIN_CACHED_HTML.
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 <area;> tags defining hot spots)
386 * handle is an imagehandle to the corresponding
388 * array(false,false) if an error occured
390 function getMap($dbi, $argarray, $request) {
391 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
392 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
395 /* --------------------- produce Html ----------------------------- */
398 * Creates an HTML map hyperlinked to the image specified
399 * by url and containing the hotspots given by map.
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 <area> tags defining active
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
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 ),
419 // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
420 'usemap' => '#'.$key ))
425 * Creates an HTML <img> tag hyperlinking to the specified
426 * url and produces an alternative text for non-graphical
430 * @param url string url pointing to the image part of the map
431 * @param map string <area> tags defining active
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
440 function embedImg($url, $dbi, $argarray, $request) {
441 return HTML::img( array(
443 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request)) ) );
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>
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>
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)));
467 $object->pushContent($params);
471 // --------------------------------------------------------------------------
472 // ---------------------- static member functions ---------------------------
473 // --------------------------------------------------------------------------
476 * Creates one static PEAR Cache object and returns copies afterwards.
477 * FIXME: There should be references returned
479 * @access static protected
480 * @return Cache copy of the cache object
482 function newCache() {
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'))
492 else // fall back to our own copy
493 require_once('lib/pear/Cache.php');
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));
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;
504 if (! PLUGIN_CACHED_USECACHE ) {
505 $staticcache->setCaching(false);
508 return $staticcache; // FIXME: use references ?
512 * Determines whether a needed image type may is available
513 * from the GD library and gives an alternative otherwise.
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
521 function decideImgType($wish) {
522 if ($wish=='html') return $wish;
523 if ($wish=='jpg') { $wish = 'jpeg'; }
525 $supportedtypes = array();
526 // Todo: swf, pdf, ...
533 /* // these do work but not with the ImageType bitmask
539 if (function_exists('ImageTypes')) {
540 $presenttypes = ImageTypes();
541 foreach ($imagetypes as $imgtype => $bitmask)
542 if ( $presenttypes && $bitmask )
543 array_push($supportedtypes, $imgtype);
545 foreach ($imagetypes as $imgtype => $bitmask)
546 if (function_exists("Image".$imgtype))
547 array_push($supportedtypes, $imgtype);
549 if (in_array($wish, $supportedtypes))
551 elseif (!empty($supportedtypes))
552 return reset($supportedtypes);
559 * Writes an image into a file or to the browser.
560 * Note that there is no check if the image can
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
568 * @see decideImageType
570 function writeImage($imgtype, $imghandle, $imgfile=false) {
571 if ($imgtype != 'html') {
572 $func = "Image" . strtoupper($imgtype);
574 $func($imghandle,$imgfile);
582 * Sends HTTP Header for some predefined file types.
583 * There is no parameter check.
585 * @access public static
586 * @param doctype string 'gif', 'png', 'jpeg', 'html'
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]);
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.
610 * @access public static
611 * @param argarray array contains all arguments to be converted
612 * @return string concated arguments
614 function glueArgs($argarray) {
615 if (!empty($argarray)) {
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)
622 return substr($argstr, 0, strlen($argstr)-1);
627 // ---------------------- FetchImageFromCache ------------------------------
630 * Extracts the cache entry id from the url and the plugin call
631 * parameters if available.
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
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.
646 function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat) {
647 $id = $request->getArg('id');
648 $plugincall = rawurldecode($request->getArg('args'));
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);
657 $id = $cache->generateId( $plugincall );
665 * Extracts the parameters necessary to reconstruct the plugin
666 * call needed to produce the requested image.
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.
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
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." ),
685 $this->printError($errorformat, $errortext);
689 $plugincall = unserialize($plugincall);
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
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);
712 $imagehandle = $plugin->getImage($dbi, $argarray, $request);
715 $content['imagetype']
716 = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request));
717 $errortext = $plugin->getError();
719 if (!$imagehandle||$errortext) {
721 $errortext = "'<?plugin ".$plugin->getName(). ' '
722 . $this->glueArgs($argarray)." ?>' returned no image, "
723 . " although no error was reported.";
725 $this->printError($errorformat, $errortext);
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)) {
737 $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext);
738 if (!strstr(basename($tmpfile), $ext)) {
742 $tmpfile = getUploadFilePath() . basename($tmpfile);
743 if (is_string($imagehandle) and file_exists($imagehandle)) {
744 rename($imagehandle, $tmpfile);
747 $tmpfile = $this->tempnam();
749 if (is_resource($imagehandle)) {
750 $this->writeImage($content['imagetype'], $imagehandle, $tmpfile);
751 ImageDestroy($imagehandle);
753 } elseif (is_string($imagehandle)) {
754 $content['file'] = getUploadFilePath() . basename($tmpfile);
755 $content['url'] = getUploadDataPath() . basename($tmpfile);
758 if (file_exists($tmpfile)) {
759 $fp = fopen($tmpfile,'rb');
760 $content['image'] = fread($fp, filesize($tmpfile));
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);
769 if ($content['image'])
775 function staticUrl ($tmpfile) {
776 $content['file'] = $tmpfile;
777 $content['url'] = getUploadDataPath() . basename($tmpfile);
781 function tempnam($prefix = "") {
782 if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) {
786 $ext = isWindows()? ".tmp" : "";
788 $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR)
789 : PLUGIN_CACHED_CACHE_DIR,
790 $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
792 if ($ext != ".tmp") unlink($temp);
793 $temp = preg_replace("/\.tmp$/", $ext, $temp);
801 * Main function for obtaining images from cache or generating on-the-fly
802 * from parameters sent by url or session vars.
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'
809 function fetchImageFromCache($dbi, $request, $errorformat='png') {
810 $cache = $this->newCache();
811 $errorformat = $this->decideImgType($errorformat);
813 if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false;
815 $content = $cache->get($id, 'imagecache');
817 if (!empty($content['image'])) {
818 $this->writeHeader($content['imagetype']);
819 print $content['image'];
822 if (!empty($content['html'])) {
823 print $content['html'];
827 if (!empty($content['file']) && !empty($content['url']) && file_exists($content['file'])) {
828 print $this->embedImg($content['url'], $dbi, array(), $request);
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;
838 $pluginname = $plugincall['pluginname'];
839 $argarray = $plugincall['arguments'];
841 $loader = new WikiPluginLoader;
842 $plugin = $loader->getPlugin($pluginname);
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);
851 if (!$this->produceImage($content, $plugin, $dbi, $argarray,
852 $request, $errorformat))
855 $expire = $plugin->getExpire($dbi, $argarray, $request);
857 if ($content['image']) {
858 $cache->save($id, $content, $expire, 'imagecache');
859 $this->writeHeader($content['imagetype']);
860 print $content['image'];
864 $errortext = "Could not create image file from imagehandle.";
865 $this->printError($errorformat, $errortext);
867 } // FetchImageFromCache
869 // -------------------- error handling ----------------------------
872 * Resets buffer containing all error messages. This is allways
873 * done before invoking any abstract creation routines like
874 * <code>getImage</code>.
879 function resetError() {
880 $this->_errortext = '';
884 * Returns all accumulated error messages.
887 * @return string error messages printed with <code>complain</code>.
889 function getError() {
890 return $this->_errortext;
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.
899 * @param addtext string errormessage to be printed (separate
900 * multiple lines with '\n')
903 function complain($addtext) {
904 $this->_errortext .= $addtext;
908 * Outputs the error as image if possible or as html text
909 * if wished or html header has already been sent.
911 * @access static protected
912 * @param imgtype string 'png', 'gif', 'jpeg' or 'html'
913 * @param errortext string guess what?
916 function printError($imgtype, $errortext) {
917 $imgtype = $this->decideImgType($imgtype);
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);
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);
931 trigger_error($errortext, E_USER_WARNING);
934 $this->writeHeader($imgtype);
935 $this->writeImage($imgtype, $im);
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.
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
956 function text2img($txt,$fontnr,$textcol,$bgcol) {
957 // basic (!) output for error handling
960 if ($fontnr<1 || $fontnr>5) {
963 if (!is_array($textcol) || !is_array($bgcol)) {
964 $textcol = array(0,0,0);
965 $bgcol = array(255,255,255);
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);
975 // prepare Parameters
977 // set maximum values
984 if (function_exists('ImageFontWidth')) {
985 $charx = ImageFontWidth($fontnr);
986 $chary = ImageFontHeight($fontnr);
988 $charx = 10; $chary = 10;
991 $marginy = floor($chary/2);
993 $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2*$marginx )/$charx));
994 $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2*$marginy )/$chary));
1000 $len = strlen($txt);
1001 $npos = strpos($txt, "\n");
1003 if ($npos===false) {
1004 $breaklen = min($IMAGESIZE['cols'],$len);
1006 $breaklen = min($npos+1, $IMAGESIZE['cols']);
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']));
1013 // recalculate image size
1014 $IMAGESIZE['rows'] = $y;
1015 $IMAGESIZE['cols'] = $wx;
1017 $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2*$marginx;
1018 $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2*$marginy;
1020 // create blank image
1021 $im = @ImageCreate($IMAGESIZE['width'],$IMAGESIZE['height']);
1023 $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]);
1024 $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]);
1026 ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width']-1, $IMAGESIZE['height']-1, $bg);
1029 foreach($lines as $nr => $textstr) {
1030 ImageString( $im, $fontnr, $marginx, $marginy+$nr*$chary,
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
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);
1052 while(!feof($pipes[1])) {
1053 $buf .= fgets($pipes[1], 1024);
1057 while(!feof($pipes[2])) {
1058 $stderr .= fgets($pipes[2], 1024);
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));
1069 // run "echo $source | $commandLine" and return result
1070 function filterThroughCmd($source, $commandLine) {
1071 return $this->newFilterThroughCmd($source, $commandLine);
1075 * Execute system command and wait until the outfile $until exists.
1077 * @param cmd string command to be invoked
1078 * @param until string expected output filename
1079 * @return boolean error status; true=ok; false=error
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);
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);
1093 while (!file_exists($until) and $loop > 0) {
1102 return file_exists($until);
1111 // c-basic-offset: 4
1112 // c-hanging-comment-ender-p: nil
1113 // indent-tabs-mode: nil