Merge "Replace deprecated Title::userIsWatching()"
[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 return $info !== false;
58 }
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 return false;
76 }
77
78 // ---------
79
80 /**
81 * For debugging; dump the IFF chunk structure
82 */
83 function dump() {
84 $file = fopen( $this->mFilename, 'rb' );
85 $header = fread( $file, 12 );
86 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
87 extract( unpack( 'a4magic/a4chunk/NchunkLength', $header ) );
88 echo "$chunk $chunkLength\n";
89 $this->dumpForm( $file, $chunkLength, 1 );
90 fclose( $file );
91 }
92
93 private function dumpForm( $file, $length, $indent ) {
94 $start = ftell( $file );
95 $secondary = fread( $file, 4 );
96 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
97 while( ftell( $file ) - $start < $length ) {
98 $chunkHeader = fread( $file, 8 );
99 if( $chunkHeader == '' ) {
100 break;
101 }
102 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
103 extract( unpack( 'a4chunk/NchunkLength', $chunkHeader ) );
104 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
105
106 if( $chunk == 'FORM' ) {
107 $this->dumpForm( $file, $chunkLength, $indent + 1 );
108 } else {
109 fseek( $file, $chunkLength, SEEK_CUR );
110 if( $chunkLength & 1 == 1 ) {
111 // Padding byte between chunks
112 fseek( $file, 1, SEEK_CUR );
113 }
114 }
115 }
116 }
117
118 function getInfo() {
119 wfSuppressWarnings();
120 $file = fopen( $this->mFilename, 'rb' );
121 wfRestoreWarnings();
122 if( $file === false ) {
123 wfDebug( __METHOD__ . ": missing or failed file read\n" );
124 return false;
125 }
126
127 $header = fread( $file, 16 );
128 $info = false;
129
130 if( strlen( $header ) < 16 ) {
131 wfDebug( __METHOD__ . ": too short file header\n" );
132 } else {
133 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
134 extract( unpack( 'a4magic/a4form/NformLength/a4subtype', $header ) );
135
136 if( $magic != 'AT&T' ) {
137 wfDebug( __METHOD__ . ": not a DjVu file\n" );
138 } elseif( $subtype == 'DJVU' ) {
139 // Single-page document
140 $info = $this->getPageInfo( $file, $formLength );
141 } elseif( $subtype == 'DJVM' ) {
142 // Multi-page document
143 $info = $this->getMultiPageInfo( $file, $formLength );
144 } else {
145 wfDebug( __METHOD__ . ": unrecognized DJVU file type '$formType'\n" );
146 }
147 }
148 fclose( $file );
149 return $info;
150 }
151
152 private function readChunk( $file ) {
153 $header = fread( $file, 8 );
154 if( strlen( $header ) < 8 ) {
155 return array( false, 0 );
156 } else {
157 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
158 extract( unpack( 'a4chunk/Nlength', $header ) );
159 return array( $chunk, $length );
160 }
161 }
162
163 private function skipChunk( $file, $chunkLength ) {
164 fseek( $file, $chunkLength, SEEK_CUR );
165
166 if( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
167 // padding byte
168 fseek( $file, 1, SEEK_CUR );
169 }
170 }
171
172 private function getMultiPageInfo( $file, $formLength ) {
173 // For now, we'll just look for the first page in the file
174 // and report its information, hoping others are the same size.
175 $start = ftell( $file );
176 do {
177 list( $chunk, $length ) = $this->readChunk( $file );
178 if( !$chunk ) {
179 break;
180 }
181
182 if( $chunk == 'FORM' ) {
183 $subtype = fread( $file, 4 );
184 if( $subtype == 'DJVU' ) {
185 wfDebug( __METHOD__ . ": found first subpage\n" );
186 return $this->getPageInfo( $file, $length );
187 }
188 $this->skipChunk( $file, $length - 4 );
189 } else {
190 wfDebug( __METHOD__ . ": skipping '$chunk' chunk\n" );
191 $this->skipChunk( $file, $length );
192 }
193 } while( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
194
195 wfDebug( __METHOD__ . ": multi-page DJVU file contained no pages\n" );
196 return false;
197 }
198
199 private function getPageInfo( $file, $formLength ) {
200 list( $chunk, $length ) = $this->readChunk( $file );
201 if( $chunk != 'INFO' ) {
202 wfDebug( __METHOD__ . ": expected INFO chunk, got '$chunk'\n" );
203 return false;
204 }
205
206 if( $length < 9 ) {
207 wfDebug( __METHOD__ . ": INFO should be 9 or 10 bytes, found $length\n" );
208 return false;
209 }
210 $data = fread( $file, $length );
211 if( strlen( $data ) < $length ) {
212 wfDebug( __METHOD__ . ": INFO chunk cut off\n" );
213 return false;
214 }
215
216 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
217 extract( unpack(
218 'nwidth/' .
219 'nheight/' .
220 'Cminor/' .
221 'Cmajor/' .
222 'vresolution/' .
223 'Cgamma', $data ) );
224 # Newer files have rotation info in byte 10, but we don't use it yet.
225
226 return array(
227 'width' => $width,
228 'height' => $height,
229 'version' => "$major.$minor",
230 'resolution' => $resolution,
231 'gamma' => $gamma / 10.0 );
232 }
233
234 /**
235 * Return an XML string describing the DjVu image
236 * @return string
237 */
238 function retrieveMetaData() {
239 global $wgDjvuToXML, $wgDjvuDump, $wgDjvuTxt;
240 wfProfileIn( __METHOD__ );
241
242 if ( isset( $wgDjvuDump ) ) {
243 # djvudump is faster as of version 3.5
244 # http://sourceforge.net/tracker/index.php?func=detail&aid=1704049&group_id=32953&atid=406583
245 wfProfileIn( 'djvudump' );
246 $cmd = wfEscapeShellArg( $wgDjvuDump ) . ' ' . wfEscapeShellArg( $this->mFilename );
247 $dump = wfShellExec( $cmd );
248 $xml = $this->convertDumpToXML( $dump );
249 wfProfileOut( 'djvudump' );
250 } elseif ( isset( $wgDjvuToXML ) ) {
251 wfProfileIn( 'djvutoxml' );
252 $cmd = wfEscapeShellArg( $wgDjvuToXML ) . ' --without-anno --without-text ' .
253 wfEscapeShellArg( $this->mFilename );
254 $xml = wfShellExec( $cmd );
255 wfProfileOut( 'djvutoxml' );
256 } else {
257 $xml = null;
258 }
259 # Text layer
260 if ( isset( $wgDjvuTxt ) ) {
261 wfProfileIn( 'djvutxt' );
262 $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename ) ;
263 wfDebug( __METHOD__.": $cmd\n" );
264 $retval = '';
265 $txt = wfShellExec( $cmd, $retval, array(), array( 'memory' => self::DJVUTXT_MEMORY_LIMIT ) );
266 wfProfileOut( 'djvutxt' );
267 if( $retval == 0) {
268 # Strip some control characters
269 $txt = preg_replace( "/[\013\035\037]/", "", $txt );
270 $reg = <<<EOR
271 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
272 ((?> # Text to match is composed of atoms of either:
273 \\\\. # - any escaped character
274 | # - any character different from " and \
275 [^"\\\\]+
276 )*?)
277 "\s*\)
278 | # Or page can be empty ; in this case, djvutxt dumps ()
279 \(\s*()\)/sx
280 EOR;
281 $txt = preg_replace_callback( $reg, array( $this, 'pageTextCallback' ), $txt );
282 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
283 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 );
284 $xml = $xml . $txt. '</mw-djvu>' ;
285 }
286 }
287 wfProfileOut( __METHOD__ );
288 return $xml;
289 }
290
291 function pageTextCallback( $matches ) {
292 # Get rid of invalid UTF-8, strip control characters
293 return '<PAGE value="' . htmlspecialchars( UtfNormal::cleanUp( $matches[1] ) ) . '" />';
294 }
295
296 /**
297 * Hack to temporarily work around djvutoxml bug
298 * @return bool|string
299 */
300 function convertDumpToXML( $dump ) {
301 if ( strval( $dump ) == '' ) {
302 return false;
303 }
304
305 $xml = <<<EOT
306 <?xml version="1.0" ?>
307 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
308 <DjVuXML>
309 <HEAD></HEAD>
310 <BODY>
311 EOT;
312
313 $dump = str_replace( "\r", '', $dump );
314 $line = strtok( $dump, "\n" );
315 $m = false;
316 $good = false;
317 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
318 # Single-page
319 if ( $this->parseFormDjvu( $line, $xml ) ) {
320 $good = true;
321 } else {
322 return false;
323 }
324 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
325 # Multi-page
326 $parentLevel = strlen( $m[1] );
327 # Find DIRM
328 $line = strtok( "\n" );
329 while ( $line !== false ) {
330 $childLevel = strspn( $line, ' ' );
331 if ( $childLevel <= $parentLevel ) {
332 # End of chunk
333 break;
334 }
335
336 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
337 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
338 return false;
339 }
340 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
341 # Found page
342 if ( $this->parseFormDjvu( $line, $xml ) ) {
343 $good = true;
344 } else {
345 return false;
346 }
347 }
348 $line = strtok( "\n" );
349 }
350 }
351 if ( !$good ) {
352 return false;
353 }
354
355 $xml .= "</BODY>\n</DjVuXML>\n";
356 return $xml;
357 }
358
359 function parseFormDjvu( $line, &$xml ) {
360 $parentLevel = strspn( $line, ' ' );
361 $line = strtok( "\n" );
362
363 # Find INFO
364 while ( $line !== false ) {
365 $childLevel = strspn( $line, ' ' );
366 if ( $childLevel <= $parentLevel ) {
367 # End of chunk
368 break;
369 }
370
371 if ( preg_match( '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/', $line, $m ) ) {
372 $xml .= Xml::tags( 'OBJECT',
373 array(
374 #'data' => '',
375 #'type' => 'image/x.djvu',
376 'height' => $m[2],
377 'width' => $m[1],
378 #'usemap' => '',
379 ),
380 "\n" .
381 Xml::element( 'PARAM', array( 'name' => 'DPI', 'value' => $m[3] ) ) . "\n" .
382 Xml::element( 'PARAM', array( 'name' => 'GAMMA', 'value' => $m[4] ) ) . "\n"
383 ) . "\n";
384 return true;
385 }
386 $line = strtok( "\n" );
387 }
388 # Not found
389 return false;
390 }
391 }