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';
32 define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation)
33 define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images
34 define('PLUGIN_CACHED_MAP', 2); // area maps
35 define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object
36 define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback
37 define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object
38 define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?)
39 define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?)
41 define('PLUGIN_CACHED_IMG_ONDEMAND', 64); // don't cache
42 define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id=
45 * An extension of the WikiPlugin class to allow image output and
47 * There are several abstract functions to be overloaded.
48 * Have a look at the example files
49 * <ul><li>plugin/TexToPng.php</li>
50 * <li>plugin/CacheTest.php (extremely simple example)</li>
51 * <li>plugin/RecentChangesCached.php</li>
52 * <li>plugin/VisualWiki.php</li>
53 * <li>plugin/Ploticus.php</li>
56 * @author Johannes Große, Reini Urban
58 abstract 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 object $cache the cache object used to store the images
68 * @param array $argarray all parameters (including those set to
69 * default values) of the plugin call to be
71 * @return array(id,url)
73 * TODO: check if args is needed at all (on lost cache)
75 private function genUrl($cache, $argarray)
79 $plugincall = serialize(array(
80 'pluginname' => $this->getName(),
81 'arguments' => $argarray));
82 $id = $cache->generateId($plugincall);
83 $plugincall_arg = rawurlencode($plugincall);
84 //$plugincall_arg = md5($plugincall);
85 // will not work if plugin has to recreate content and cache is lost
87 $url = DATA_PATH . '/getimg.php?';
88 if (($lastchar = substr($url, -1)) == '/') {
89 $url = substr($url, 0, -1);
91 if (strlen($plugincall_arg) > PLUGIN_CACHED_MAXARGLEN) {
92 // we can't send the data as URL so we just send the id
93 if (!$request->getSessionVar('imagecache' . $id)) {
94 $request->setSessionVar('imagecache' . $id, $plugincall);
96 $plugincall_arg = false; // not needed anymore
99 if ($lastchar == '?') {
100 // this indicates that a direct call of the image creation
101 // script is wished ($url is assumed to link to the script)
102 $url .= "id=$id" . ($plugincall_arg ? '&args=' . $plugincall_arg : '');
104 // Not yet supported.
105 // We are supposed to use the indirect 404 ErrorDocument method
106 // ($url is assumed to be the url of the image in
107 // cache_dir and the image creation script is referred to in the
108 // ErrorDocument 404 directive.)
109 $url .= '/' . PLUGIN_CACHED_FILENAME_PREFIX . $id . '.img'
110 . ($plugincall_arg ? '?args=' . $plugincall_arg : '');
112 if ($request->getArg("start_debug") and (DEBUG & _DEBUG_REMOTE))
113 $url .= "&start_debug=1";
114 return array($id, $url);
118 * Replaces the abstract run method of WikiPlugin to implement
119 * a cache check which can avoid redundant runs.
120 * <b>Do not override this method in a subclass. Instead you may
121 * rename your run method to getHtml, getImage or getMap.
122 * Have a close look on the arguments and required return values,
125 * @param WikiDB $dbi database abstraction class
126 * @param string $argstr plugin arguments in the call from PhpWiki
127 * @param WikiRequest $request
128 * @param string $basepage Pagename to use to interpret links [/relative] page names.
129 * @return string HTML output to be printed to browser
135 public function run($dbi, $argstr, &$request, $basepage)
137 $cache = $this->newCache();
139 $sortedargs = $this->getArgs($argstr, $request);
140 if (is_array($sortedargs))
142 $this->_args =& $sortedargs;
143 $this->_type = $this->getPluginType();
144 $this->_static = false;
145 if ($this->_type & PLUGIN_CACHED_STATIC
146 or $request->getArg('action') == 'pdf'
147 ) // htmldoc doesn't grok subrequests
149 $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC;
150 $this->_static = true;
153 // ---------- embed static image, no getimg.php? url -----------------
154 if (0 and $this->_static) {
155 //$content = $cache->get($id, 'imagecache');
157 if ($this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html')) {
158 // save the image in uploads
159 return $this->embedImg($content['url'], $dbi, $sortedargs, $request);
161 // copy the cached image into uploads if older
166 list($id, $url) = $this->genUrl($cache, $sortedargs);
167 // ---------- don't check cache: html and img gen. -----------------
168 // override global PLUGIN_CACHED_USECACHE for a plugin
169 if ($this->getPluginType() & PLUGIN_CACHED_IMG_ONDEMAND) {
170 if ($this->_static and $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'))
171 $url = $content['url'];
172 return $this->embedImg($url, $dbi, $sortedargs, $request);
176 $content = $cache->get($id, 'imagecache');
177 switch ($this->_type) {
178 case PLUGIN_CACHED_HTML:
179 if (!$content || !$content['html']) {
181 $content['html'] = $this->getHtml($dbi, $sortedargs, $request, $basepage);
182 if ($errortext = $this->getError()) {
183 $this->printError($errortext, 'html');
189 case PLUGIN_CACHED_IMG_INLINE:
190 if (PLUGIN_CACHED_USECACHE && (!$content || !$content['image'])) { // new
191 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
192 if ($this->_static) $url = $content['url'];
193 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
194 } elseif (!empty($content['url']) && $this->_static) { // already in cache
195 $content['html'] = $this->embedImg($content['url'], $dbi, $sortedargs, $request);
196 } elseif (!empty($content['image']) && $this->_static) { // copy from cache to upload
197 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
198 $url = $content['url'];
199 $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false;
202 case PLUGIN_CACHED_MAP:
203 if (!$content || !$content['image'] || !$content['html']) {
204 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
205 if ($this->_static) $url = $content['url'];
206 $content['html'] = $do_save
207 ? $this->embedMap($id, $url, $content['html'], $dbi, $sortedargs, $request)
211 case PLUGIN_CACHED_SVG:
212 if (!$content || !$content['html']) {
213 $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
214 if ($this->_static) $url = $content['url'];
215 $args = array(); //width+height => object args
216 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
217 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
218 $content['html'] = $do_save
219 ? $this->embedObject($url, 'image/svg+xml', $args,
220 HTML::embed(array_merge(
221 array('src' => $url, 'type' => 'image/svg+xml'),
226 case PLUGIN_CACHED_SVG_PNG:
227 if (!$content || !$content['html']) {
228 $do_save_svg = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
229 if ($this->_static) $url = $content['url'];
230 // hack alert! somehow we should know which argument will produce the secondary image (PNG)
232 $args[$this->pngArg()] = $content['imagetype']; // default type: PNG or GIF
233 $do_save = $this->produceImage($pngcontent, $this, $dbi, $args, $request, $content['imagetype']);
234 $args = array(); //width+height => object args
235 if (!empty($sortedargs['width'])) $args['width'] = $sortedargs['width'];
236 if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height'];
237 $content['html'] = $do_save_svg
238 ? $this->embedObject($url, 'image/svg+xml', $args,
239 $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request))
245 $content['args'] = md5($this->_pi);
246 $expire = $this->getExpire($dbi, $content['args'], $request);
247 $cache->save($id, $content, $expire, 'imagecache');
249 if ($content['html'])
250 return $content['html'];
254 /* --------------------- abstract functions ----------- */
257 * Sets the type of the plugin to html, image or map
260 * @return int determines the plugin to produce either html,
261 * an image or an image map; uses on of the
262 * following predefined values
264 * <li>PLUGIN_CACHED_HTML</li>
265 * <li>PLUGIN_CACHED_IMG_INLINE</li>
266 * <li>PLUGIN_CACHED_IMG_ONDEMAND</li>
267 * <li>PLUGIN_CACHED_MAP</li>
270 abstract protected function getPluginType();
273 * Creates an image handle from the given user arguments.
274 * This method is only called if the return value of
275 * <code>getPluginType</code> is set to
276 * PLUGIN_CACHED_IMG_INLINE or PLUGIN_CACHED_IMG_ONDEMAND.
278 * @param WikiDB $dbi database abstraction class
279 * @param array $argarray complete (!) arguments to produce
280 * image. It is not necessary to call
281 * WikiPlugin->getArgs anymore.
282 * @param Request $request
283 * @return mixed imagehandle image handle if successful
284 * false if an error occured
286 abstract protected function getImage($dbi, $argarray, $request);
289 * Sets the life time of a cache entry in seconds.
290 * Expired entries are not used anymore.
291 * During a garbage collection each expired entry is
292 * removed. If removing all expired entries is not
293 * sufficient, the expire time is ignored and removing
294 * is determined by the last "touch" of the entry.
296 * @param WikiDB $dbi database abstraction class
297 * @param array $argarray complete (!) arguments. It is
298 * not necessary to call
299 * WikiPlugin->getArgs anymore.
300 * @param Request $request
301 * @return string format: '+seconds'
304 protected function getExpire($dbi, $argarray, $request)
306 return '0'; // persist forever
310 * Decides the image type of an image output.
311 * Always used unless plugin type is PLUGIN_CACHED_HTML.
313 * @param WikiDB $dbi database abstraction class
314 * @param array $argarray complete (!) arguments. It is
315 * not necessary to call
316 * WikiPlugin->getArgs anymore.
317 * @param Request $request
318 * @return string 'png', 'jpeg' or 'gif'
320 protected function getImageType(&$dbi, $argarray, &$request)
322 if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
323 return $argarray['imgtype'];
329 * Produces the alt text for an image.
330 * <code> <img src=... alt="getAlt(...)"> </code>
332 * @param WikiDB $dbi database abstraction class
333 * @param array $argarray complete (!) arguments. It is
334 * not necessary to call
335 * WikiPlugin->getArgs anymore.
336 * @param Request $request
337 * @return string "alt" description of the image
339 protected function getAlt($dbi, $argarray, $request)
341 return '<?plugin ' . $this->getName() . ' ' . $this->glueArgs($argarray) . '?>';
345 * Creates HTML output to be cached.
346 * This method is only called if the plugin_type is set to
347 * PLUGIN_CACHED_HTML.
349 * @param WikiDB $dbi database abstraction class
350 * @param array $argarray complete (!) arguments to produce
351 * image. It is not necessary to call
352 * WikiPlugin->getArgs anymore.
353 * @param Request $request
354 * @param string $basepage Pagename to use to interpret links [/relative] page names.
355 * @return string html to be printed in place of the plugin command
356 * false if an error occured
358 abstract protected function getHtml($dbi, $argarray, $request, $basepage);
361 * Creates HTML output to be cached.
362 * This method is only called if the plugin_type is set to
363 * PLUGIN_CACHED_HTML.
365 * @param WikiDB $dbi database abstraction class
366 * @param array $argarray complete (!) arguments to produce
367 * image. It is not necessary to call
368 * WikiPlugin->getArgs anymore.
369 * @param Request $request
370 * @return array(html,handle) html for the map interior (to be specific,
371 * only <area;> tags defining hot spots)
372 * handle is an imagehandle to the corresponding
374 * array(false,false) if an error occured
376 abstract protected function getMap($dbi, $argarray, $request);
378 /* --------------------- produce Html ----------------------------- */
381 * Creates an HTML map hyperlinked to the image specified
382 * by url and containing the hotspots given by map.
384 * @param string $id unique id for the plugin call
385 * @param string $url url pointing to the image part of the map
386 * @param string $map <area> tags defining active
388 * @param WikiDB $dbi database abstraction class
389 * @param array $argarray complete (!) arguments to produce
390 * image. It is not necessary to call
391 * WikiPlugin->getArgs anymore.
392 * @param Request $request
393 * @return string html output
395 protected function embedMap($id, $url, $map, &$dbi, $argarray, &$request)
397 // id is not unique if the same map is produced twice
398 $key = substr($id, 0, 8) . substr(microtime(), 0, 6);
399 return HTML(HTML::map(array('name' => $key), $map),
402 // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
403 'usemap' => '#' . $key))
408 * Which argument must be set to 'png', for the fallback image when svg
409 * will fail on the client.
414 protected function pngArg()
416 trigger_error('WikiPluginCached::pngArg: pure virtual function in file '
417 . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
421 * Creates an HTML <img> tag hyperlinking to the specified
422 * url and produces an alternative text for non-graphical
425 * @param string $url url pointing to the image part of the map
426 * @param WikiDB $dbi database abstraction class
427 * @param array $argarray complete (!) arguments to produce
428 * image. It is not necessary to call
429 * WikiPlugin->getArgs anymore.
430 * @param Request $request
431 * @return string html output
433 private function embedImg($url, $dbi, $argarray, $request)
435 return HTML::img(array(
437 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request))));
442 <object type="audio/x-wav" standby="Loading Audio" data="example.wav">
443 <param name="src" value="example.wav" valuetype="data"></param>
444 <param name="autostart" value="false" valuetype="data"></param>
445 <param name="controls" value="ControlPanel" valuetype="data"></param>
446 <a href="example.wav">Example Audio File</a>
448 * See http://www.protocol7.com/svg-wiki/?EmbedingSvgInHTML
449 <object data="sample.svgz" type="image/svg+xml"
450 width="400" height="300">
451 <embed src="sample.svgz" type="image/svg+xml"
452 width="400" height="300" />
453 <p>Alternate Content like <img src="" /></p>
456 // how to handle alternate images? always provide alternate static images?
457 function embedObject($url, $type, $args = false, $params = false)
459 if (!$args) $args = array();
460 $object = HTML::object(array_merge($args, array('src' => $url, 'type' => $type)));
462 $object->pushContent($params);
466 // --------------------------------------------------------------------------
467 // ---------------------- static member functions ---------------------------
468 // --------------------------------------------------------------------------
471 * Creates one static PEAR Cache object and returns copies afterwards.
472 * FIXME: There should be references returned
474 * @return Cache copy of the cache object
476 static public function newCache()
480 if (!is_object($staticcache)) {
481 if (!class_exists('Cache')) {
482 // uuh, pear not in include_path! should print a warning.
483 // search some possible pear paths.
484 $pearFinder = new PearFileFinder;
485 if ($lib = $pearFinder->findFile('Cache.php', 'missing_ok'))
487 else // fall back to our own copy
488 require_once 'lib/pear/Cache.php';
490 $cacheparams = array();
491 foreach (explode(':', 'database:cache_dir:filename_prefix:highwater:lowwater'
492 . ':maxlifetime:maxarglen:usecache:force_syncmap') as $key) {
493 $cacheparams[$key] = constant('PLUGIN_CACHED_' . strtoupper($key));
495 $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES);
496 $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams);
497 $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME;
499 if (!PLUGIN_CACHED_USECACHE) {
500 $staticcache->setCaching(false);
503 return $staticcache; // FIXME: use references ?
507 * Determines whether a needed image type may is available
508 * from the GD library and gives an alternative otherwise.
510 * @param string $wish one of 'png', 'gif', 'jpeg', 'jpg'
511 * @return string the image type to be used ('png', 'gif', 'jpeg')
512 * 'html' in case of an error
515 public static function decideImgType($wish)
517 if ($wish == 'html') return $wish;
518 if ($wish == 'jpg') {
522 $supportedtypes = array();
523 // Todo: swf, pdf, ...
530 /* // these do work but not with the ImageType bitmask
536 $presenttypes = ImageTypes();
537 foreach ($imagetypes as $imgtype => $bitmask)
538 if ($presenttypes && $bitmask)
539 array_push($supportedtypes, $imgtype);
540 if (in_array($wish, $supportedtypes))
542 elseif (!empty($supportedtypes))
543 return reset($supportedtypes); else
549 * Writes an image into a file or to the browser.
550 * Note that there is no check if the image can
553 * @param string $imgtype 'png', 'gif' or 'jpeg'
554 * @param string $imghandle image handle containing the image
555 * @param string $imgfile file name of the image to be produced
557 * @see decideImageType
559 public static function writeImage($imgtype, $imghandle, $imgfile = '')
561 if ($imgtype != 'html') {
562 $func = "Image" . strtoupper($imgtype);
564 $func($imghandle, $imgfile);
572 * Sends HTTP Header for some predefined file types.
573 * There is no parameter check.
575 * @param string $doctype 'gif', 'png', 'jpeg', 'html'
578 public static function writeHeader($doctype)
580 static $IMAGEHEADER = array(
581 'gif' => 'Content-type: image/gif',
582 'png' => 'Content-type: image/png',
583 'jpeg' => 'Content-type: image/jpeg',
584 'xbm' => 'Content-type: image/xbm',
585 'xpm' => 'Content-type: image/xpm',
586 'gd' => 'Content-type: image/gd',
587 'gd2' => 'Content-type: image/gd2',
588 'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such.
589 'html' => 'Content-type: text/html');
590 // Todo: swf, pdf, svg, svgz
591 Header($IMAGEHEADER[$doctype]);
595 * Converts argument array to a string of format option="value".
596 * This should only be used for displaying plugin options for
597 * the quoting of arguments is not safe, yet.
599 * @param array $argarray contains all arguments to be converted
600 * @return string concated arguments
602 public static function glueArgs($argarray)
604 if (!empty($argarray)) {
606 while (list($key, $value) = each($argarray)) {
607 $argstr .= $key . '=' . '"' . $value . '" ';
608 // FIXME: How are values quoted? Can a value contain '"'?
609 // TODO: rawurlencode(value)
611 return substr($argstr, 0, strlen($argstr) - 1);
616 // ---------------------- FetchImageFromCache ------------------------------
619 * Extracts the cache entry id from the url and the plugin call
620 * parameters if available.
622 * @param string $id return value. Image is stored under this id.
623 * @param string $plugincall return value. Only returned if present in url.
624 * Contains all parameters to reconstruct
626 * @param Cache $cache PEAR Cache object
627 * @param Request $request
628 * @param string $errorformat format which should be used to
629 * output errors ('html', 'png', 'gif', 'jpeg')
630 * @return bool false if an error occurs, true otherwise.
631 * Param id and param plugincall are
632 * also return values.
634 private function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat)
636 $id = $request->getArg('id');
637 $plugincall = rawurldecode($request->getArg('args'));
641 // This should never happen, so do not gettextify.
642 $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters.";
643 $this->printError($errorformat, $errortext);
646 $id = $cache->generateId($plugincall);
653 * Extracts the parameters necessary to reconstruct the plugin
654 * call needed to produce the requested image.
656 * @param string $plugincall reference to serialized array containing both
657 * name and parameters of the plugin call
658 * @param Request $request ???
659 * @return bool false if an error occurs, true otherwise.
662 private function checkCall2(&$plugincall, $request)
664 // if plugincall wasn't sent by URL, it must have been
665 // stored in a session var instead and we can retreive it from there
667 if (!$plugincall = $request->getSessionVar('imagecache' . $id)) {
668 // I think this is the only error which may occur
669 // without having written bad code. So gettextify it.
670 $errortext = sprintf(
671 gettext("There is no image creation data available to id “%s”. Please reload referring page."),
673 $this->printError($errorformat, $errortext);
677 $plugincall = unserialize($plugincall);
682 * Creates an image or image map depending on the plugin type.
683 * @param array $content reference to created array which overwrite the keys
684 * 'image', 'imagetype' and possibly 'html'
685 * @param WikiPluginCached $plugin plugin which is called to create image or map
686 * @param WikiDB $dbi WikiDB handle to database
687 * @param array $argarray array Contains all arguments needed by plugin
688 * @param Request $request Request ????
689 * @param string $errorformat outputs errors in 'png', 'gif', 'jpg' or 'html'
690 * @return bool error status; true=ok; false=error
692 private function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat)
694 $plugin->resetError();
695 $content['html'] = $imagehandle = false;
696 if ($plugin->getPluginType() == PLUGIN_CACHED_MAP) {
697 list($imagehandle, $content['html']) = $plugin->getMap($dbi, $argarray, $request);
699 $imagehandle = $plugin->getImage($dbi, $argarray, $request);
702 $content['imagetype']
703 = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request));
704 $errortext = $plugin->getError();
706 if (!$imagehandle || $errortext) {
708 $errortext = "'<<" . $plugin->getName() . ' '
709 . $this->glueArgs($argarray) . " >>' returned no image, "
710 . " although no error was reported.";
712 $this->printError($errorformat, $errortext);
716 // image handle -> image data
717 if (!empty($this->_static)) {
718 $ext = "." . $content['imagetype'];
719 if (is_string($imagehandle) and file_exists($imagehandle)) {
720 if (preg_match("/.(\w+)$/", $imagehandle, $m)) {
724 $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext);
725 if (!strstr(basename($tmpfile), $ext)) {
729 $tmpfile = getUploadFilePath() . basename($tmpfile);
730 if (is_string($imagehandle) and file_exists($imagehandle)) {
731 rename($imagehandle, $tmpfile);
734 $tmpfile = $this->tempnam();
736 if (is_resource($imagehandle)) {
737 $this->writeImage($content['imagetype'], $imagehandle, $tmpfile);
738 ImageDestroy($imagehandle);
740 } elseif (is_string($imagehandle)) {
741 $content['file'] = getUploadFilePath() . basename($tmpfile);
742 $content['url'] = getUploadDataPath() . basename($tmpfile);
745 if (file_exists($tmpfile)) {
746 $fp = fopen($tmpfile, 'rb');
747 if (filesize($tmpfile)) {
748 $content['image'] = fread($fp, filesize($tmpfile));
750 $content['image'] = '';
753 if (!empty($this->_static)) {
754 // on static it is in "uploads/" but in wikicached also
755 $content['file'] = $tmpfile;
756 $content['url'] = getUploadDataPath() . basename($tmpfile);
760 if ($content['image']) {
767 function staticUrl($tmpfile)
769 $content['file'] = $tmpfile;
770 $content['url'] = getUploadDataPath() . basename($tmpfile);
774 function tempnam($prefix = "")
776 if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) {
780 $ext = isWindows() ? ".tmp" : "";
782 $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR)
783 : PLUGIN_CACHED_CACHE_DIR,
784 $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
786 if ($ext != ".tmp") unlink($temp);
787 $temp = preg_replace("/\.tmp$/", $ext, $temp);
795 * Main function for obtaining images from cache or generating on-the-fly
796 * from parameters sent by url or session vars.
798 * @param WikiDB $dbi handle to database
799 * @param Request $request ???
800 * @param string $errorformat outputs errors in 'png', 'gif', 'jpeg' or 'html'
803 public function fetchImageFromCache($dbi, $request, $errorformat = 'png')
805 $cache = $this->newCache();
806 $errorformat = $this->decideImgType($errorformat);
808 if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false;
810 $content = $cache->get($id, 'imagecache');
812 if (!empty($content['image'])) {
813 $this->writeHeader($content['imagetype']);
814 print $content['image'];
817 if (!empty($content['html'])) {
818 print $content['html'];
822 if (!empty($content['file']) && !empty($content['url']) && file_exists($content['file'])) {
823 print $this->embedImg($content['url'], $dbi, array(), $request);
827 // re-produce image. At first, we need the plugincall parameters.
828 // Cached args with matching id override given args to shorten getimg.php?id=md5
829 if (!empty($content['args']))
830 $plugincall['arguments'] = $content['args'];
831 if (!$this->checkCall2($plugincall, $request)) return false;
833 $pluginname = $plugincall['pluginname'];
834 $argarray = $plugincall['arguments'];
836 $loader = new WikiPluginLoader();
837 $plugin = $loader->getPlugin($pluginname);
839 // cache empty, but image maps have to be created _inline_
840 // so ask user to reload wiki page instead
841 if (($plugin->getPluginType() & PLUGIN_CACHED_MAP) && PLUGIN_CACHED_FORCE_SYNCMAP) {
842 $errortext = _("Image map expired. Reload wiki page to recreate its html part.");
843 $this->printError($errorformat, $errortext);
846 if (!$this->produceImage($content, $plugin, $dbi, $argarray,
847 $request, $errorformat)
851 $expire = $plugin->getExpire($dbi, $argarray, $request);
853 if ($content['image']) {
854 $cache->save($id, $content, $expire, 'imagecache');
855 $this->writeHeader($content['imagetype']);
856 print $content['image'];
860 $errortext = _("Could not create image file from imagehandle.");
861 $this->printError($errorformat, $errortext);
863 } // FetchImageFromCache
865 // -------------------- error handling ----------------------------
868 * Resets buffer containing all error messages. This is allways
869 * done before invoking any abstract creation routines like
870 * <code>getImage</code>.
874 protected function resetError()
876 $this->_errortext = '';
880 * Returns all accumulated error messages.
882 * @return string error messages printed with <code>complain</code>.
884 protected function getError()
886 return $this->_errortext;
890 * Collects the error messages in a string for later output
891 * by WikiPluginCached. This should be used for any errors
892 * that occur during data (html,image,map) creation.
894 * @param string $addtext errormessage to be printed (separate
895 * multiple lines with '\n')
898 protected function complain($addtext)
900 $this->_errortext .= $addtext;
904 * Outputs the error as image if possible or as html text
905 * if wished or html header has already been sent.
907 * @param string $imgtype 'png', 'gif', 'jpeg' or 'html'
908 * @param string $errortext guess what?
911 public function printError($imgtype, $errortext)
913 $imgtype = $this->decideImgType($imgtype);
915 $talkedallready = ob_get_contents() || headers_sent();
916 if (($imgtype == 'html') || $talkedallready) {
917 if (is_object($errortext))
918 $errortext = $errortext->asXml();
919 trigger_error($errortext, E_USER_WARNING);
921 $red = array(255, 0, 0);
922 $grey = array(221, 221, 221);
923 if (is_object($errortext))
924 $errortext = $errortext->asString();
925 $im = $this->text2img($errortext, 2, $red, $grey);
927 trigger_error($errortext, E_USER_WARNING);
930 $this->writeHeader($imgtype);
931 $this->writeImage($imgtype, $im);
937 * Basic text to image converter for error handling which allows
938 * multiple line output.
939 * It will only output the first 25 lines of 80 characters. Both
940 * values may be smaller if the chosen font is to big for there
941 * is further restriction to 600 pixel in width and 350 in height.
943 * @param string $txt multi line text to be converted
944 * @param int $fontnr number (1-5) telling gd which internal font to use;
945 * I recommend font 2 for errors and 4 for help texts.
946 * @param array $textcol text color as a list of the rgb components; array(red,green,blue)
947 * @param array $bgcol background color; array(red,green,blue)
948 * @return string image handle for gd routines
950 static public function text2img($txt, $fontnr, $textcol, $bgcol)
952 // basic (!) output for error handling
955 if ($fontnr < 1 || $fontnr > 5) {
958 if (!is_array($textcol) || !is_array($bgcol)) {
959 $textcol = array(0, 0, 0);
960 $bgcol = array(255, 255, 255);
962 foreach (array_merge($textcol, $bgcol) as $component) {
963 if ($component < 0 || $component > 255) {
964 $textcol = array(0, 0, 0);
965 $bgcol = array(255, 255, 255);
970 // prepare Parameters
972 // set maximum values
979 $charx = ImageFontWidth($fontnr);
980 $chary = ImageFontHeight($fontnr);
982 $marginy = floor($chary / 2);
984 $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2 * $marginx) / $charx));
985 $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2 * $marginy) / $chary));
992 $npos = strpos($txt, "\n");
994 if ($npos === false) {
995 $breaklen = min($IMAGESIZE['cols'], $len);
997 $breaklen = min($npos + 1, $IMAGESIZE['cols']);
999 $lines[$y] = chop(substr($txt, 0, $breaklen));
1000 $wx = max($wx, strlen($lines[$y++]));
1001 $txt = substr($txt, $breaklen);
1002 } while ($txt && ($y < $IMAGESIZE['rows']));
1004 // recalculate image size
1005 $IMAGESIZE['rows'] = $y;
1006 $IMAGESIZE['cols'] = $wx;
1008 $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2 * $marginx;
1009 $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2 * $marginy;
1011 // create blank image
1012 $im = @ImageCreate($IMAGESIZE['width'], $IMAGESIZE['height']);
1014 $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]);
1015 $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]);
1017 ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width'] - 1, $IMAGESIZE['height'] - 1, $bg);
1020 foreach ($lines as $nr => $textstr) {
1021 ImageString($im, $fontnr, $marginx, $marginy + $nr * $chary,
1027 function newFilterThroughCmd($input, $commandLine)
1029 $descriptorspec = array(
1030 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1031 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
1032 2 => array("pipe", "w"), // stdout is a pipe that the child will write to
1035 $process = proc_open("$commandLine", $descriptorspec, $pipes);
1036 if (is_resource($process)) {
1037 // $pipes now looks like this:
1038 // 0 => writeable handle connected to child stdin
1039 // 1 => readable handle connected to child stdout
1040 // 2 => readable handle connected to child stderr
1041 fwrite($pipes[0], $input);
1044 while (!feof($pipes[1])) {
1045 $buf .= fgets($pipes[1], 1024);
1049 while (!feof($pipes[2])) {
1050 $stderr .= fgets($pipes[2], 1024);
1053 // It is important that you close any pipes before calling
1054 // proc_close in order to avoid a deadlock
1055 proc_close($process);
1056 if (empty($buf)) printXML($this->error($stderr));
1062 // run "echo $source | $commandLine" and return result
1063 function filterThroughCmd($source, $commandLine)
1065 return $this->newFilterThroughCmd($source, $commandLine);
1069 * Execute system command and wait until the outfile $until exists.
1071 * @param string $cmd command to be invoked
1072 * @param string $until expected output filename
1073 * @return bool error status; true=ok; false=error
1075 function execute($cmd, $until = '')
1077 // cmd must redirect stderr to stdout though!
1078 $errstr = exec($cmd); //, $outarr, $returnval); // normally 127
1079 //$errstr = join('',$outarr);
1080 $ok = empty($errstr);
1082 trigger_error("\n" . $cmd . " failed: $errstr", E_USER_WARNING);
1083 } elseif ($GLOBALS['request']->getArg('debug'))
1084 trigger_error("\n" . $cmd . ": success\n", E_USER_NOTICE);
1088 while (!file_exists($until) and $loop > 0) {
1097 return file_exists($until);
1106 // c-basic-offset: 4
1107 // c-hanging-comment-ender-p: nil
1108 // indent-tabs-mode: nil