]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPluginCached.php
improve pear handling with silent fallback to ours
[SourceForge/phpwiki.git] / lib / WikiPluginCached.php
1 <?php rcs_id('$Id: WikiPluginCached.php,v 1.11 2004-09-06 09:12:46 rurban Exp $');
2 /*
3  Copyright (C) 2002 Johannes Große (Johannes Gro&szlig;e)
4
5  This file is part of PhpWiki.
6
7  PhpWiki is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2 of the License, or
10  (at your option) any later version.
11
12  PhpWiki is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  GNU General Public License for more details.
16
17  You should have received a copy of the GNU General Public License
18  along with PhpWiki; if not, write to the Free Software
19  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */ 
21
22 /**
23  * You should set up the options in config/config.ini at Part seven:
24  * $ pear install http://pear.php.net/get/Cache
25  * This file belongs to WikiPluginCached.
26  * @author  Johannes Große
27  * @version 0.8
28  */
29
30 require_once "lib/WikiPlugin.php";
31 // require_once "lib/plugincache-config.php"; // replaced by config.ini settings!
32
33 // Try the system pear class. See newCache()
34 @require_once('Cache.php');
35
36 define('PLUGIN_CACHED_HTML',0);
37 define('PLUGIN_CACHED_IMG_INLINE',1);
38 define('PLUGIN_CACHED_IMG_ONDEMAND',2);
39 define('PLUGIN_CACHED_MAP',3);
40
41 /**
42  * An extension of the WikiPlugin class to allow image output and      
43  * cacheing.                                                         
44  * There are several abstract functions to be overloaded. 
45  * Have a look at the example files
46  * <ul><li>plugin/TexToPng.php</li>
47  *     <li>plugin/CacheTest.php (extremely simple example)</li>
48  *     <li>plugin/RecentChanges.php</li>
49  *     <li>plugin/VisualWiki.php</li></ul>
50  *
51  * @author  Johannes Große
52  * @version 1.0
53  */                                                                
54 class WikiPluginCached extends WikiPlugin
55 {   
56     /** 
57      * Produces URL and id number from plugin arguments which later on,
58      * will allow to find a cached image or to reconstruct the complete 
59      * plugin call to recreate the image.
60      * 
61      * @param cache    object the cache object used to store the images
62      * @param argarray array  all parameters (including those set to 
63      *                        default values) of the plugin call to be
64      *                        prepared
65      * @access private
66      * @return array(id,url)  
67      */
68     function genUrl($cache, $argarray) {
69         global $request;
70         //$cacheparams = $GLOBALS['CacheParams'];
71
72         $plugincall = serialize( array( 
73             'pluginname' => $this->getName(),
74             'arguments'  => $argarray ) ); 
75         $id = $cache->generateId( $plugincall );
76
77         $url = DATA_PATH . '/getimg.php?';
78         if (($lastchar = substr($url,-1)) == '/') {
79             $url = substr($url, 0, -1);
80         }
81         if (strlen($plugincall) > PLUGIN_CACHED_MAXARGLEN) {
82             // we can't send the data as URL so we just send the id  
83             if (!$request->getSessionVar('imagecache'.$id)) {
84                 $request->setSessionVar('imagecache'.$id, $plugincall);
85             } 
86             $plugincall = false; // not needed anymore
87         }
88
89         if ($lastchar == '?') {
90             // this indicates that a direct call of the image creation
91             // script is wished ($url is assumed to link to the script)
92             $url .= "id=$id" . ($plugincall ? '&args='.rawurlencode($plugincall) : '');
93         } else {
94             // Not yet supported.
95             // We are supposed to use the indirect 404 ErrorDocument method
96             // ($url is assumed to be the url of the image in 
97             //  cache_dir and the image creation script is referred to in the 
98             //  ErrorDocument 404 directive.)
99             $url .= '/' . PLUGIN_CACHED_FILENAME_PREFIX . $id . '.img' 
100                     . ($plugincall ? '?args='.rawurlencode($plugincall) : '');
101         }
102         if ($request->getArg("start_debug"))
103             $url .= "&start_debug=1";
104         return array($id, $url);
105     } // genUrl
106
107     /** 
108      * Replaces the abstract run method of WikiPlugin to implement
109      * a cache check which can avoid redundant runs. 
110      * <b>Do not override this method in a subclass. Instead you may
111      * rename your run method to getHtml, getImage or getMap.
112      * Have a close look on the arguments and required return values,
113      * however. </b>  
114      * 
115      * @access protected
116      * @param  dbi       WikiDB  database abstraction class
117      * @param  argstr    string  plugin arguments in the call from PhpWiki
118      * @param  request   Request ???
119      * @param  string    basepage Pagename to use to interpret links [/relative] page names.
120      * @return           string  HTML output to be printed to browser
121      *
122      * @see #getHtml
123      * @see #getImage
124      * @see #getMap
125      */
126     function run($dbi, $argstr, &$request, $basepage) {
127         $cache = WikiPluginCached::newCache();
128         //$cacheparams = $GLOBALS['CacheParams'];
129
130         $sortedargs = $this->getArgs($argstr, $request);
131         if (is_array($sortedargs) )
132             ksort($sortedargs);
133         $this->_args =& $sortedargs;
134         list($id,$url) = $this->genUrl($cache, $sortedargs);
135
136         // ---------- html and img gen. -----------------
137         if ($this->getPluginType() == PLUGIN_CACHED_IMG_ONDEMAND) {
138             return $this->embedImg($url, $dbi, $sortedargs, $request);
139         }
140
141         $do_save = false;
142         $content = $cache->get($id, 'imagecache');
143         switch($this->getPluginType()) {
144             case PLUGIN_CACHED_HTML:
145                 if (!$content || !$content['html']) {
146                     $this->resetError();
147                     $content['html'] = $this->getHtml($dbi,$sortedargs,$request,$basepage);
148                     if ($errortext = $this->getError()) {
149                         WikiPluginCached::printError($errortext,'html');
150                         return HTML();
151                     }
152                     $do_save = true;
153                 } 
154                 break;
155             case PLUGIN_CACHED_IMG_INLINE:
156                 if (PLUGIN_CACHED_USECACHE && (!$content || !$content['image'])) {
157                     $do_save = WikiPluginCached::produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
158                     $content['html'] = $do_save?$this->embedImg($url, $dbi, $sortedargs, $request) : false;
159                 }
160                 break;
161             case PLUGIN_CACHED_MAP:
162                 if (!$content || !$content['image'] || !$content['html'] ) {
163                     $do_save = WikiPluginCached::produceImage($content, $this, $dbi, $sortedargs, $request, 'html');
164                     $content['html'] = $do_save?WikiPluginCached::embedMap($id,
165                         $url,$content['html'],$dbi,$sortedargs,$request):false;
166                 }
167                 break;
168         }
169         if ($do_save) {
170             $expire = $this->getExpire($dbi,$sortedargs,$request);
171             $cache->save($id, $content, $expire,'imagecache');
172         }
173         if ($content['html'])
174             return $content['html'];
175         return HTML();
176     } // run
177
178
179     /* --------------------- virtual or abstract functions ----------- */
180
181     /**
182      * Sets the type of the plugin to html, image or map 
183      * production
184      *
185      * @access protected 
186      * @return int determines the plugin to produce either html, 
187      *             an image or an image map; uses on of the 
188      *             following predefined values
189      *             <ul> 
190      *             <li>PLUGIN_CACHED_HTML</li>
191      *             <li>PLUGIN_CACHED_IMG_INLINE</li>
192      *             <li>PLUGIN_CACHED_IMG_ONDEMAND</li>
193      *             <li>PLUGIN_CACHED_MAP</li>
194      *             </ul>    
195      */
196     function getPluginType() {
197         return PLUGIN_CACHED_IMG_ONDEMAND;
198     }
199
200     /** 
201      * Creates an image handle from the given user arguments. 
202      * This method is only called if the return value of 
203      * <code>getPluginType</code> is set to 
204      * PLUGIN_CACHED_IMG_INLINE or PLUGIN_CACHED_IMG_ONDEMAND.
205      *
206      * @access protected pure virtual
207      * @param  dbi       WikiDB       database abstraction class
208      * @param  argarray  array        complete (!) arguments to produce 
209      *                                image. It is not necessary to call 
210      *                                WikiPlugin->getArgs anymore.
211      * @param  request   Request      ??? 
212      * @return           imagehandle  image handle if successful
213      *                                false if an error occured
214      */
215     function getImage($dbi,$argarray,$request) {
216         trigger_error('WikiPluginCached::getImage: pure virtual function in file ' 
217                       . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
218         return false;
219     }
220
221     /** 
222      * Sets the life time of a cache entry in seconds. 
223      * Expired entries are not used anymore.
224      * During a garbage collection each expired entry is
225      * removed. If removing all expired entries is not
226      * sufficient, the expire time is ignored and removing
227      * is determined by the last "touch" of the entry.
228      * 
229      * @access protected virtual
230      * @param  dbi       WikiDB       database abstraction class
231      * @param  argarray  array        complete (!) arguments. It is
232      *                                not necessary to call 
233      *                                WikiPlugin->getArgs anymore.
234      * @param  request   Request      ??? 
235      * @return           string       format: '+seconds'
236      *                                '0' never expires
237      */
238     function getExpire($dbi,$argarray,$request) {
239         return '0'; // persist forever
240     }
241
242     /** 
243      * Decides the image type of an image output. 
244      * Always used unless plugin type is PLUGIN_CACHED_HTML.
245      * 
246      * @access protected virtual
247      * @param  dbi       WikiDB       database abstraction class
248      * @param  argarray  array        complete (!) arguments. It is
249      *                                not necessary to call 
250      *                                WikiPlugin->getArgs anymore.
251      * @param  request   Request      ??? 
252      * @return           string       'png', 'jpeg' or 'gif'
253      */    
254     function getImageType(&$dbi, $argarray, &$request) {
255         if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES)))
256             return $argarray['imgtype'];
257         else
258             return 'png';
259     }
260
261     /** 
262      * Produces the alt text for an image.
263      * <code> &lt;img src=... alt="getAlt(...)"&gt; </code> 
264      *
265      * @access protected virtual
266      * @param  dbi       WikiDB       database abstraction class
267      * @param  argarray  array        complete (!) arguments. It is
268      *                                not necessary to call 
269      *                                WikiPlugin->getArgs anymore.
270      * @param  request   Request      ??? 
271      * @return           string       "alt" description of the image
272      */
273     function getAlt($dbi,$argarray,$request) {
274         return '<?plugin '.$this->getName().' '.$this->glueArgs($argarray).'?>';
275     }
276
277     /** 
278      * Creates HTML output to be cached.  
279      * This method is only called if the plugin_type is set to 
280      * PLUGIN_CACHED_HTML.
281      *
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      * @param  string    $basepage    Pagename to use to interpret links [/relative] page names.
289      * @return           string       html to be printed in place of the plugin command
290      *                                false if an error occured
291      */
292     function getHtml($dbi, $argarray, $request, $basepage) {
293         trigger_error('WikiPluginCached::getHtml: pure virtual function in file ' 
294                       . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
295     }
296
297     /** 
298      * Creates HTML output to be cached.  
299      * This method is only called if the plugin_type is set to 
300      * PLUGIN_CACHED_HTML.
301      *
302      * @access protected pure virtual
303      * @param  dbi       WikiDB       database abstraction class
304      * @param  argarray  array        complete (!) arguments to produce 
305      *                                image. It is not necessary to call 
306      *                                WikiPlugin->getArgs anymore.
307      * @param  request   Request      ??? 
308      * @return array(html,handle)     html for the map interior (to be specific,
309      *                                only &lt;area;&gt; tags defining hot spots)
310      *                                handle is an imagehandle to the corresponding
311      *                                image.
312      *                                array(false,false) if an error occured
313      */
314     function getMap($dbi, $argarray, $request) {
315         trigger_error('WikiPluginCached::getHtml: pure virtual function in file ' 
316                       . __FILE__ . ' line ' . __LINE__, E_USER_ERROR);
317     }
318
319     /* --------------------- produce Html ----------------------------- */
320
321     /** 
322      * Creates an HTML map hyperlinked to the image specified
323      * by url and containing the hotspots given by map.
324      *
325      * @access private
326      * @param  id       string  unique id for the plugin call
327      * @param  url      string  url pointing to the image part of the map
328      * @param  map      string  &lt;area&gt; tags defining active
329      *                          regions in the map
330      * @param  dbi      WikiDB  database abstraction class
331      * @param  argarray array   complete (!) arguments to produce 
332      *                          image. It is not necessary to call 
333      *                          WikiPlugin->getArgs anymore.
334      * @param  request  Request ??? 
335      * @return          string  html output
336      */
337     function embedMap($id,$url,$map,$dbi,$argarray,$request) {
338         // id is not unique if the same map is produced twice
339         $key = substr($id,0,8).substr(microtime(),0,6);
340         return HTML(HTML::map(array( 'name' => $key ), $map ),
341                     HTML::img( array(
342                    'src'    => $url, 
343                    //  'alt'    => htmlspecialchars($this->getAlt($dbi,$argarray,$request)) 
344                    'usemap' => '#'.$key ))
345                );
346     }
347
348     /** 
349      * Creates an HTML &lt;img&gt; tag hyperlinking to the specified
350      * url and produces an alternative text for non-graphical
351      * browsers.
352      *
353      * @access private
354      * @param  url      string  url pointing to the image part of the map
355      * @param  map      string  &lt;area&gt; tags defining active
356      *                          regions in the map
357      * @param  dbi      WikiDB  database abstraction class
358      * @param  argarray array   complete (!) arguments to produce 
359      *                          image. It is not necessary to call 
360      *                          WikiPlugin->getArgs anymore.
361      * @param  request  Request ??? 
362      * @return          string  html output
363      */
364     function embedImg($url,$dbi,$argarray,$request) {
365         return HTML::img( array( 
366             'src' => $url,
367             'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request)) ) );         
368     }
369
370
371 // --------------------------------------------------------------------------
372 // ---------------------- static member functions ---------------------------
373 // --------------------------------------------------------------------------
374
375     /** 
376      * Creates one static PEAR Cache object and returns copies afterwards.
377      * FIXME: There should be references returned
378      *
379      * @access static protected
380      * @return Cache  copy of the cache object
381      */
382     function newCache() {
383         static $staticcache;
384   
385         if (!is_object($staticcache)) {
386             if (!class_exists('Cache')) {
387                 // uuh, pear not in include_path! should print a warning.
388                 // search some possible pear paths.
389                 $pearFinder = new PearFileFinder;
390                 if ($lib = $pearFinder->findFile('Cache.php', 'missing_ok'))
391                     require_once($lib);
392                 else // fall back to our own copy
393                     require_once('lib/pear/Cache.php');
394             }
395             $cacheparams = array();
396             foreach (explode(':','database:cache_dir:filename_prefix:highwater:lowwater'
397                              .':maxlifetime:maxarglen:usecache:force_syncmap') as $key) {
398                 $cacheparams[$key] = constant('PLUGIN_CACHED_'.strtoupper($key));
399             }
400             $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES);
401             $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams);
402             $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME;
403  
404             if (! PLUGIN_CACHED_USECACHE ) {
405                 $staticcache->setCaching(false);
406             }
407         }
408         return $staticcache; // FIXME: use references ?
409     }
410
411     /** 
412      * Determines whether a needed image type may is available 
413      * from the GD library and gives an alternative otherwise.
414      *
415      * @access  public static
416      * @param   wish   string one of 'png', 'gif', 'jpeg', 'jpg'
417      * @return         string the image type to be used ('png', 'gif', 'jpeg')
418      *                        'html' in case of an error
419      */
420
421     function decideImgType($wish) {
422         if ($wish=='html') return $wish;                 
423         if ($wish=='jpg') { $wish = 'jpeg'; }
424
425         $supportedtypes = array();
426         // Todo: swf, pdf, ...
427         $imagetypes = array(  
428             'png'   => IMG_PNG,
429             'gif'   => IMG_GIF,                             
430             'jpeg'  => IMG_JPEG,
431             'wbmp'  => IMG_WBMP,
432             'xpm'   => IMG_XPM,
433             /* // these do work but not with the ImageType bitmask
434             'gd'    => IMG_GD,
435             'gd2'   => IMG_GD,
436             'xbm'   => IMG_XBM,
437             */
438             );
439
440         $presenttypes = ImageTypes();
441         foreach($imagetypes as $imgtype => $bitmask)
442             if ( $presenttypes && $bitmask )
443                 array_push($supportedtypes, $imgtype);        
444
445         if (in_array($wish, $supportedtypes)) 
446             return $wish;
447         elseif (!empty($supportedtypes))
448             return reset($supportedtypes);
449         else
450             return 'html';
451         
452     } // decideImgType
453
454
455     /** 
456      * Writes an image into a file or to the browser.
457      * Note that there is no check if the image can 
458      * be written.
459      *
460      * @access  public static
461      * @param   imgtype   string 'png', 'gif' or 'jpeg'
462      * @param   imghandle string image handle containing the image
463      * @param   imgfile   string file name of the image to be produced
464      * @return  void
465      * @see     decideImageType
466      */
467     function writeImage($imgtype, $imghandle, $imgfile=false) {
468         if ($imgtype != 'html') {
469             $func = "Image" . strtoupper($imgtype);    
470             if ($imgfile) {
471                 $func($imghandle,$imgfile);
472             } else {
473                 $func($imghandle);
474             }
475         }
476     } // writeImage
477
478
479     /** 
480      * Sends HTTP Header for some predefined file types.
481      * There is no parameter check.
482      *
483      * @access  public static
484      * @param   doctype string 'gif', 'png', 'jpeg', 'html'
485      * @return  void 
486      */
487     function writeHeader($doctype) {
488         static $IMAGEHEADER = array( 
489             'gif'  => 'Content-type: image/gif',
490             'png'  => 'Content-type: image/png',
491             'jpeg' => 'Content-type: image/jpeg',
492             'xbm'  => 'Content-type: image/xbm',
493             'xpm'  => 'Content-type: image/xpm',
494             'gd'   => 'Content-type: image/gd',
495             'gd2'  => 'Content-type: image/gd2',
496             'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such.
497             'html' => 'Content-type: text/html' );
498        // Todo: swf, pdf
499        Header($IMAGEHEADER[$doctype]);
500     }
501
502
503     /** 
504      * Converts argument array to a string of format option="value". 
505      * This should only be used for displaying plugin options for 
506      * the quoting of arguments is not safe, yet.
507      *
508      * @access public static
509      * @param  argarray array   contains all arguments to be converted
510      * @return          string  concated arguments
511      */
512     function glueArgs($argarray) {
513         if (!empty($argarray)) {
514             $argstr = '';
515             while (list($key,$value)=each($argarray)) {
516                 $argstr .= $key. '=' . '"' . $value . '" ';  
517             // FIXME FIXME: How are values quoted? Can a value contain " ?
518             }
519             return substr($argstr,0,strlen($argstr)-1);
520         }
521         return '';
522     } // glueArgs
523
524     // ---------------------- FetchImageFromCache ------------------------------
525
526     /** 
527      * Extracts the cache entry id from the url and the plugin call
528      * parameters if available.
529      *
530      * @access private static
531      * @param  id           string   return value. Image is stored under this id.
532      * @param  plugincall   string   return value. Only returned if present in url.
533      *                               Contains all parameters to reconstruct
534      *                               plugin call.
535      * @param  cache        Cache    PEAR Cache object
536      * @param  request      Request  ???
537      * @param  errorformat  string   format which should be used to
538      *                               output errors ('html', 'png', 'gif', 'jpeg')
539      * @return boolean               false if an error occurs, true otherwise.
540      *                               Param id and param plugincall are
541      *                               also return values.
542      */
543     function checkCall1(&$id, &$plugincall,$cache,$request, $errorformat) {
544         $id=$request->getArg('id');
545         $plugincall=rawurldecode($request->getArg('args')); 
546
547         if (!$id) {
548            if (!$plugincall) {
549                 // This should never happen, so do not gettextify.
550                 $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters.";
551                 WikiPluginCached::printError($errorformat, $errortext);
552                 return false;
553             } else {
554                 $id = $cache->generateId( $plugincall );
555             }
556         }   
557         return true;     
558     } // checkCall1
559
560
561     /** 
562      * Extracts the parameters necessary to reconstruct the plugin
563      * call needed to produce the requested image. 
564      *
565      * @access static private  
566      * @param  plugincall string   reference to serialized array containing both 
567      *                             name and parameters of the plugin call
568      * @param  request    Request  ???
569      * @return            boolean  false if an error occurs, true otherwise.
570      *                 
571      */
572     function checkCall2(&$plugincall,$request) {
573         // if plugincall wasn't sent by URL, it must have been
574         // stored in a session var instead and we can retreive it from there
575         if (!$plugincall) {
576             if (!$plugincall=$request->getSessionVar('imagecache'.$id)) {
577                 // I think this is the only error which may occur
578                 // without having written bad code. So gettextify it.
579                 $errortext = sprintf(
580                     gettext ("There is no image creation data available to id '%s'. Please reload referring page." ),
581                     $id );  
582                 WikiPluginCached::printError($errorformat, $errortext);
583                 return false; 
584             }       
585         }
586         $plugincall = unserialize($plugincall);
587         return true;
588     } // checkCall2
589
590
591     /** 
592      * Creates an image or image map depending on the plugin type. 
593      * @access static private 
594      * @param  content array             reference to created array which overwrite the keys
595      *                                   'image', 'imagetype' and possibly 'html'
596      * @param  plugin  WikiPluginCached  plugin which is called to create image or map
597      * @param  dbi     WikiDB            handle to database
598      * @param  argarray array            Contains all arguments needed by plugin
599      * @param  request Request           ????
600      * @param  errorformat string        outputs errors in 'png', 'gif', 'jpg' or 'html'
601      * @return boolean                   error status; true=ok; false=error
602      */
603     function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat) {
604         $plugin->resetError();
605         $content['html'] = $imagehandle = false;
606         if ($plugin->getPluginType() == PLUGIN_CACHED_MAP ) {
607             list($imagehandle,$content['html']) = $plugin->getMap($dbi, $argarray, $request);
608         } else {
609             $imagehandle = $plugin->getImage($dbi, $argarray, $request);
610         }
611
612         $content['imagetype'] 
613             = WikiPluginCached::decideImgType($plugin->getImageType($dbi, $argarray, $request));
614         $errortext = $plugin->getError();
615
616         if (!$imagehandle||$errortext) {
617             if (!$errortext) {
618                 $errortext = "'<?plugin ".$plugin->getName(). ' '
619                     . WikiPluginCached::glueArgs($argarray)." ?>' returned no image, " 
620                     . " although no error was reported.";
621             }
622             WikiPluginCached::printError($errorformat, $errortext);
623             return false; 
624         }
625
626         // image handle -> image data        
627         //$cacheparams = $GLOBALS['CacheParams'];
628         $tmpfile = $this->tempnam();
629         WikiPluginCached::writeImage($content['imagetype'], $imagehandle, $tmpfile);             
630         ImageDestroy($imagehandle);
631         if (file_exists($tmpfile)) {
632             $fp = fopen($tmpfile,'rb');
633             $content['image'] = fread($fp,filesize($tmpfile));
634             fclose($fp);
635             unlink($tmpfile);
636             if ($content['image'])
637                 return true;
638         }
639         return false;
640     } // produceImage
641
642     function tempnam($prefix = false) {
643         return tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR) : PLUGIN_CACHED_CACHE_DIR,
644                        $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX);
645     }
646
647     /** 
648      * Main function for obtaining images from cache or generating on-the-fly
649      * from parameters sent by url or session vars.
650      *
651      * @access static public
652      * @param  dbi     WikiDB            handle to database
653      * @param  request Request           ???
654      * @param  errorformat string        outputs errors in 'png', 'gif', 'jpeg' or 'html'
655      */
656     function fetchImageFromCache($dbi,$request,$errorformat='png') {
657         $cache   = WikiPluginCached::newCache();      
658         $errorformat = WikiPluginCached::decideImgType($errorformat);
659
660         if (!WikiPluginCached::checkCall1($id,$plugincall,$cache,$request,$errorformat)) return false;
661
662         // check cache 
663         $content = $cache->get($id,'imagecache');
664
665         if ($content && $content['image']) {
666             WikiPluginCached::writeHeader($content['imagetype']);
667             print $content['image']; 
668             return true;
669         } 
670
671         // produce image, now. At first, we need plugincall parameters
672         if (!WikiPluginCached::checkCall2($plugincall,$request)) return false;
673
674         $pluginname = $plugincall['pluginname'];
675         $argarray   = $plugincall['arguments'];
676
677         $loader = new WikiPluginLoader;
678         $plugin = $loader->getPlugin($pluginname);
679
680         // cache empty, but image maps have to be created _inline_
681         // so ask user to reload wiki page instead
682         //$cacheparams = $GLOBALS['CacheParams'];
683         if (($plugin->getPluginType() == PLUGIN_CACHED_MAP) && PLUGIN_CACHED_FORCE_SYNCMAP) {
684             $errortext = _("Image map expired. Reload wiki page to recreate its html part.");
685             WikiPluginCached::printError($errorformat, $errortext);
686         }
687
688         
689         if (!WikiPluginCached::produceImage($content, $plugin, $dbi, $argarray, 
690                                             $request, $errorformat) ) return false;
691
692         $expire = $plugin->getExpire($dbi,$argarray,$request);
693
694         if ($content['image']) {
695             $cache->save($id, $content, $expire,'imagecache');
696             WikiPluginCached::writeHeader($content['imagetype']); 
697             print $content['image'];
698             return true;
699         }
700
701         $errortext = "Could not create image file from imagehandle.";
702         WikiPluginCached::printError($errorformat, $errortext);
703         return false; 
704     } // FetchImageFromCache
705
706     // -------------------- error handling ---------------------------- 
707
708     /** 
709      * Resets buffer containing all error messages. This is allways
710      * done before invoking any abstract creation routines like
711      * <code>getImage</code>.
712      *
713      * @access private
714      * @return void
715      */
716     function resetError() {
717         $this->_errortext = '';
718     }
719        
720     /** 
721      * Returns all accumulated error messages. 
722      *
723      * @access protected
724      * @return string error messages printed with <code>complain</code>.
725      */
726     function getError() {
727         return $this->_errortext;
728     }
729
730     /** 
731      * Collects the error messages in a string for later output 
732      * by WikiPluginCached. This should be used for any errors
733      * that occur during data (html,image,map) creation.
734      * 
735      * @access protected
736      * @param  addtext string errormessage to be printed (separate 
737      *                        multiple lines with '\n')
738      * @return void
739      */
740     function complain($addtext) {
741         $this->_errortext .= $addtext;
742     }
743
744     /** 
745      * Outputs the error as image if possible or as html text 
746      * if wished or html header has already been sent.
747      *
748      * @access static protected
749      * @param  imgtype string 'png', 'gif', 'jpeg' or 'html'
750      * @param  errortext string guess what?
751      * @return void
752      */
753     function printError($imgtype, $errortext) {
754        $imgtype = WikiPluginCached::decideImgType($imgtype);
755
756        $talkedallready = ob_get_contents() || headers_sent();
757        if (($imgtype=='html') || $talkedallready) {
758            trigger_error($errortext, E_USER_WARNING);
759        } else {
760            $red = array(255,0,0);
761            $grey = array(221,221,221);
762            $im = WikiPluginCached::text2img($errortext, 2, $red, $grey);
763            if (!$im) { 
764                trigger_error($errortext, E_USER_WARNING);
765                return;
766            }
767            WikiPluginCached::writeHeader($imgtype);
768            WikiPluginCached::writeImage($imgtype, $im); 
769            ImageDestroy($im);
770        }
771     } // printError
772
773
774     /** 
775      * Basic text to image converter for error handling which allows
776      * multiple line output.
777      * It will only output the first 25 lines of 80 characters. Both 
778      * values may be smaller if the chosen font is to big for there
779      * is further restriction to 600 pixel in width and 350 in height.
780      * 
781      * @access static public
782      * @param  txt     string  multi line text to be converted
783      * @param  fontnr  integer number (1-5) telling gd which internal font to use;
784      *                         I recommend font 2 for errors and 4 for help texts.
785      * @param  textcol array   text color as a list of the rgb components; array(red,green,blue)
786      * @param  bgcol   array   background color; array(red,green,blue)
787      * @return string          image handle for gd routines
788      */
789     function text2img($txt,$fontnr,$textcol,$bgcol) {
790         // basic (!) output for error handling
791
792         // check parameters
793         if ($fontnr<1 || $fontnr>5) {
794             $fontnr = 2;
795         }
796         if (!is_array($textcol) || !is_array($bgcol)) {
797                 $textcol = array(0,0,0);
798                 $bgcol = array(255,255,255);
799         }
800         foreach( array_merge($textcol,$bgcol) as $component) {
801             if ($component<0 || $component > 255) {
802                 $textcol = array(0,0,0);
803                 $bgcol = array(255,255,255);
804                 break;
805             }
806         }
807
808         // prepare Parameters 
809         
810         // set maximum values
811         $IMAGESIZE  = array(
812             'cols'   => 80,
813             'rows'   => 25,
814             'width'  => 600,
815             'height' => 350 );
816
817         $charx    = ImageFontWidth($fontnr);
818         $chary    = ImageFontHeight($fontnr);
819         $marginx  = $charx;
820         $marginy  = floor($chary/2);
821
822         $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width']  - 2*$marginx )/$charx));
823         $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2*$marginy )/$chary));
824
825         // split lines
826         $y = 0;
827         $wx = 0;
828         do {
829             $len = strlen($txt);
830             $npos = strpos($txt, "\n");
831
832             if ($npos===false) {
833                 $breaklen = min($IMAGESIZE['cols'],$len);
834             } else {
835                 $breaklen = min($npos+1, $IMAGESIZE['cols']);
836             }
837             $lines[$y] = chop(substr($txt, 0, $breaklen));
838             $wx = max($wx,strlen($lines[$y++]));
839             $txt = substr($txt, $breaklen); 
840         } while ($txt && ($y < $IMAGESIZE['rows']));
841
842         // recalculate image size
843         $IMAGESIZE['rows'] = $y;
844         $IMAGESIZE['cols'] = $wx;
845  
846         $IMAGESIZE['width']  = $IMAGESIZE['cols'] * $charx + 2*$marginx;
847         $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2*$marginy;
848
849         // create blank image
850         $im = @ImageCreate($IMAGESIZE['width'],$IMAGESIZE['height']);
851
852         $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]); 
853         $bg  = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]); 
854
855         ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width']-1, $IMAGESIZE['height']-1, $bg);
856     
857         // write text lines
858         foreach($lines as $nr => $textstr) {
859             ImageString( $im, $fontnr, $marginx, $marginy+$nr*$chary, 
860                          $textstr, $col );
861         }
862         return $im;
863     } // text2img
864
865 } // WikiPluginCached
866
867
868 // $Log: not supported by cvs2svn $
869
870 // For emacs users
871 // Local Variables:
872 // mode: php
873 // tab-width: 4
874 // c-basic-offset: 4
875 // c-hanging-comment-ender-p: nil
876 // indent-tabs-mode: nil
877 // End:
878 ?>