]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/TexToPng.php
Gettext-ify description & small bugfix.
[SourceForge/phpwiki.git] / lib / plugin / TexToPng.php
1 <?php // -*-php-*-
2 // +---------------------------------------------------------------------+
3 // | TexToPng.php                                                        |
4 // +---------------------------------------------------------------------+
5 // | This is a WikiPlugin that surrounds tex commands given as parameter |
6 // | with a page description and renders it using several existing       |
7 // | engines into a gif, png or jpeg file.                               |
8 // | TexToPng is usage example for WikiPluginCached.                     |
9 // |                                                                     |
10 // | Copyright (C) 2002 Johannes Große (Johannes Gro&szlig;e)            |
11 // | You may copy this code freely under the conditions of the GPL       |
12 // +---------------------------------------------------------------------+
13
14 /*-----------------------------------------------------------------------
15  | CONFIGURATION
16  *----------------------------------------------------------------------*/
17 // needs (la)tex, dvips, gs, netpbm, libpng
18 // LaTeX2HTML ftp://ftp.dante.de/tex-archive/support/latex2html
19 $texbin = '/usr/bin/tex';
20 $dvipsbin = '/usr/bin/dvips';
21 $pstoimgbin = '/usr/bin/pstoimg';
22
23 // output mere debug messages (should be set to false in a stable 
24 // version)
25    define('TexToPng_debug', false);                                          
26
27 /*-----------------------------------------------------------------------
28  | OPTION DEFAULTS                                                      
29  *----------------------------------------------------------------------*/ 
30 /*----
31  | use antialias for rendering;
32  | anitalias: blurs, _looks better_, needs twice space, renders slowlier
33  |                                                                      */  
34    define('TexToPng_antialias', true);    
35
36 /*----
37  | Use transparent background; dont combine with antialias on a dark 
38  | background. Seems to have a bug: produces strange effects for some 
39  | ps-files (almost non readable,blurred output) even when directly 
40  | invoked from shell. So its probably a pstoimg bug.
41  |                                                                      */  
42    define('TexToPng_transparent', false);
43
44 /*----
45  | default value for rescaling
46  | allowed range: 0 - 5 (integer) 
47  |                                                                      */  
48    define('TexToPng_magstep', 3);            
49
50
51 /*-----------------------------------------------------------------------
52  |
53  |  Source
54  |
55  *----------------------------------------------------------------------*/
56
57 // check boolean constants
58
59    if (!defined('TexToPng_debug'))       { define('TexToPng_debug', false); }
60    if (!defined('TexToPng_antialias'))   { define('TexToPng_antialias', false); }
61    if (!defined('TexToPng_transparent')) { define('TexToPng_transparent', false); }
62
63 /*-----------------------------------------------------------------------
64  | WikiPlugin_TexToPng
65  *----------------------------------------------------------------------*/
66
67 require_once "lib/WikiPluginCached.php";
68
69 class WikiPlugin_TexToPng extends WikiPluginCached
70 {   
71     /* --------- overwrite virtual or abstract methods ---------------- */ 
72
73     function getPluginType() {
74         return PLUGIN_CACHED_IMG_ONDEMAND;
75     }
76  
77     function getName() {
78         return "TexToPng";
79     }
80
81     function getDescription() {
82         return _("Converts TeX to an image. May be used to embed formulas in PhpWiki.");
83     }
84
85     function getDefaultArguments() {
86         return array('tex'          => "",
87                      'magstep'      => TexToPng_magstep,
88                      'img'          => 'png',
89                      'subslash'     => 'off',
90                      'antialias'    => TexToPng_antialias   ? 'on' : 'off',
91                      'transparent'  => TexToPng_transparent ? 'on' : 'off', 
92                      'center'       => 'off');
93     }
94
95     function getImage($dbi, $argarray, $request) {
96         extract($argarray);
97         $this->checkParams($tex, $magstep, $subslash, $antialias, $transparent);
98         return $this->TexToImg($tex, $magstep, $antialias, $transparent);
99     } // run
100
101     function getExpire($dbi, $argarray, $request) {
102         return '0';
103     }
104
105     function getImageType($dbi, $argarray, $request) {
106         extract($argarray);
107         return $img;
108     }
109
110     function getAlt($dbi, $argarray, $request) {
111         extract($argarray); 
112         return $tex; 
113     }
114
115     function embedImg($url,$dbi,$argarray,$request) {
116         $html = HTML::img( array( 
117             'src'   => $url,
118             'alt'   => htmlspecialchars($this->getAlt($dbi,$argarray,$request))
119             )); 
120         if ($argarray['center']=='on')
121             return HTML::div( array('style' => 'text-align:center;'), $html);
122         return $html;
123     }
124
125     /* -------------------- error handling ---------------------------- */
126
127     function dbg( $out ) {
128         // test if verbose debug info is selected
129         if (TexToPng_debug) {
130             $this->complain( $out."\n" );
131         } else {
132             if (!$this->_errortext) {
133                 // yeah, I've been told to be quiet, but obviously 
134                 // an error occured. So at least complain silently.
135                 $this->complain(' ');
136             }
137         }
138
139     } // dbg
140
141     /* -------------------- parameter handling ------------------------ */
142
143     function helptext() {
144         $aa= TexToPng_antialias  ?'on(default)$|$off':'on$|$off(default)';
145         $tp= TexToPng_transparent?'on(default)$|$off':'on$|$off(default)';
146         $help = 
147           '/settabs/+/indent&$<$?plugin /bf{Tex} & [{/tt transparent}] & = "png(default)$|$jpeg$|$gif"& /cr'."\n".
148           '/+&$<$?plugin /bf{TexToPng} & /hfill {/tt tex}           & = "/TeX/  commands"& /cr'."\n".
149           '/+&                         & /hfill [{/tt img}]         & = "png(default)$|$jpeg$|$gif"& /cr'."\n".
150           '/+&                         & /hfill [{/tt magstep}]     & = "0 to 5 ('.TexToPng_magstep.' default)"& /cr'."\n".
151           '/+&                         & /hfill [{/tt center}]      & = "on$|$off(default)"& /cr'."\n".
152           '/+&                         & /hfill [{/tt subslash}]    & = "on$|$off(default)"& /cr'."\n".
153           '/+&                         & /hfill [{/tt antialias}]   & = "'.$aa.'"& /cr'."\n".
154           '/+&                         & /hfill [{/tt transparent}] & = "'.$tp.'"&?$>$ /cr'."\n";
155       
156         return strtr($help, '/', '\\' );
157     } // helptext    
158
159
160     function checkParams( &$tex, &$magstep, $subslash, &$aalias, &$transp ) {  
161
162         if ($subslash=='on') {
163             // WORKAROUND for backslashes
164             $tex = strtr($tex,'/','\\');
165         }
166
167         // ------- check parameters
168         $def = $this->getDefaultArguments();
169
170         if ($tex=='') { $tex = $this->helptext(); }
171
172         if ($magstep < 0 || $magstep > 5 ) { $magstep = $def["magstep"]; }
173         // calculate magnification factor
174         $magstep = floor(10*pow(1.2,$magstep))/10; 
175
176         $aalias = $aalias != 'off';
177         $transp = $transp != 'off';
178
179     } // checkParams
180
181     /* ------------------ image creation ------------------------------ */
182
183     function execute($cmd,$complainvisibly=false) {
184         exec($cmd, $errortxt, $returnval);
185         $ok = $returnval == 0;
186         
187         if (!$ok) {
188             if (!$complainvisibly) {
189                  $this->dbg('Error during execution of '.$cmd );                         
190             };
191             while (list($key,$value)=each($errortxt)) {
192                 if ($complainvisibly) { 
193                     $this->complain( $value."\n" );
194                 } else {
195                     $this->dbg( $value );             
196                 }
197             }
198         }
199         return $ok;
200     } // execute
201
202     /* ---------------------------------------------------------------- */
203
204     function createTexFile($texfile,$texstr) {
205         if ($ok=($fp=fopen($texfile, 'w'))!=0 ) {
206             // prepare .tex file
207             $texcommands = 
208                 '\nopagenumbers'   . "\n" .
209                 '\hoffset=0cm'     . "\n" .
210                 '\voffset=0cm'     . "\n" . 
211             //    '\hsize=20cm'    . "\n" .
212             //    '\vsize=10ex'    . "\n" .
213                 $texstr            . "\n" .
214                 '\vfill\eject'     . "\n" .
215                 '\end'             . "\n\n";
216             
217             $ok = fwrite($fp, $texcommands);
218             $ok = fclose($fp) && $ok;  // close anyway
219         }
220         if (!$ok) {
221             $this->dbg('could not write .tex file: ' . $texstr);
222         }
223         return $ok;
224     } // createTexFile
225
226     /* ---------------------------------------------------------------- */            
227
228     function TexToImg($texstr, $scale, $aalias, $transp) {
229         $cacheparams = $GLOBALS['CacheParams'];        
230         $tempfiles = tempnam($cacheparams['cache_dir'],'TexToPng');
231         $img = 0; // $size = 0;
232
233         // procuce options for pstoimg
234         $options = 
235            ($aalias ? '-aaliastext -color 8 ' : '-color 1 ') .
236            ($transp ? '-transparent ' : '') .
237            '-scale ' . $scale . ' ' .
238            '-type png -crop btlr -geometry 600x150 -margins 0,0';
239
240         // rely on intelligent bool interpretation 
241         $ok= $tempfiles &&
242              $this->createTexFile($tempfiles.'.tex',$texstr) &&
243              $this->execute('cd '.$cacheparams['cache_dir'].'; '.
244                             "$texbin ".$tempfiles.'.tex',true) &&                  
245              $this->execute("$dvipsbin -o".$tempfiles.'.ps '.$tempfiles.'.dvi') &&  
246              $this->execute("$pstoimgbin $options"
247                             .' -out '.$tempfiles.'.png '.
248                             $tempfiles.'.ps'               ) &&
249              file_exists( $tempfiles.'.png' );
250
251         if ($ok) {
252             if (!($img = ImageCreateFromPNG( $tempfiles.'.png' ))) {
253                 $this->dbg("Could not open just created image file: $tempfiles");
254                 $ok = false;
255             }     
256         }
257
258         // clean up tmpdir; in debug mode only if no error occured
259
260         if ( !TexToPng_debug || (TexToPng_debug && $ok))  {
261             if ($tempfiles) {
262                 unlink($tempfiles);
263                 unlink($tempfiles.'.ps');        
264                 unlink($tempfiles.'.tex');
265                 //unlink($tempfiles.'.aux');
266                 unlink($tempfiles.'.dvi');
267                 unlink($tempfiles.'.log');
268                 unlink($tempfiles.'.png');
269             }
270         }
271
272         if ($ok) {
273             return $img; 
274         }
275         return false;
276     } // TexToImg
277 } // WikiPlugin_TexToPng
278
279
280
281 // For emacs users
282 // Local Variables:
283 // mode: php
284 // tab-width: 4
285 // c-basic-offset: 4
286 // c-hanging-comment-ender-p: nil
287 // indent-tabs-mode: nil
288 // End:
289 ?>