1 <?php rcs_id('$Id: WikiPluginCached.php,v 1.17 2004-10-12 15:06:02 rurban Exp $');
3 Copyright (C) 2002 Johannes Große (Johannes Große)
4 Copyright (C) 2004 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
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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!
32 // Try the system pear class. See newCache()
33 @require_once('Cache.php');
36 define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation)
37 define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images
38 define('PLUGIN_CACHED_MAP', 2); // area maps
39 define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object
40 define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback
41 define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object
42 define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?)
43 define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?)
45 define('PLUGIN_CACHED_IMG_ONDEMAND', 64); // don't cache
46 define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id=
49 * An extension of the WikiPlugin class to allow image output and
51 * There are several abstract functions to be overloaded.
52 * Have a look at the example files
53 * <ul><li>plugin/TexToPng.php</li>
54 * <li>plugin/CacheTest.php (extremely simple example)</li>
55 * <li>plugin/RecentChangesCached.php</li>
56 * <li>plugin/VisualWiki.php</li>
57 * <li>plugin/Ploticus.php</li>
60 * @author Johannes Große, Reini Urban
62 class WikiPluginCached extends WikiPlugin
66 * Produces URL and id number from plugin arguments which later on,
67 * will allow to find a cached image or to reconstruct the complete
68 * plugin call to recreate the image.
70 * @param cache object the cache object used to store the images
71 * @param argarray array all parameters (including those set to
72 * default values) of the plugin call to be
75 * @return array(id,url)
77 * TODO: check if args is needed at all (on lost cache)
79 function genUrl($cache, $argarray) {
81 //$cacheparams = $GLOBALS['CacheParams'];
83 $plugincall = serialize( array(
84 'pluginname' => $this->getName(),
85 'arguments' => $argarray ) );
86 $id = $cache->generateId( $plugincall );
87 $plugincall_arg = rawurlencode($plugincall);
88 //$plugincall_arg = md5($plugincall); // will not work if plugin has to recreate content and cache is lost
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"))
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) {
140 $cache = $this->newCache();
141 //$cacheparams = $GLOBALS['CacheParams'];
143 $sortedargs = $this->getArgs($argstr, $request);
144 if (is_array($sortedargs) )
146 $this->_args =& $sortedargs;
147 $this->_type = $this->getPluginType();
148 $this->_static = false;
149 if ($this->_type & PLUGIN_CACHED_STATIC
150 or $request->getArg('action') == 'pdf') // htmldoc doesn't grok subrequests
152 $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC;
153 $this->_static = true;
156 // ---------- embed static image, no getimg.php? url -----------------
157 if (0 and $this->_static) {
158 //$content = $cache->get($id, 'imagecache');
160 if ($this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html')) {
161 // save the image in uploads
162 return $this->embedImg($content['url'], $dbi, $sortedargs, $request);
164 // copy the cached image into uploads if older
169 list($id, $url) = $this->genUrl($cache, $sortedargs);
170 // ---------- don't check cache: html and img gen. -----------------
171 // override global PLUGIN_CACHED_USECACHE for a plugin
172 if ($this->getPluginType() & PLUGIN_CACHED_IMG_ONDEMAND) {
173 if ($this->_static and $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'))
174 $url = $content['url'];
175 return $this->embedImg($url, $dbi, $sortedargs, $request);
179 $content = $cache->get($id, 'imagecache');
180 switch ($this->_type) {
181 case PLUGIN_CACHED_HTML:
182 if (!$content || !$content['html']) {
184 $content['html'] = $this->getHtml($dbi, $sortedargs, $request, $basepage);
185 if ($errortext = $this->getError()) {
186 $this->printError($errortext, 'html');
192 case PLUGIN_CACHED_IMG_INLINE:
193 if (PLUGIN_CACHED_USECACHE && (!$content || !$content['image'])) { // new
194 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
195 if ($this->_static) $url = $content['url'];
196 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
197 } elseif (!empty($content['url']) && $this->_static) { // already in cache
198 $content['html'] = $this->embedImg($content['url'], $dbi, $sortedargs, $request);
199 } elseif (!empty($content['image']) && $this->_static) { // copy from cache to upload
200 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
201 $url = $content['url'];
202 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
205 case PLUGIN_CACHED_MAP:
206 if (!$content || !$content['image'] || !$content['html'] ) {
207 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
208 if ($this->_static) $url = $content['url'];
209 $content['html'] = $do_save
210 ? $this->embedMap($id, $url, $content['html'], $dbi, $sortedargs, $request)
214 case PLUGIN_CACHED_SVG:
215 if (!$content || !$content['html'] ) {
216 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
217 if ($this->_static) $url = $content['url'];
218 $args = array(); //width+height => object args
219 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
220 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
221 $content['html'] = $do_save
222 ? $this->embedObject($url, 'image/svg+xml', $args,
223 HTML::embed(array_merge(
224 array('src'=>$url, 'type'=>'image/svg+xml'),
229 case PLUGIN_CACHED_SVG_PNG:
230 if (!$content || !$content['html'] ) {
231 $do_save_svg = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
232 if ($this->_static) $url = $content['url'];
233 // hack alert! somehow we should know which argument will produce the secondary image (PNG)
235 $args[$this->pngArg()] = $content['imagetype']; // default type: PNG or GIF
236 $do_save = $this->produceImage($pngcontent, $this, $dbi, $args, $request, $content['imagetype']);
237 $args = array(); //width+height => object args
238 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
239 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
240 $content['html'] = $do_save_svg
241 ? $this->embedObject($url, 'image/svg+xml', $args,
242 $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request))
248 $expire = $this->getExpire($dbi, $sortedargs, $request);
249 $content['args'] = $sortedargs;
250 $cache->save($id, $content, $expire, 'imagecache');
252 if ($content['html'])
253 return $content['html'];
258 /* --------------------- virtual or abstract functions ----------- */
261 * Sets the type of the plugin to html, image or map
265 * @return int determines the plugin to produce either html,
266 * an image or an image map; uses on of the
267 * following predefined values
269 * <li>PLUGIN_CACHED_HTML</li>
270 * <li>PLUGIN_CACHED_IMG_INLINE</li>
271 * <li>PLUGIN_CACHED_IMG_ONDEMAND</li>
272 * <li>PLUGIN_CACHED_MAP</li>
275 function getPluginType() {
276 return PLUGIN_CACHED_IMG_ONDEMAND;
280 * Creates an image handle from the given user arguments.
281 * This method is only called if the return value of
282 * <code>getPluginType</code> is set to
283 * PLUGIN_CACHED_IMG_INLINE or PLUGIN_CACHED_IMG_ONDEMAND.
285 * @access protected pure virtual
286 * @param dbi WikiDB database abstraction class
287 * @param argarray array complete (!) arguments to produce
288 * image. It is not necessary to call
289 * WikiPlugin->getArgs anymore.
290 * @param request Request ???
291 * @return imagehandle image handle if successful
292 * false if an error occured
294 function getImage($dbi,$argarray,$request) {
295 trigger_error('WikiPluginCached::getImage: pure virtual function in file '
296 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
301 * Sets the life time of a cache entry in seconds.
302 * Expired entries are not used anymore.
303 * During a garbage collection each expired entry is
304 * removed. If removing all expired entries is not
305 * sufficient, the expire time is ignored and removing
306 * is determined by the last "touch" of the entry.
308 * @access protected virtual
309 * @param dbi WikiDB database abstraction class
310 * @param argarray array complete (!) arguments. It is
311 * not necessary to call
312 * WikiPlugin->getArgs anymore.
313 * @param request Request ???
314 * @return string format: '+seconds'
317 function getExpire($dbi,$argarray,$request) {
318 return '0'; // persist forever
322 * Decides the image type of an image output.
323 * Always used unless plugin type is PLUGIN_CACHED_HTML.
325 * @access protected virtual
326 * @param dbi WikiDB database abstraction class
327 * @param argarray array complete (!) arguments. It is
328 * not necessary to call
329 * WikiPlugin->getArgs anymore.
330 * @param request Request ???
331 * @return string 'png', 'jpeg' or 'gif'
333 function getImageType(&$dbi, $argarray, &$request) {
334 if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
335 return $argarray['imgtype'];
341 * Produces the alt text for an image.
342 * <code> <img src=... alt="getAlt(...)"> </code>
344 * @access protected virtual
345 * @param dbi WikiDB database abstraction class
346 * @param argarray array complete (!) arguments. It is
347 * not necessary to call
348 * WikiPlugin->getArgs anymore.
349 * @param request Request ???
350 * @return string "alt" description of the image
352 function getAlt($dbi,$argarray,$request) {
353 return '<?plugin '.$this->getName().' '.$this->glueArgs($argarray).'?>';
357 * Creates HTML output to be cached.
358 * This method is only called if the plugin_type is set to
359 * PLUGIN_CACHED_HTML.
361 * @access protected pure virtual
362 * @param dbi WikiDB database abstraction class
363 * @param argarray array complete (!) arguments to produce
364 * image. It is not necessary to call
365 * WikiPlugin->getArgs anymore.
366 * @param request Request ???
367 * @param string $basepage Pagename to use to interpret links [/relative] page names.
368 * @return string html to be printed in place of the plugin command
369 * false if an error occured
371 function getHtml($dbi, $argarray, $request, $basepage) {
372 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
373 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
377 * Creates HTML output to be cached.
378 * This method is only called if the plugin_type is set to
379 * PLUGIN_CACHED_HTML.
381 * @access protected pure virtual
382 * @param dbi WikiDB database abstraction class
383 * @param argarray array complete (!) arguments to produce
384 * image. It is not necessary to call
385 * WikiPlugin->getArgs anymore.
386 * @param request Request ???
387 * @return array(html,handle) html for the map interior (to be specific,
388 * only <area;> tags defining hot spots)
389 * handle is an imagehandle to the corresponding
391 * array(false,false) if an error occured
393 function getMap($dbi, $argarray, $request) {
394 trigger_error('WikiPluginCached::getHtml: pure virtual function in file '
395 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
398 /* --------------------- produce Html ----------------------------- */
401 * Creates an HTML map hyperlinked to the image specified
402 * by url and containing the hotspots given by map.
405 * @param id string unique id for the plugin call
406 * @param url string url pointing to the image part of the map
407 * @param map string <area> tags defining active
409 * @param dbi WikiDB database abstraction class
410 * @param argarray array complete (!) arguments to produce
411 * image. It is not necessary to call
412 * WikiPlugin->getArgs anymore.
413 * @param request Request ???
414 * @return string html output
416 function embedMap($id,$url,$map,&$dbi,$argarray,&$request) {
417 // id is not unique if the same map is produced twice
418 $key = substr($id,0,8).substr(microtime(),0,6);
419 return HTML(HTML::map(array( 'name' => $key ), $map ),
422 // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
423 'usemap' => '#'.$key ))
428 * Creates an HTML <img> tag hyperlinking to the specified
429 * url and produces an alternative text for non-graphical
433 * @param url string url pointing to the image part of the map
434 * @param map string <area> tags defining active
436 * @param dbi WikiDB database abstraction class
437 * @param argarray array complete (!) arguments to produce
438 * image. It is not necessary to call
439 * WikiPlugin->getArgs anymore.
440 * @param request Request ???
441 * @return string html output
443 function embedImg($url, $dbi, $argarray, $request) {
444 return HTML::img( array(
446 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request)) ) );
451 <object type="audio/x-wav" standby="Loading Audio" data="example.wav">
452 <param name="src" value="example.wav" valuetype="data"></param>
453 <param name="autostart" value="false" valuetype="data"></param>
454 <param name="controls" value="ControlPanel" valuetype="data"></param>
455 <a href="example.wav">Example Audio File</a>
457 * See http://www.protocol7.com/svg-wiki/?EmbedingSvgInHTML
458 <object data="sample.svgz" type="image/svg+xml"
459 width="400" height="300">
460 <embed src="sample.svgz" type="image/svg+xml"
461 width="400" height="300" />
462 <p>Alternate Content like <img src="" /></p>
465 // how to handle alternate images? always provide alternate static images?
466 function embedObject($url, $type, $args = false, $params = false) {
467 if (!$args) $args = array();
468 $object = HTML::object(array_merge($args, array('src' => $url, 'type' => $type)));
470 $object->pushContent($params);
475 // --------------------------------------------------------------------------
476 // ---------------------- static member functions ---------------------------
477 // --------------------------------------------------------------------------
480 * Creates one static PEAR Cache object and returns copies afterwards.
481 * FIXME: There should be references returned
483 * @access static protected
484 * @return Cache copy of the cache object
486 function newCache() {
489 if (!is_object($staticcache)) {
490 if (!class_exists('Cache')) {
491 // uuh, pear not in include_path! should print a warning.
492 // search some possible pear paths.
493 $pearFinder = new PearFileFinder;
494 if ($lib = $pearFinder->findFile('Cache.php', 'missing_ok'))
496 else // fall back to our own copy
497 require_once('lib/pear/Cache.php');
499 $cacheparams = array();
500 foreach (explode(':','database:cache_dir:filename_prefix:highwater:lowwater'
501 .':maxlifetime:maxarglen:usecache:force_syncmap') as $key) {
502 $cacheparams[$key] = constant('PLUGIN_CACHED_'.strtoupper($key));
504 $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES);
505 $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams);
506 $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME;
508 if (! PLUGIN_CACHED_USECACHE ) {
509 $staticcache->setCaching(false);
512 return $staticcache; // FIXME: use references ?
516 * Determines whether a needed image type may is available
517 * from the GD library and gives an alternative otherwise.
519 * @access public static
520 * @param wish string one of 'png', 'gif', 'jpeg', 'jpg'
521 * @return string the image type to be used ('png', 'gif', 'jpeg')
522 * 'html' in case of an error
525 function decideImgType($wish) {
526 if ($wish=='html') return $wish;
527 if ($wish=='jpg') { $wish = 'jpeg'; }
529 $supportedtypes = array();
530 // Todo: swf, pdf, ...
537 /* // these do work but not with the ImageType bitmask
544 $presenttypes = ImageTypes();
545 foreach($imagetypes as $imgtype => $bitmask)
546 if ( $presenttypes && $bitmask )
547 array_push($supportedtypes, $imgtype);
549 if (in_array($wish, $supportedtypes))
551 elseif (!empty($supportedtypes))
552 return reset($supportedtypes);
560 * Writes an image into a file or to the browser.
561 * Note that there is no check if the image can
564 * @access public static
565 * @param imgtype string 'png', 'gif' or 'jpeg'
566 * @param imghandle string image handle containing the image
567 * @param imgfile string file name of the image to be produced
569 * @see decideImageType
571 function writeImage($imgtype, $imghandle, $imgfile=false) {
572 if ($imgtype != 'html') {
573 $func = "Image" . strtoupper($imgtype);
575 $func($imghandle,$imgfile);
584 * Sends HTTP Header for some predefined file types.
585 * There is no parameter check.
587 * @access public static
588 * @param doctype string 'gif', 'png', 'jpeg', 'html'
591 function writeHeader($doctype) {
592 static $IMAGEHEADER = array(
593 'gif' => 'Content-type: image/gif',
594 'png' => 'Content-type: image/png',
595 'jpeg' => 'Content-type: image/jpeg',
596 'xbm' => 'Content-type: image/xbm',
597 'xpm' => 'Content-type: image/xpm',
598 'gd' => 'Content-type: image/gd',
599 'gd2' => 'Content-type: image/gd2',
600 'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such.
601 'html' => 'Content-type: text/html' );
602 // Todo: swf, pdf, svg, svgz
603 Header($IMAGEHEADER[$doctype]);
608 * Converts argument array to a string of format option="value".
609 * This should only be used for displaying plugin options for
610 * the quoting of arguments is not safe, yet.
612 * @access public static
613 * @param argarray array contains all arguments to be converted
614 * @return string concated arguments
616 function glueArgs($argarray) {
617 if (!empty($argarray)) {
619 while (list($key,$value)=each($argarray)) {
620 $argstr .= $key. '=' . '"' . $value . '" ';
621 // FIXME: How are values quoted? Can a value contain '"'?
622 // TODO: rawurlencode(value)
624 return substr($argstr, 0, strlen($argstr)-1);
629 // ---------------------- FetchImageFromCache ------------------------------
632 * Extracts the cache entry id from the url and the plugin call
633 * parameters if available.
635 * @access private static
636 * @param id string return value. Image is stored under this id.
637 * @param plugincall string return value. Only returned if present in url.
638 * Contains all parameters to reconstruct
640 * @param cache Cache PEAR Cache object
641 * @param request Request ???
642 * @param errorformat string format which should be used to
643 * output errors ('html', 'png', 'gif', 'jpeg')
644 * @return boolean false if an error occurs, true otherwise.
645 * Param id and param plugincall are
646 * also return values.
648 function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat) {
649 $id = $request->getArg('id');
650 $plugincall = rawurldecode($request->getArg('args'));
654 // This should never happen, so do not gettextify.
655 $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters.";
656 $this->printError($errorformat, $errortext);
659 $id = $cache->generateId( $plugincall );
667 * Extracts the parameters necessary to reconstruct the plugin
668 * call needed to produce the requested image.
670 * @access static private
671 * @param plugincall string reference to serialized array containing both
672 * name and parameters of the plugin call
673 * @param request Request ???
674 * @return boolean false if an error occurs, true otherwise.
677 function checkCall2(&$plugincall, $request) {
678 // if plugincall wasn't sent by URL, it must have been
679 // stored in a session var instead and we can retreive it from there
681 if (!$plugincall=$request->getSessionVar('imagecache'.$id)) {
682 // I think this is the only error which may occur
683 // without having written bad code. So gettextify it.
684 $errortext = sprintf(
685 gettext ("There is no image creation data available to id '%s'. Please reload referring page." ),
687 $this->printError($errorformat, $errortext);
691 $plugincall = unserialize($plugincall);
697 * Creates an image or image map depending on the plugin type.
698 * @access static private
699 * @param content array reference to created array which overwrite the keys
700 * 'image', 'imagetype' and possibly 'html'
701 * @param plugin WikiPluginCached plugin which is called to create image or map
702 * @param dbi WikiDB handle to database
703 * @param argarray array Contains all arguments needed by plugin
704 * @param request Request ????
705 * @param errorformat string outputs errors in 'png', 'gif', 'jpg' or 'html'
706 * @return boolean error status; true=ok; false=error
708 function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat) {
709 $plugin->resetError();
710 $content['html'] = $imagehandle = false;
711 if ($plugin->getPluginType() == PLUGIN_CACHED_MAP ) {
712 list($imagehandle,$content['html']) = $plugin->getMap($dbi, $argarray, $request);
714 $imagehandle = $plugin->getImage($dbi, $argarray, $request);
717 $content['imagetype']
718 = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request));
719 $errortext = $plugin->getError();
721 if (!$imagehandle||$errortext) {
723 $errortext = "'<?plugin ".$plugin->getName(). ' '
724 . $this->glueArgs($argarray)." ?>' returned no image, "
725 . " although no error was reported.";
727 $this->printError($errorformat, $errortext);
731 // image handle -> image data
732 if (!empty($this->_static)) {
733 $ext = "." . $content['imagetype'];
734 if (is_string($imagehandle) and file_exists($imagehandle)) {
735 if (preg_match("/.(\w+)$/",$imagehandle,$m)) {
739 $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext);
740 if (!strstr(basename($tmpfile), $ext)) {
744 $tmpfile = getUploadFilePath() . basename($tmpfile);
745 if (is_string($imagehandle) and file_exists($imagehandle)) {
746 rename($imagehandle, $tmpfile);
749 $tmpfile = $this->tempnam();
751 if (is_resource($imagehandle)) {
752 $this->writeImage($content['imagetype'], $imagehandle, $tmpfile);
753 ImageDestroy($imagehandle);
755 } elseif (is_string($imagehandle)) {
756 $content['file'] = getUploadFilePath() . basename($tmpfile);
757 $content['url'] = getUploadDataPath() . basename($tmpfile);
760 if (file_exists($tmpfile)) {
761 $fp = fopen($tmpfile,'rb');
762 $content['image'] = fread($fp, filesize($tmpfile));
764 if (!empty($this->_static)) {
765 // on static it is in "uploads/" but in wikicached also
766 $content['file'] = $tmpfile;
767 $content['url'] = getUploadDataPath() . basename($tmpfile);
771 if ($content['image'])
777 function staticUrl ($tmpfile) {
778 $content['file'] = $tmpfile;
779 $content['url'] = getUploadDataPath() . basename($tmpfile);
783 function tempnam($prefix = false) {
784 return tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR) : PLUGIN_CACHED_CACHE_DIR,
785 $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
789 * Main function for obtaining images from cache or generating on-the-fly
790 * from parameters sent by url or session vars.
792 * @access static public
793 * @param dbi WikiDB handle to database
794 * @param request Request ???
795 * @param errorformat string outputs errors in 'png', 'gif', 'jpeg' or 'html'
797 function fetchImageFromCache($dbi, $request, $errorformat='png') {
798 $cache = $this->newCache();
799 $errorformat = $this->decideImgType($errorformat);
801 if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false;
803 $content = $cache->get($id, 'imagecache');
805 if (!empty($content['image'])) {
806 $this->writeHeader($content['imagetype']);
807 print $content['image'];
810 if (!empty($content['html'])) {
811 print $content['html'];
815 if (!empty($content['file']) && !empty($content['url']) && file_exists($content['file'])) {
816 print $this->embedImg($content['url'], $dbi, array(), $request);
820 // re-produce image. At first, we need the plugincall parameters.
821 // Cached args with matching id override given args to shorten getimg.php?id=md5
822 if (!empty($content['args']))
823 $plugincall['arguments'] = $content['args'];
824 if (!$this->checkCall2($plugincall, $request)) return false;
826 $pluginname = $plugincall['pluginname'];
827 $argarray = $plugincall['arguments'];
829 $loader = new WikiPluginLoader;
830 $plugin = $loader->getPlugin($pluginname);
832 // cache empty, but image maps have to be created _inline_
833 // so ask user to reload wiki page instead
834 if (($plugin->getPluginType() & PLUGIN_CACHED_MAP) && PLUGIN_CACHED_FORCE_SYNCMAP) {
835 $errortext = _("Image map expired. Reload wiki page to recreate its html part.");
836 $this->printError($errorformat, $errortext);
839 if (!$this->produceImage($content, $plugin, $dbi, $argarray,
840 $request, $errorformat))
843 $expire = $plugin->getExpire($dbi, $argarray, $request);
845 if ($content['image']) {
846 $cache->save($id, $content, $expire, 'imagecache');
847 $this->writeHeader($content['imagetype']);
848 print $content['image'];
852 $errortext = "Could not create image file from imagehandle.";
853 $this->printError($errorformat, $errortext);
855 } // FetchImageFromCache
857 // -------------------- error handling ----------------------------
860 * Resets buffer containing all error messages. This is allways
861 * done before invoking any abstract creation routines like
862 * <code>getImage</code>.
867 function resetError() {
868 $this->_errortext = '';
872 * Returns all accumulated error messages.
875 * @return string error messages printed with <code>complain</code>.
877 function getError() {
878 return $this->_errortext;
882 * Collects the error messages in a string for later output
883 * by WikiPluginCached. This should be used for any errors
884 * that occur during data (html,image,map) creation.
887 * @param addtext string errormessage to be printed (separate
888 * multiple lines with '\n')
891 function complain($addtext) {
892 $this->_errortext .= $addtext;
896 * Outputs the error as image if possible or as html text
897 * if wished or html header has already been sent.
899 * @access static protected
900 * @param imgtype string 'png', 'gif', 'jpeg' or 'html'
901 * @param errortext string guess what?
904 function printError($imgtype, $errortext) {
905 $imgtype = $this->decideImgType($imgtype);
907 $talkedallready = ob_get_contents() || headers_sent();
908 if (($imgtype=='html') || $talkedallready) {
909 if (is_object($errortext))
910 $errortext = $errortext->asXml();
911 trigger_error($errortext, E_USER_WARNING);
913 $red = array(255,0,0);
914 $grey = array(221,221,221);
915 if (is_object($errortext))
916 $errortext = $errortext->asString();
917 $im = $this->text2img($errortext, 2, $red, $grey);
919 trigger_error($errortext, E_USER_WARNING);
922 $this->writeHeader($imgtype);
923 $this->writeImage($imgtype, $im);
930 * Basic text to image converter for error handling which allows
931 * multiple line output.
932 * It will only output the first 25 lines of 80 characters. Both
933 * values may be smaller if the chosen font is to big for there
934 * is further restriction to 600 pixel in width and 350 in height.
936 * @access static public
937 * @param txt string multi line text to be converted
938 * @param fontnr integer number (1-5) telling gd which internal font to use;
939 * I recommend font 2 for errors and 4 for help texts.
940 * @param textcol array text color as a list of the rgb components; array(red,green,blue)
941 * @param bgcol array background color; array(red,green,blue)
942 * @return string image handle for gd routines
944 function text2img($txt,$fontnr,$textcol,$bgcol) {
945 // basic (!) output for error handling
948 if ($fontnr<1 || $fontnr>5) {
951 if (!is_array($textcol) || !is_array($bgcol)) {
952 $textcol = array(0,0,0);
953 $bgcol = array(255,255,255);
955 foreach( array_merge($textcol,$bgcol) as $component) {
956 if ($component<0 || $component > 255) {
957 $textcol = array(0,0,0);
958 $bgcol = array(255,255,255);
963 // prepare Parameters
965 // set maximum values
972 if (function_exists('ImageFontWidth')) {
973 $charx = ImageFontWidth($fontnr);
974 $chary = ImageFontHeight($fontnr);
976 $charx = 10; $chary = 10;
979 $marginy = floor($chary/2);
981 $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2*$marginx )/$charx));
982 $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2*$marginy )/$chary));
989 $npos = strpos($txt, "\n");
992 $breaklen = min($IMAGESIZE['cols'],$len);
994 $breaklen = min($npos+1, $IMAGESIZE['cols']);
996 $lines[$y] = chop(substr($txt, 0, $breaklen));
997 $wx = max($wx,strlen($lines[$y++]));
998 $txt = substr($txt, $breaklen);
999 } while ($txt && ($y < $IMAGESIZE['rows']));
1001 // recalculate image size
1002 $IMAGESIZE['rows'] = $y;
1003 $IMAGESIZE['cols'] = $wx;
1005 $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2*$marginx;
1006 $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2*$marginy;
1008 // create blank image
1009 $im = @ImageCreate($IMAGESIZE['width'],$IMAGESIZE['height']);
1011 $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]);
1012 $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]);
1014 ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width']-1, $IMAGESIZE['height']-1, $bg);
1017 foreach($lines as $nr => $textstr) {
1018 ImageString( $im, $fontnr, $marginx, $marginy+$nr*$chary,
1024 function newFilterThroughCmd($input, $commandLine) {
1025 $descriptorspec = array(
1026 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1027 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
1028 2 => array("pipe", "w"), // stdout is a pipe that the child will write to
1031 $process = proc_open("$commandLine", $descriptorspec, $pipes);
1032 if (is_resource($process)) {
1033 // $pipes now looks like this:
1034 // 0 => writeable handle connected to child stdin
1035 // 1 => readable handle connected to child stdout
1036 // 2 => readable handle connected to child stderr
1037 fwrite($pipes[0], $input);
1040 while(!feof($pipes[1])) {
1041 $buf .= fgets($pipes[1], 1024);
1045 while(!feof($pipes[2])) {
1046 $stderr .= fgets($pipes[2], 1024);
1049 // It is important that you close any pipes before calling
1050 // proc_close in order to avoid a deadlock
1051 $return_value = proc_close($process);
1052 if (empty($buf)) printXML($this->error($stderr));
1057 /* PHP versions < 4.3
1058 * TODO: via temp file looks more promising
1060 function OldFilterThroughCmd($input, $commandLine) {
1061 $input = str_replace ("\\", "\\\\", $input);
1062 $input = str_replace ("\"", "\\\"", $input);
1063 $input = str_replace ("\$", "\\\$", $input);
1064 $input = str_replace ("`", "\`", $input);
1065 $input = str_replace ("'", "\'", $input);
1066 //$input = str_replace (";", "\;", $input);
1068 $pipe = popen("echo \"$input\"|$commandLine", 'r');
1070 print "pipe failed.";
1074 while (!feof($pipe)) {
1075 $output .= fread($pipe, 1024);
1081 // run "echo $source | $commandLine" and return result
1082 function filterThroughCmd($source, $commandLine) {
1083 if (check_php_version(4,3,0))
1084 return $this->newFilterThroughCmd($source, $commandLine);
1086 return $this->oldFilterThroughCmd($source, $commandLine);
1089 } // WikiPluginCached
1092 // $Log: not supported by cvs2svn $
1093 // Revision 1.16 2004/10/12 14:56:57 rurban
1094 // lib/WikiPluginCached.php:731: Notice[8]: Undefined property: _static
1096 // Revision 1.15 2004/09/26 17:09:23 rurban
1097 // add SVG support for Ploticus (and hopefully all WikiPluginCached types)
1100 // Revision 1.14 2004/09/25 16:26:08 rurban
1101 // some plugins use HTML
1103 // Revision 1.13 2004/09/22 13:46:25 rurban
1104 // centralize upload paths.
1105 // major WikiPluginCached feature enhancement:
1106 // support _STATIC pages in uploads/ instead of dynamic getimg.php? subrequests.
1107 // mainly for debugging, cache problems and action=pdf
1109 // Revision 1.12 2004/09/07 13:26:31 rurban
1110 // new WikiPluginCached option debug=static and some more sf.net defaults for VisualWiki
1112 // Revision 1.11 2004/09/06 09:12:46 rurban
1113 // improve pear handling with silent fallback to ours
1120 // c-basic-offset: 4
1121 // c-hanging-comment-ender-p: nil
1122 // indent-tabs-mode: nil