-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclass.latex-vb.php
345 lines (282 loc) · 11.5 KB
/
class.latex-vb.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
/*
* class.latex.php: Small class for rendering LaTeX formulae
* Author: David Moxey
*/
// Input environments:
define('LATEX_INPUT_NORM', 1); // Normal 'displaymath' environment
define('LATEX_INPUT_INLINE', 2); // For inline text
define('LATEX_INPUT_CHEM', 3); // Chemical equations (requires mhchem)
define('LATEX_INPUT_PGF', 4); // PGF pictures.
// Output environments:
define('LATEX_OUTPUT_PNG', 'png');
define('LATEX_OUTPUT_GIF', 'gif');
// Errors:
define('LATEX_ERROR_TOOLONG', -1); // Message too long
define('LATEX_ERROR_BADWORD', -2); // String included a bad word
define('LATEX_ERROR_NODIR', -3); // Directory(ies) don't exist
define('LATEX_ERROR_NOPERM', -4); // Directory(ies) aren't writeable
define('LATEX_ERROR_TOOBIG', -5); // Dimensions of resultant image are too big
define('LATEX_ERROR_SYNTAX', -6); // Syntax error
define('LATEX_ERROR_COPY', -7); // Copy error
class Latex {
/**************** BEGIN CONFIGURATION *****************/
/*
* Path information: this is important!
* Alter the information below according to your system.
* 'latex': path to LaTeX application
* 'dvipng': path to dvipng application
*
* 'base': base directory of your latex/ directory, WITHOUT trailing slash
* 'baseurl': the URL to your latex directory, WITHOUT trailing slash
*
* For example, if my LaTeX directory was /home/dave/public_html/latex then:
* 'base' => '/home/dave/public_html/latex'
* 'baseurl' => 'http://my.domain.name/~dave/latex'
*/
var $path = array(
// Applications
'latex' => '/usr/bin/latex',
'dvipng' => '/usr/bin/dvipng',
'mogrify' => '/usr/bin/mogrify',
'convert' => '/usr/bin/convert',
// Base directory
'base' => '/www/scienceforums.net/html/latex',
'baseurl' => '/latex'
);
/*
* Presentation information:
* 'class': LaTeX class to use in \documentclass call
* 'fontsize': Font size to use in \documentclass call
* 'extrapackages': An array of extra packages you might want to use
* 'format': Default output format. LATEX_OUTPUT_PNG or LATEX_OUTPUT_GIF
* for GIF and PNG respectively.
* 'retina': Create retina images.
*/
var $display = array(
'class' => 'article',
'fontsize' => '18pt',
'extrapackages' => array('amsmath', 'amsfonts', 'amssymb', 'color', 'slashed'),
'format' => LATEX_OUTPUT_PNG,
'retina' => true
);
/*
* dvipng options:
* 'background': You can either choose transparent for a transparent
* background, or a colour. The format of the colour must
* be 'rgb 1.0 0.0 0.0'; for example, this defines red. See
* the example below.
* 'foreground': Not implemented yet.
* 'density': Density to render image at. 100 is about right for most
* applications.
* 'gamma': Apply gamma to image - 1.0 to leave untouched.
* 'resample': Use mogrify to resample this image. This ends up improving
* image quality by better anti-aliasing lines.
*/
var $dvipng = array(
'background' => 'Transparent',
//'background' => "'rgb 1.0 0.0 0.0'",
'foreground' => false,
'density' => '300',
'gamma' => '2.0',
'resample' => '130'
);
/********* Security Options **********/
// Maximum lengths of input string for each type
var $str_length = array(
LATEX_INPUT_NORM => 1000,
LATEX_INPUT_INLINE => 200,
LATEX_INPUT_CHEM => 200,
LATEX_INPUT_PGF => 8000
);
// Maximum image dimensions
var $image_dim = array(
LATEX_INPUT_NORM => array(1000, 800),
LATEX_INPUT_INLINE => array(500, 200),
LATEX_INPUT_CHEM => array(600, 200),
LATEX_INPUT_PGF => array(1500, 1500)
);
// Barred commands: taken from LatexRender - best not to alter
var $barred_commands = array(
'include', 'def', 'command', 'loop', 'repeat', 'open', 'toks', 'output', 'input',
'catcode', 'name', '^^',
'\\every', '\\errhelp', '\\errorstopmode', '\\scrollmode', '\\nonstopmode', '\\batchmode',
'\\read', '\\write', 'csname', '\\newhelp', '\\uppercase', '\\lowercase', '\\relax', '\\aftergroup',
'\\afterassignment', '\\expandafter', '\\noexpand', '\\special'
);
/*********** END CONFIGURATION **********/
var $tmp_filename;
var $md5hash;
var $method = LATEX_INPUT_NORM;
var $currentdir = '';
function Latex($inputmethod, $outputmethod=FALSE)
{
$this->method = $inputmethod;
if ($outputmethod)
$this->display['format'] = $outputmethod;
if ($this->display['format'] == LATEX_OUTPUT_GIF)
$this->path['dvipng'] .= " --gif";
$this->path['tmp'] = $this->path['base'].'/tmp';
$this->path['img'] = $this->path['base'].'/img';
}
function renderLatex($latexstring)
{
$this->tmp_filename = md5(rand());
$this->currentdir = getcwd();
$path = $this->path;
$latexstring = trim($latexstring);
$this->md5hash = md5($latexstring);
$filename = $this->md5hash.'-'.$this->method.'.' .$this->display['format'];
$filename_retina = $this->md5hash.'-'.$this->method.'@2x.'.$this->display['format'];
// Check existance of correct folders/permissions
if (!is_dir($path['base']) || !is_dir($path['tmp']) || !is_dir($path['img']))
return $this->error(LATEX_ERROR_NODIR, '');
if (!is_writeable($path['tmp']) || !is_writeable($path['img']))
return $this->error(LATEX_ERROR_NOPERM, '');
$d1 = substr($this->md5hash, 0, 1);
$d2 = substr($this->md5hash, 1, 1);
$imgpath = $path['img'].'/'.$d1.'/'.$d2.'/';
// Check whether this image already exists
if (is_file($imgpath.$filename)) {
$imageinfo = @getimagesize($imgpath.$filename);
$url = $this->path['baseurl']."/img/".$d1."/".$d2."/".$filename;
$tmparr = array(array($url), $imageinfo[0], $imageinfo[1]);
if ($this->display['retina'])
{
array_push($tmparr[0], $this->path['baseurl']."/img/".$d1."/".$d2."/".$filename_retina);
}
return $tmparr;
}
// Do security checks
if ($this->str_length[$this->method] != 0 && strlen($latexstring) > $this->str_length[$this->method])
return $this->error(LATEX_ERROR_TOOLONG, strlen($latexstring));
foreach ($this->barred_commands as $command) {
if (stristr($latexstring, $command))
return $this->error(LATEX_ERROR_BADWORD, $command);
}
// Store current directory and
chdir($path['tmp']);
// Wrap out string as snug as a bug in a rug and output it to something
$tmp_file = fopen($path['tmp'].'/'.$this->tmp_filename.'.tex', 'w');
fwrite($tmp_file, $this->wrapFormula($latexstring));
fclose($tmp_file);
// Compile command
$command = $path['latex']." --interaction=nonstopmode ".$this->tmp_filename.".tex && ".
$path['dvipng']." -q -D ".$this->dvipng['density']." -T tight -gamma ".$this->dvipng['gamma']." -bg ".$this->dvipng['background']." -o $filename ".$this->tmp_filename.".dvi";
exec($command);
if (!is_readable($filename))
return $this->error(LATEX_ERROR_SYNTAX, '', true);
// Run through convert utility if required.
if (isset($this->dvipng['resample'])) {
if (!$this->display['retina']) {
$command = $path['mogrify']." -density ".$this->dvipng['density']." -filter Lanczos -resample ".$this->dvipng['resample']." -sharpen 2 $filename";
exec($command);
} else {
$newsample = intval($this->dvipng['resample'])*2;
$command = $path['convert']." $filename -density ".$this->dvipng['density']." -filter Lanczos -resample $newsample -sharpen 2 $filename_retina";
exec($command);
$command = $path['mogrify']." -density ".$this->dvipng['density']." -filter Lanczos -resample ".$this->dvipng['resample']." -sharpen 2 $filename";
exec($command);
}
}
// Security check: image height/width
$imageinfo = @getimagesize($filename);
if ($this->image_dim[$this->method] != NULL && ($imageinfo[0] > $this->image_dim[$this->method][0] || $imageinfo[1] > $this->image_dim[$this->method][1]))
return $this->error(LATEX_ERROR_TOOBIG, $imageinfo[0].'x'.$imageinfo[1], true);
// Create an appropriate subdirectory structure for hash.
@mkdir($path['img'].'/'.$d1.'/'.$d2, 0777, true);
$copy = @copy($filename, $imgpath.$filename);
if (!$copy)
return $this->error(LATEX_ERROR_COPY, '', true);
if ($this->display['retina']) {
$copy = @copy($filename_retina, $imgpath.$filename_retina);
if (!$copy)
return $this->error(LATEX_ERROR_COPY, '', true);
}
$this->cleanTmpDir();
chdir($this->currentdir);
$tmparr = array(array($this->path['baseurl']."/img/".$d1.'/'.$d2.'/'.$filename), $imageinfo[0], $imageinfo[1]);
if ($this->display['retina']) {
array_push($tmparr[0], $this->path['baseurl']."/img/".$d1.'/'.$d2.'/'.$filename_retina);
}
return $tmparr;
}
function wrapFormula($latexstring)
{
$wrap = "\documentclass[".$this->display['fontsize']."]{".$this->display['class']."}\n";
$wrap .= "\pagestyle{empty}\n";
foreach ($this->display['extrapackages'] as $extra)
$wrap .= "\usepackage{".$extra."}\n";
switch ($this->method) {
case LATEX_INPUT_CHEM:
$wrap .= "\usepackage[version=3]{mhchem}\n";
break;
case LATEX_INPUT_PGF:
$wrap .= "\usepackage{tikz}\n";
break;
}
$wrap .= "\begin{document}\n";
switch ($this->method) {
case LATEX_INPUT_NORM:
$wrap .= "\\[ $latexstring \\]\n";
break;
case LATEX_INPUT_INLINE:
$wrap .= "$ $latexstring $\n";
break;
case LATEX_INPUT_CHEM:
$wrap .= "\\ce{".$latexstring."}\n";
break;
case LATEX_INPUT_PGF:
$wrap .= "\\begin{tikzpicture}\n";
$wrap .= $latexstring;
$wrap .= "\\end{tikzpicture}\n";
break;
}
$wrap .= "\\end{document}\n";
return $wrap;
}
function error($errorcode, $detail, $chdir=false)
{
$err = 'Error: ';
switch ($errorcode) {
case LATEX_ERROR_TOOLONG:
$err .= "String is too long (".$detail.", limit ".$this->str_length[$this->method].")";
break;
case LATEX_ERROR_BADWORD:
$err .= 'Restricted command found ('.$detail.')';
break;
case LATEX_ERROR_NODIR:
$err .= 'One or more directories do not exist';
break;
case LATEX_ERROR_NOPERM:
$err .= "Can't write to directory";
break;
case LATEX_ERROR_TOOBIG:
$err .= 'Image is too big ('.$detail.', limit '.implode('x', $this->image_dim[$this->method]).')';
break;
case LATEX_ERROR_SYNTAX:
$err .= 'Syntax error';
break;
case LATEX_ERROR_COPY:
$err .= "Couldn't copy temporary file";
break;
}
if ($chdir) {
chdir($this->currentdir);
$this->cleanTmpDir();
}
return $err;
}
function cleanTmpDir()
{
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.tex');
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.aux');
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.log');
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.dvi');
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.ps');
@unlink($this->path['tmp'].'/'.$this->tmp_filename.'.'.$this->display['format']);
@unlink($this->path['tmp'].'/'.$this->md5hash.'-'.$this->method.'.'.$this->display['format']);
@unlink($this->path['tmp'].'/'.$this->md5hash.'-'.$this->method.'@2x.'.$this->display['format']);
}
}
?>