Merge "Remove 6 unused revdelete messages"
[lhc/web/wiklou.git] / includes / media / DjVuImage.php
1 <?php
2 /**
3 * DjVu image handler.
4 *
5 * Copyright © 2006 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Media
25 */
26
27 /**
28 * Support for detecting/validating DjVu image files and getting
29 * some basic file metadata (resolution etc)
30 *
31 * File format docs are available in source package for DjVuLibre:
32 * http://djvulibre.djvuzone.org/
33 *
34 * @ingroup Media
35 */
36 class DjVuImage {
37 /**
38 * Constructor
39 *
40 * @param string $filename The DjVu file name.
41 */
42 function __construct( $filename ) {
43 $this->mFilename = $filename;
44 }
45
46 /**
47 * @const DJVUTXT_MEMORY_LIMIT Memory limit for the DjVu description software
48 */
49 const DJVUTXT_MEMORY_LIMIT = 300000;
50
51 /**
52 * Check if the given file is indeed a valid DjVu image file
53 * @return bool
54 */
55 public function isValid() {
56 $info = $this->getInfo();
57
58 return $info !== false;
59 }
60
61 /**
62 * Return data in the style of getimagesize()
63 * @return array or false on failure
64 */
65 public function getImageSize() {
66 $data = $this->getInfo();
67
68 if ( $data !== false ) {
69 $width = $data['width'];
70 $height = $data['height'];
71
72 return array( $width, $height, 'DjVu',
73 "width=\"$width\" height=\"$height\"" );
74 }
75
76 return false;
77 }
78
79 // ---------
80
81 /**
82 * For debugging; dump the IFF chunk structure
83 */
84 function dump() {
85 $file = fopen( $this->mFilename, 'rb' );
86 $header = fread( $file, 12 );
87 // @todo FIXME: Would be good to replace this extract() call with
88 // something that explicitly initializes local variables.
89 extract( unpack( 'a4magic/a4chunk/NchunkLength', $header ) );
90 echo "$chunk $chunkLength\n";
91 $this->dumpForm( $file, $chunkLength, 1 );
92 fclose( $file );
93 }
94
95 private function dumpForm( $file, $length, $indent ) {
96 $start = ftell( $file );
97 $secondary = fread( $file, 4 );
98 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
99 while ( ftell( $file ) - $start < $length ) {
100 $chunkHeader = fread( $file, 8 );
101 if ( $chunkHeader == '' ) {
102 break;
103 }
104 // @todo FIXME: Would be good to replace this extract() call with
105 // something that explicitly initializes local variables.
106 extract( unpack( 'a4chunk/NchunkLength', $chunkHeader ) );
107 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
108
109 if ( $chunk == 'FORM' ) {
110 $this->dumpForm( $file, $chunkLength, $indent + 1 );
111 } else {
112 fseek( $file, $chunkLength, SEEK_CUR );
113 if ( $chunkLength & 1 == 1 ) {
114 // Padding byte between chunks
115 fseek( $file, 1, SEEK_CUR );
116 }
117 }
118 }
119 }
120
121 function getInfo() {
122 wfSuppressWarnings();
123 $file = fopen( $this->mFilename, 'rb' );
124 wfRestoreWarnings();
125 if ( $file === false ) {
126 wfDebug( __METHOD__ . ": missing or failed file read\n" );
127
128 return false;
129 }
130
131 $header = fread( $file, 16 );
132 $info = false;
133
134 if ( strlen( $header ) < 16 ) {
135 wfDebug( __METHOD__ . ": too short file header\n" );
136 } else {
137 // @todo FIXME: Would be good to replace this extract() call with
138 // something that explicitly initializes local variables.
139 extract( unpack( 'a4magic/a4form/NformLength/a4subtype', $header ) );
140
141 if ( $magic != 'AT&T' ) {
142 wfDebug( __METHOD__ . ": not a DjVu file\n" );
143 } elseif ( $subtype == 'DJVU' ) {
144 // Single-page document
145 $info = $this->getPageInfo( $file, $formLength );
146 } elseif ( $subtype == 'DJVM' ) {
147 // Multi-page document
148 $info = $this->getMultiPageInfo( $file, $formLength );
149 } else {
150 wfDebug( __METHOD__ . ": unrecognized DJVU file type '$formType'\n" );
151 }
152 }
153 fclose( $file );
154
155 return $info;
156 }
157
158 private function readChunk( $file ) {
159 $header = fread( $file, 8 );
160 if ( strlen( $header ) < 8 ) {
161 return array( false, 0 );
162 } else {
163 // @todo FIXME: Would be good to replace this extract() call with
164 // something that explicitly initializes local variables.
165 extract( unpack( 'a4chunk/Nlength', $header ) );
166
167 return array( $chunk, $length );
168 }
169 }
170
171 private function skipChunk( $file, $chunkLength ) {
172 fseek( $file, $chunkLength, SEEK_CUR );
173
174 if ( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
175 // padding byte
176 fseek( $file, 1, SEEK_CUR );
177 }
178 }
179
180 private function getMultiPageInfo( $file, $formLength ) {
181 // For now, we'll just look for the first page in the file
182 // and report its information, hoping others are the same size.
183 $start = ftell( $file );
184 do {
185 list( $chunk, $length ) = $this->readChunk( $file );
186 if ( !$chunk ) {
187 break;
188 }
189
190 if ( $chunk == 'FORM' ) {
191 $subtype = fread( $file, 4 );
192 if ( $subtype == 'DJVU' ) {
193 wfDebug( __METHOD__ . ": found first subpage\n" );
194
195 return $this->getPageInfo( $file, $length );
196 }
197 $this->skipChunk( $file, $length - 4 );
198 } else {
199 wfDebug( __METHOD__ . ": skipping '$chunk' chunk\n" );
200 $this->skipChunk( $file, $length );
201 }
202 } while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
203
204 wfDebug( __METHOD__ . ": multi-page DJVU file contained no pages\n" );
205
206 return false;
207 }
208
209 private function getPageInfo( $file, $formLength ) {
210 list( $chunk, $length ) = $this->readChunk( $file );
211 if ( $chunk != 'INFO' ) {
212 wfDebug( __METHOD__ . ": expected INFO chunk, got '$chunk'\n" );
213
214 return false;
215 }
216
217 if ( $length < 9 ) {
218 wfDebug( __METHOD__ . ": INFO should be 9 or 10 bytes, found $length\n" );
219
220 return false;
221 }
222 $data = fread( $file, $length );
223 if ( strlen( $data ) < $length ) {
224 wfDebug( __METHOD__ . ": INFO chunk cut off\n" );
225
226 return false;
227 }
228
229 // @todo FIXME: Would be good to replace this extract() call with
230 // something that explicitly initializes local variables.
231 extract( unpack(
232 'nwidth/' .
233 'nheight/' .
234 'Cminor/' .
235 'Cmajor/' .
236 'vresolution/' .
237 'Cgamma', $data ) );
238
239 # Newer files have rotation info in byte 10, but we don't use it yet.
240
241 return array(
242 'width' => $width,
243 'height' => $height,
244 'version' => "$major.$minor",
245 'resolution' => $resolution,
246 'gamma' => $gamma / 10.0 );
247 }
248
249 /**
250 * Return an XML string describing the DjVu image
251 * @return string
252 */
253 function retrieveMetaData() {
254 global $wgDjvuToXML, $wgDjvuDump, $wgDjvuTxt;
255 wfProfileIn( __METHOD__ );
256
257 if ( isset( $wgDjvuDump ) ) {
258 # djvudump is faster as of version 3.5
259 # http://sourceforge.net/tracker/index.php?func=detail&aid=1704049&group_id=32953&atid=406583
260 wfProfileIn( 'djvudump' );
261 $cmd = wfEscapeShellArg( $wgDjvuDump ) . ' ' . wfEscapeShellArg( $this->mFilename );
262 $dump = wfShellExec( $cmd );
263 $xml = $this->convertDumpToXML( $dump );
264 wfProfileOut( 'djvudump' );
265 } elseif ( isset( $wgDjvuToXML ) ) {
266 wfProfileIn( 'djvutoxml' );
267 $cmd = wfEscapeShellArg( $wgDjvuToXML ) . ' --without-anno --without-text ' .
268 wfEscapeShellArg( $this->mFilename );
269 $xml = wfShellExec( $cmd );
270 wfProfileOut( 'djvutoxml' );
271 } else {
272 $xml = null;
273 }
274 # Text layer
275 if ( isset( $wgDjvuTxt ) ) {
276 wfProfileIn( 'djvutxt' );
277 $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename );
278 wfDebug( __METHOD__ . ": $cmd\n" );
279 $retval = '';
280 $txt = wfShellExec( $cmd, $retval, array(), array( 'memory' => self::DJVUTXT_MEMORY_LIMIT ) );
281 wfProfileOut( 'djvutxt' );
282 if ( $retval == 0 ) {
283 # Strip some control characters
284 $txt = preg_replace( "/[\013\035\037]/", "", $txt );
285 $reg = <<<EOR
286 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
287 ((?> # Text to match is composed of atoms of either:
288 \\\\. # - any escaped character
289 | # - any character different from " and \
290 [^"\\\\]+
291 )*?)
292 "\s*\)
293 | # Or page can be empty ; in this case, djvutxt dumps ()
294 \(\s*()\)/sx
295 EOR;
296 $txt = preg_replace_callback( $reg, array( $this, 'pageTextCallback' ), $txt );
297 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
298 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 );
299 $xml = $xml . $txt . '</mw-djvu>';
300 }
301 }
302 wfProfileOut( __METHOD__ );
303
304 return $xml;
305 }
306
307 function pageTextCallback( $matches ) {
308 # Get rid of invalid UTF-8, strip control characters
309 return '<PAGE value="' . htmlspecialchars( UtfNormal::cleanUp( $matches[1] ) ) . '" />';
310 }
311
312 /**
313 * Hack to temporarily work around djvutoxml bug
314 * @return bool|string
315 */
316 function convertDumpToXML( $dump ) {
317 if ( strval( $dump ) == '' ) {
318 return false;
319 }
320
321 $xml = <<<EOT
322 <?xml version="1.0" ?>
323 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
324 <DjVuXML>
325 <HEAD></HEAD>
326 <BODY>
327 EOT;
328
329 $dump = str_replace( "\r", '', $dump );
330 $line = strtok( $dump, "\n" );
331 $m = false;
332 $good = false;
333 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
334 # Single-page
335 if ( $this->parseFormDjvu( $line, $xml ) ) {
336 $good = true;
337 } else {
338 return false;
339 }
340 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
341 # Multi-page
342 $parentLevel = strlen( $m[1] );
343 # Find DIRM
344 $line = strtok( "\n" );
345 while ( $line !== false ) {
346 $childLevel = strspn( $line, ' ' );
347 if ( $childLevel <= $parentLevel ) {
348 # End of chunk
349 break;
350 }
351
352 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
353 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
354
355 return false;
356 }
357 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
358 # Found page
359 if ( $this->parseFormDjvu( $line, $xml ) ) {
360 $good = true;
361 } else {
362 return false;
363 }
364 }
365 $line = strtok( "\n" );
366 }
367 }
368 if ( !$good ) {
369 return false;
370 }
371
372 $xml .= "</BODY>\n</DjVuXML>\n";
373
374 return $xml;
375 }
376
377 function parseFormDjvu( $line, &$xml ) {
378 $parentLevel = strspn( $line, ' ' );
379 $line = strtok( "\n" );
380
381 # Find INFO
382 while ( $line !== false ) {
383 $childLevel = strspn( $line, ' ' );
384 if ( $childLevel <= $parentLevel ) {
385 # End of chunk
386 break;
387 }
388
389 if ( preg_match(
390 '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
391 $line,
392 $m
393 ) ) {
394 $xml .= Xml::tags(
395 'OBJECT',
396 array(
397 #'data' => '',
398 #'type' => 'image/x.djvu',
399 'height' => $m[2],
400 'width' => $m[1],
401 #'usemap' => '',
402 ),
403 "\n" .
404 Xml::element( 'PARAM', array( 'name' => 'DPI', 'value' => $m[3] ) ) . "\n" .
405 Xml::element( 'PARAM', array( 'name' => 'GAMMA', 'value' => $m[4] ) ) . "\n"
406 ) . "\n";
407
408 return true;
409 }
410 $line = strtok( "\n" );
411 }
412
413 # Not found
414 return false;
415 }
416 }