]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/Math.php
MediaWiki 1.16.1
[autoinstalls/mediawiki.git] / includes / Math.php
1 <?php
2 /**
3  * Contain everything related to <math> </math> parsing
4  * @file
5  * @ingroup Parser
6  */
7
8 /**
9  * Takes LaTeX fragments, sends them to a helper program (texvc) for rendering
10  * to rasterized PNG and HTML and MathML approximations. An appropriate
11  * rendering form is picked and returned.
12  *
13  * @author Tomasz Wegrzanowski, with additions by Brion Vibber (2003, 2004)
14  * @ingroup Parser
15  */
16 class MathRenderer {
17         var $mode = MW_MATH_MODERN;
18         var $tex = '';
19         var $inputhash = '';
20         var $hash = '';
21         var $html = '';
22         var $mathml = '';
23         var $conservativeness = 0;
24
25         function __construct( $tex, $params=array() ) {
26                 $this->tex = $tex;
27                 $this->params = $params;
28         }
29
30         function setOutputMode( $mode ) {
31                 $this->mode = $mode;
32         }
33
34         function render() {
35                 global $wgTmpDirectory, $wgInputEncoding;
36                 global $wgTexvc, $wgMathCheckFiles, $wgTexvcBackgroundColor;
37
38                 if( $this->mode == MW_MATH_SOURCE ) {
39                         # No need to render or parse anything more!
40                         return ('$ '.htmlspecialchars( $this->tex ).' $');
41                 }
42                 if( $this->tex == '' ) {
43                         return; # bug 8372
44                 }
45
46                 if( !$this->_recall() ) {
47                         if( $wgMathCheckFiles ) {
48                                 # Ensure that the temp and output directories are available before continuing...
49                                 if( !file_exists( $wgTmpDirectory ) ) {
50                                         if( !wfMkdirParents( $wgTmpDirectory ) ) {
51                                                 return $this->_error( 'math_bad_tmpdir' );
52                                         }
53                                 } elseif( !is_dir( $wgTmpDirectory ) || !is_writable( $wgTmpDirectory ) ) {
54                                         return $this->_error( 'math_bad_tmpdir' );
55                                 }
56                         }
57
58                         if( function_exists( 'is_executable' ) && !is_executable( $wgTexvc ) ) {
59                                 return $this->_error( 'math_notexvc' );
60                         }
61                         $cmd = $wgTexvc . ' ' .
62                                         escapeshellarg( $wgTmpDirectory ).' '.
63                                         escapeshellarg( $wgTmpDirectory ).' '.
64                                         escapeshellarg( $this->tex ).' '.
65                                         escapeshellarg( $wgInputEncoding ).' '.
66                                         escapeshellarg( $wgTexvcBackgroundColor );
67
68                         if ( wfIsWindows() ) {
69                                 # Invoke it within cygwin sh, because texvc expects sh features in its default shell
70                                 $cmd = 'sh -c ' . wfEscapeShellArg( $cmd );
71                         }
72
73                         wfDebug( "TeX: $cmd\n" );
74                         $contents = `$cmd`;
75                         wfDebug( "TeX output:\n $contents\n---\n" );
76
77                         if (strlen($contents) == 0) {
78                                 return $this->_error( 'math_unknown_error' );
79                         }
80
81                         $retval = substr ($contents, 0, 1);
82                         $errmsg = '';
83                         if (($retval == 'C') || ($retval == 'M') || ($retval == 'L')) {
84                                 if ($retval == 'C') {
85                                         $this->conservativeness = 2;
86                                 } else if ($retval == 'M') {
87                                         $this->conservativeness = 1;
88                                 } else {
89                                         $this->conservativeness = 0;
90                                 }
91                                 $outdata = substr ($contents, 33);
92
93                                 $i = strpos($outdata, "\000");
94
95                                 $this->html = substr($outdata, 0, $i);
96                                 $this->mathml = substr($outdata, $i+1);
97                         } else if (($retval == 'c') || ($retval == 'm') || ($retval == 'l'))  {
98                                 $this->html = substr ($contents, 33);
99                                 if ($retval == 'c') {
100                                         $this->conservativeness = 2;
101                                 } else if ($retval == 'm') {
102                                         $this->conservativeness = 1;
103                                 } else {
104                                         $this->conservativeness = 0;
105                                 }
106                                 $this->mathml = null;
107                         } else if ($retval == 'X') {
108                                 $this->html = null;
109                                 $this->mathml = substr ($contents, 33);
110                                 $this->conservativeness = 0;
111                         } else if ($retval == '+') {
112                                 $this->html = null;
113                                 $this->mathml = null;
114                                 $this->conservativeness = 0;
115                         } else {
116                                 $errbit = htmlspecialchars( substr($contents, 1) );
117                                 switch( $retval ) {
118                                         case 'E':
119                                                 $errmsg = $this->_error( 'math_lexing_error', $errbit );
120                                                 break;
121                                         case 'S':
122                                                 $errmsg = $this->_error( 'math_syntax_error', $errbit );
123                                                 break;
124                                         case 'F':
125                                                 $errmsg = $this->_error( 'math_unknown_function', $errbit );
126                                                 break;
127                                         default:
128                                                 $errmsg = $this->_error( 'math_unknown_error', $errbit );
129                                 }
130                         }
131
132                         if ( !$errmsg ) {
133                                  $this->hash = substr ($contents, 1, 32);
134                         }
135
136                         wfRunHooks( 'MathAfterTexvc', array( &$this, &$errmsg ) );
137
138                         if ( $errmsg ) {
139                                  return $errmsg;
140                         }
141
142                         if (!preg_match("/^[a-f0-9]{32}$/", $this->hash)) {
143                                 return $this->_error( 'math_unknown_error' );
144                         }
145
146                         if( !file_exists( "$wgTmpDirectory/{$this->hash}.png" ) ) {
147                                 return $this->_error( 'math_image_error' );
148                         }
149
150                         if( filesize( "$wgTmpDirectory/{$this->hash}.png" ) == 0 ) {
151                                 return $this->_error( 'math_image_error' );
152                         }
153
154                         $hashpath = $this->_getHashPath();
155                         if( !file_exists( $hashpath ) ) {
156                                 if( !@wfMkdirParents( $hashpath, 0755 ) ) {
157                                         return $this->_error( 'math_bad_output' );
158                                 }
159                         } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
160                                 return $this->_error( 'math_bad_output' );
161                         }
162
163                         if( !rename( "$wgTmpDirectory/{$this->hash}.png", "$hashpath/{$this->hash}.png" ) ) {
164                                 return $this->_error( 'math_output_error' );
165                         }
166
167                         # Now save it back to the DB:
168                         if ( !wfReadOnly() ) {
169                                 $outmd5_sql = pack('H32', $this->hash);
170
171                                 $md5_sql = pack('H32', $this->md5); # Binary packed, not hex
172
173                                 $dbw = wfGetDB( DB_MASTER );
174                                 $dbw->replace( 'math', array( 'math_inputhash' ),
175                                   array(
176                                         'math_inputhash' => $dbw->encodeBlob($md5_sql),
177                                         'math_outputhash' => $dbw->encodeBlob($outmd5_sql),
178                                         'math_html_conservativeness' => $this->conservativeness,
179                                         'math_html' => $this->html,
180                                         'math_mathml' => $this->mathml,
181                                   ), __METHOD__
182                                 );
183                         }
184                         
185                         // If we're replacing an older version of the image, make sure it's current.
186                         global $wgUseSquid;
187                         if ( $wgUseSquid ) {
188                                 $urls = array( $this->_mathImageUrl() );
189                                 $u = new SquidUpdate( $urls );
190                                 $u->doUpdate();
191                         }
192                 }
193
194                 return $this->_doRender();
195         }
196
197         function _error( $msg, $append = '' ) {
198                 $mf   = htmlspecialchars( wfMsg( 'math_failure' ) );
199                 $errmsg = htmlspecialchars( wfMsg( $msg ) );
200                 $source = htmlspecialchars( str_replace( "\n", ' ', $this->tex ) );
201                 return "<strong class='error'>$mf ($errmsg$append): $source</strong>\n";
202         }
203
204         function _recall() {
205                 global $wgMathDirectory, $wgMathCheckFiles;
206
207                 $this->md5 = md5( $this->tex );
208                 $dbr = wfGetDB( DB_SLAVE );
209                 $rpage = $dbr->selectRow( 'math',
210                         array( 'math_outputhash','math_html_conservativeness','math_html','math_mathml' ),
211                         array( 'math_inputhash' => $dbr->encodeBlob(pack("H32", $this->md5))), # Binary packed, not hex
212                         __METHOD__
213                 );
214
215                 if( $rpage !== false ) {
216                         # Tailing 0x20s can get dropped by the database, add it back on if necessary:
217                         $xhash = unpack( 'H32md5', $dbr->decodeBlob($rpage->math_outputhash) . "                " );
218                         $this->hash = $xhash ['md5'];
219
220                         $this->conservativeness = $rpage->math_html_conservativeness;
221                         $this->html = $rpage->math_html;
222                         $this->mathml = $rpage->math_mathml;
223
224                         $filename = $this->_getHashPath() . "/{$this->hash}.png";
225                         
226                         if( !$wgMathCheckFiles ) {
227                                 // Short-circuit the file existence & migration checks
228                                 return true;
229                         }
230                         
231                         if( file_exists( $filename ) ) {
232                                 if( filesize( $filename ) == 0 ) {
233                                         // Some horrible error corrupted stuff :(
234                                         @unlink( $filename );
235                                 } else {
236                                         return true;
237                                 }
238                         }
239
240                         if( file_exists( $wgMathDirectory . "/{$this->hash}.png" ) ) {
241                                 $hashpath = $this->_getHashPath();
242
243                                 if( !file_exists( $hashpath ) ) {
244                                         if( !@wfMkdirParents( $hashpath, 0755 ) ) {
245                                                 return false;
246                                         }
247                                 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
248                                         return false;
249                                 }
250                                 if ( function_exists( "link" ) ) {
251                                         return link ( $wgMathDirectory . "/{$this->hash}.png",
252                                                         $hashpath . "/{$this->hash}.png" );
253                                 } else {
254                                         return rename ( $wgMathDirectory . "/{$this->hash}.png",
255                                                         $hashpath . "/{$this->hash}.png" );
256                                 }
257                         }
258
259                 }
260
261                 # Missing from the database and/or the render cache
262                 return false;
263         }
264
265         /**
266          * Select among PNG, HTML, or MathML output depending on
267          */
268         function _doRender() {
269                 if( $this->mode == MW_MATH_MATHML && $this->mathml != '' ) {
270                         return Xml::tags( 'math',
271                                 $this->_attribs( 'math',
272                                         array( 'xmlns' => 'http://www.w3.org/1998/Math/MathML' ) ),
273                                 $this->mathml );
274                 }
275                 if (($this->mode == MW_MATH_PNG) || ($this->html == '') ||
276                    (($this->mode == MW_MATH_SIMPLE) && ($this->conservativeness != 2)) ||
277                    (($this->mode == MW_MATH_MODERN || $this->mode == MW_MATH_MATHML) && ($this->conservativeness == 0))) {
278                         return $this->_linkToMathImage();
279                 } else {
280                         return Xml::tags( 'span',
281                                 $this->_attribs( 'span',
282                                         array( 'class' => 'texhtml' ) ),
283                                 $this->html );
284                 }
285         }
286
287         function _attribs( $tag, $defaults=array(), $overrides=array() ) {
288                 $attribs = Sanitizer::validateTagAttributes( $this->params, $tag );
289                 $attribs = Sanitizer::mergeAttributes( $defaults, $attribs );
290                 $attribs = Sanitizer::mergeAttributes( $attribs, $overrides );
291                 return $attribs;
292         }
293
294         function _linkToMathImage() {
295                 $url = $this->_mathImageUrl();
296
297                 return Xml::element( 'img',
298                         $this->_attribs(
299                                 'img',
300                                 array(
301                                         'class' => 'tex',
302                                         'alt' => $this->tex ),
303                                 array(
304                                         'src' => $url ) ) );
305         }
306
307         function _mathImageUrl() {
308                 global $wgMathPath;
309                 $dir = $this->_getHashSubPath();
310                 return "$wgMathPath/$dir/{$this->hash}.png";
311         }
312         
313         function _getHashPath() {
314                 global $wgMathDirectory;
315                 $path = $wgMathDirectory .'/' . $this->_getHashSubPath();
316                 wfDebug( "TeX: getHashPath, hash is: $this->hash, path is: $path\n" );
317                 return $path;
318         }
319         
320         function _getHashSubPath() {
321                 return substr($this->hash, 0, 1)
322                                         .'/'. substr($this->hash, 1, 1)
323                                         .'/'. substr($this->hash, 2, 1);
324         }
325
326         public static function renderMath( $tex, $params=array() ) {
327                 global $wgUser;
328                 $math = new MathRenderer( $tex, $params );
329                 $math->setOutputMode( $wgUser->getOption('math'));
330                 return $math->render();
331         }
332 }