A suggestion to simply extract/merge this functionality from/with another plugin.
[ikiwiki] / IkiWiki / Plugin / teximg.pm
1 #!/usr/bin/perl
2 # Licensed under GPL v2 or greater
3 # (c) 2007 Patrick Winnertz <patrick.winnertz@skolelinux.org>
4
5 package IkiWiki::Plugin::teximg;
6 use warnings;
7 use strict;
8 use Digest::MD5 qw(md5_hex);
9 use File::Temp qw(tempdir);
10 use HTML::Entities;
11 use IkiWiki 3.00;
12
13 my $default_prefix = <<EOPREFIX;
14 \\documentclass{article}
15 \\usepackage{amsmath}
16 \\usepackage{amsfonts}
17 \\usepackage{amssymb}
18 \\pagestyle{empty}
19 \\begin{document}
20 EOPREFIX
21
22 my $default_postfix = '\\end{document}';
23
24 sub import {
25         hook(type => "getsetup", id => "teximg", call => \&getsetup);
26         hook(type => "preprocess", id => "teximg", call => \&preprocess);
27 }
28
29 sub getsetup () {
30         return
31                 plugin => {
32                         safe => 1,
33                         rebuild => undef,
34                 },
35                 teximg_dvipng => {
36                         type => "boolean",
37                         description => "Should teximg use dvipng to render, or dvips and convert?",
38                         safe => 0,
39                         rebuild => undef,
40                 },
41                 teximg_prefix => {
42                         type => "string",
43                         example => $default_prefix,
44                         description => "LaTeX prefix for teximg plugin",
45                         safe => 0, # Not sure how secure LaTeX is...
46                         rebuild => 1,
47                 },
48                 teximg_postfix => {
49                         type => "string",
50                         example => $default_postfix,
51                         description => "LaTeX postfix for teximg plugin",
52                         safe => 0, # Not sure how secure LaTeX is...
53                         rebuild => 1,
54                 },
55 }
56
57 sub preprocess (@) {
58         my %params = @_;
59         
60         my $height = $params{height};
61         if (! defined $height || ! length $height) {
62                 $height = 12;
63         }
64         else {
65                 $height =~ s#(\d+)#$1#;
66         }
67         
68         my $code = $params{code};
69         if (! defined $code && ! length $code) {
70                 error gettext("missing tex code");
71         }
72
73         if (check($code)) {
74                 return create($code, check_height($height), \%params);
75         }
76         else {
77                 error gettext("code includes disallowed latex commands")
78         }
79 }
80
81 sub check_height ($) {
82         # Since latex doesn't support unlimited scaling this function
83         # returns the closest supported size.
84         my $height =shift;
85
86         my @allowed=(8,9,10,11,12,14,17,20);
87
88         my $ret;
89         my $fit;
90         foreach my $val (@allowed) {
91                 my $f = abs($val - $height);
92                 if (! defined($fit) || $f < $fit ) {
93                         $ret=$val;
94                         $fit=$f;
95                 }
96         }
97         return $ret;
98 }
99
100 sub create ($$$) {
101         # This function calls the image generating function and returns
102         # the <img .. /> for the generated image.
103         my $code = shift;
104         my $height = shift;
105         my $params = shift;
106
107         if (! defined($height) and not length($height) ) {
108                 $height = 12;
109         }
110
111         my $digest = md5_hex($code, $height);
112
113         my $imglink= $params->{page} . "/$digest.png";
114         my $imglog =  $params->{page} .  "/$digest.log";
115         will_render($params->{page}, $imglink);
116         will_render($params->{page}, $imglog);
117
118         my $imgurl=urlto($imglink, $params->{destpage});
119         my $logurl=urlto($imglog, $params->{destpage});
120         
121         if (-e "$config{destdir}/$imglink" ||
122             gen_image($code, $height, $digest, $params->{page})) {
123                 return qq{<img src="$imgurl" alt="}
124                         .(exists $params->{alt} ? $params->{alt} : encode_entities($code))
125                         .qq{" class="teximg" />};
126         }
127         else {
128                 error qq{<a href="$logurl">}.gettext("failed to generate image from code")."</a>";
129         }
130 }
131
132 sub gen_image ($$$$) {
133         # Actually creates the image.
134         my $code = shift;
135         my $height = shift;
136         my $digest = shift;
137         my $imagedir = shift;
138
139         if (!defined $config{teximg_prefix}) {
140                 $config{teximg_prefix} = $default_prefix;
141         }
142         if (!defined $config{teximg_postfix}) {
143                 $config{teximg_postfix} = $default_postfix;
144         }
145         if (!defined $config{teximg_dvipng}) {
146                 $config{teximg_dvipng} = length `which dvipng 2>/dev/null`;
147         }
148         
149         my $tex = $config{teximg_prefix};
150         $tex .= '$$'.$code.'$$';
151         $tex .= $config{teximg_postfix};
152         $tex =~ s!\\documentclass{article}!\\documentclass[${height}pt]{article}!g;
153         $tex =~ s!\\documentclass{scrartcl}!\\documentclass[${height}pt]{scrartcl}!g;
154
155         my $tmp = eval { create_tmp_dir($digest) };
156         if (! $@ &&
157             writefile("$digest.tex", $tmp, $tex) &&
158             system("cd $tmp; latex --interaction=nonstopmode $tmp/$digest.tex > /dev/null") == 0 &&
159             # ensure destination directory exists
160             writefile("$imagedir/$digest.png", $config{destdir}, "") &&
161             (($config{teximg_dvipng} &&
162                 system("dvipng -D 120 -bg Transparent -T tight -o $config{destdir}/$imagedir/$digest.png $tmp/$digest.dvi > $tmp/$digest.log") == 0
163             ) || (!$config{teximg_dvipng} &&
164                 system("dvips -E $tmp/$digest.dvi -o $tmp/$digest.ps 2> $tmp/$digest.log") == 0 &&
165                 system("convert -density 120  -trim -transparent \"#FFFFFF\" $tmp/$digest.ps $config{destdir}/$imagedir/$digest.png > $tmp/$digest.log") == 0
166             ))) {
167                 return 1;
168         }
169         else {
170                 # store failure log
171                 my $log="";
172                 {
173                         if (open(my $f, '<', "$tmp/$digest.log")) {
174                                 local $/=undef;
175                                 $log = <$f>;
176                                 close($f);
177                         }
178                 }
179                 writefile("$digest.log", "$config{destdir}/$imagedir", $log);
180
181                 return 0;
182         }
183 }
184
185 sub create_tmp_dir ($) {
186         # Create a temp directory, it will be removed when ikiwiki exits.
187         my $base = shift;
188
189         my $template = $base.".XXXXXXXXXX";
190         my $tmpdir = tempdir($template, TMPDIR => 1, CLEANUP => 1);
191         return $tmpdir;
192 }
193
194 sub check ($) {
195         # Check if the code is ok
196         my $code = shift;
197
198         my @badthings = (
199                 qr/\$\$/,
200                 qr/\\include/,
201                 qr/\\includegraphic/,
202                 qr/\\usepackage/,
203                 qr/\\newcommand/, 
204                 qr/\\renewcommand/,
205                 qr/\\def/,
206                 qr/\\input/,
207                 qr/\\open/,
208                 qr/\\loop/,
209                 qr/\\errorstopmode/,
210                 qr/\\scrollmode/,
211                 qr/\\batchmode/,
212                 qr/\\read/,
213                 qr/\\write/,
214         );
215         
216         foreach my $thing (@badthings) {
217                 if ($code =~ m/$thing/ ) {
218                         return 0;
219                 }
220         }
221         return 1;
222 }
223
224 1