Merge "Make line breaks in <blockquote> behave like <div> (bug 6200)."
[mediawiki.git] / includes / media / DjVuImage.php
blob54efe7a83384d82babff744298e3a01b990f52e9
1 <?php
2 /**
3 * DjVu image handler.
5 * Copyright © 2006 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
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.
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.
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
23 * @file
24 * @ingroup Media
27 /**
28 * Support for detecting/validating DjVu image files and getting
29 * some basic file metadata (resolution etc)
31 * File format docs are available in source package for DjVuLibre:
32 * http://djvulibre.djvuzone.org/
34 * @ingroup Media
36 class DjVuImage {
37 /**
38 * Constructor
40 * @param string $filename The DjVu file name.
42 function __construct( $filename ) {
43 $this->mFilename = $filename;
46 /**
47 * @const DJVUTXT_MEMORY_LIMIT Memory limit for the DjVu description software
49 const DJVUTXT_MEMORY_LIMIT = 300000;
51 /**
52 * Check if the given file is indeed a valid DjVu image file
53 * @return bool
55 public function isValid() {
56 $info = $this->getInfo();
57 return $info !== false;
60 /**
61 * Return data in the style of getimagesize()
62 * @return array or false on failure
64 public function getImageSize() {
65 $data = $this->getInfo();
67 if ( $data !== false ) {
68 $width = $data['width'];
69 $height = $data['height'];
71 return array( $width, $height, 'DjVu',
72 "width=\"$width\" height=\"$height\"" );
74 return false;
77 // ---------
79 /**
80 * For debugging; dump the IFF chunk structure
82 function dump() {
83 $file = fopen( $this->mFilename, 'rb' );
84 $header = fread( $file, 12 );
85 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
86 extract( unpack( 'a4magic/a4chunk/NchunkLength', $header ) );
87 echo "$chunk $chunkLength\n";
88 $this->dumpForm( $file, $chunkLength, 1 );
89 fclose( $file );
92 private function dumpForm( $file, $length, $indent ) {
93 $start = ftell( $file );
94 $secondary = fread( $file, 4 );
95 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
96 while ( ftell( $file ) - $start < $length ) {
97 $chunkHeader = fread( $file, 8 );
98 if ( $chunkHeader == '' ) {
99 break;
101 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
102 extract( unpack( 'a4chunk/NchunkLength', $chunkHeader ) );
103 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
105 if ( $chunk == 'FORM' ) {
106 $this->dumpForm( $file, $chunkLength, $indent + 1 );
107 } else {
108 fseek( $file, $chunkLength, SEEK_CUR );
109 if ( $chunkLength & 1 == 1 ) {
110 // Padding byte between chunks
111 fseek( $file, 1, SEEK_CUR );
117 function getInfo() {
118 wfSuppressWarnings();
119 $file = fopen( $this->mFilename, 'rb' );
120 wfRestoreWarnings();
121 if ( $file === false ) {
122 wfDebug( __METHOD__ . ": missing or failed file read\n" );
123 return false;
126 $header = fread( $file, 16 );
127 $info = false;
129 if ( strlen( $header ) < 16 ) {
130 wfDebug( __METHOD__ . ": too short file header\n" );
131 } else {
132 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
133 extract( unpack( 'a4magic/a4form/NformLength/a4subtype', $header ) );
135 if ( $magic != 'AT&T' ) {
136 wfDebug( __METHOD__ . ": not a DjVu file\n" );
137 } elseif ( $subtype == 'DJVU' ) {
138 // Single-page document
139 $info = $this->getPageInfo( $file, $formLength );
140 } elseif ( $subtype == 'DJVM' ) {
141 // Multi-page document
142 $info = $this->getMultiPageInfo( $file, $formLength );
143 } else {
144 wfDebug( __METHOD__ . ": unrecognized DJVU file type '$formType'\n" );
147 fclose( $file );
148 return $info;
151 private function readChunk( $file ) {
152 $header = fread( $file, 8 );
153 if ( strlen( $header ) < 8 ) {
154 return array( false, 0 );
155 } else {
156 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
157 extract( unpack( 'a4chunk/Nlength', $header ) );
158 return array( $chunk, $length );
162 private function skipChunk( $file, $chunkLength ) {
163 fseek( $file, $chunkLength, SEEK_CUR );
165 if ( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
166 // padding byte
167 fseek( $file, 1, SEEK_CUR );
171 private function getMultiPageInfo( $file, $formLength ) {
172 // For now, we'll just look for the first page in the file
173 // and report its information, hoping others are the same size.
174 $start = ftell( $file );
175 do {
176 list( $chunk, $length ) = $this->readChunk( $file );
177 if ( !$chunk ) {
178 break;
181 if ( $chunk == 'FORM' ) {
182 $subtype = fread( $file, 4 );
183 if ( $subtype == 'DJVU' ) {
184 wfDebug( __METHOD__ . ": found first subpage\n" );
185 return $this->getPageInfo( $file, $length );
187 $this->skipChunk( $file, $length - 4 );
188 } else {
189 wfDebug( __METHOD__ . ": skipping '$chunk' chunk\n" );
190 $this->skipChunk( $file, $length );
192 } while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
194 wfDebug( __METHOD__ . ": multi-page DJVU file contained no pages\n" );
195 return false;
198 private function getPageInfo( $file, $formLength ) {
199 list( $chunk, $length ) = $this->readChunk( $file );
200 if ( $chunk != 'INFO' ) {
201 wfDebug( __METHOD__ . ": expected INFO chunk, got '$chunk'\n" );
202 return false;
205 if ( $length < 9 ) {
206 wfDebug( __METHOD__ . ": INFO should be 9 or 10 bytes, found $length\n" );
207 return false;
209 $data = fread( $file, $length );
210 if ( strlen( $data ) < $length ) {
211 wfDebug( __METHOD__ . ": INFO chunk cut off\n" );
212 return false;
215 // @todo FIXME: Would be good to replace this extract() call with something that explicitly initializes local variables.
216 extract( unpack(
217 'nwidth/' .
218 'nheight/' .
219 'Cminor/' .
220 'Cmajor/' .
221 'vresolution/' .
222 'Cgamma', $data ) );
223 # Newer files have rotation info in byte 10, but we don't use it yet.
225 return array(
226 'width' => $width,
227 'height' => $height,
228 'version' => "$major.$minor",
229 'resolution' => $resolution,
230 'gamma' => $gamma / 10.0 );
234 * Return an XML string describing the DjVu image
235 * @return string
237 function retrieveMetaData() {
238 global $wgDjvuToXML, $wgDjvuDump, $wgDjvuTxt;
239 wfProfileIn( __METHOD__ );
241 if ( isset( $wgDjvuDump ) ) {
242 # djvudump is faster as of version 3.5
243 # http://sourceforge.net/tracker/index.php?func=detail&aid=1704049&group_id=32953&atid=406583
244 wfProfileIn( 'djvudump' );
245 $cmd = wfEscapeShellArg( $wgDjvuDump ) . ' ' . wfEscapeShellArg( $this->mFilename );
246 $dump = wfShellExec( $cmd );
247 $xml = $this->convertDumpToXML( $dump );
248 wfProfileOut( 'djvudump' );
249 } elseif ( isset( $wgDjvuToXML ) ) {
250 wfProfileIn( 'djvutoxml' );
251 $cmd = wfEscapeShellArg( $wgDjvuToXML ) . ' --without-anno --without-text ' .
252 wfEscapeShellArg( $this->mFilename );
253 $xml = wfShellExec( $cmd );
254 wfProfileOut( 'djvutoxml' );
255 } else {
256 $xml = null;
258 # Text layer
259 if ( isset( $wgDjvuTxt ) ) {
260 wfProfileIn( 'djvutxt' );
261 $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename );
262 wfDebug( __METHOD__ . ": $cmd\n" );
263 $retval = '';
264 $txt = wfShellExec( $cmd, $retval, array(), array( 'memory' => self::DJVUTXT_MEMORY_LIMIT ) );
265 wfProfileOut( 'djvutxt' );
266 if ( $retval == 0 ) {
267 # Strip some control characters
268 $txt = preg_replace( "/[\013\035\037]/", "", $txt );
269 $reg = <<<EOR
270 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
271 ((?> # Text to match is composed of atoms of either:
272 \\\\. # - any escaped character
273 | # - any character different from " and \
274 [^"\\\\]+
275 )*?)
276 "\s*\)
277 | # Or page can be empty ; in this case, djvutxt dumps ()
278 \(\s*()\)/sx
279 EOR;
280 $txt = preg_replace_callback( $reg, array( $this, 'pageTextCallback' ), $txt );
281 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
282 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 );
283 $xml = $xml . $txt . '</mw-djvu>';
286 wfProfileOut( __METHOD__ );
287 return $xml;
290 function pageTextCallback( $matches ) {
291 # Get rid of invalid UTF-8, strip control characters
292 return '<PAGE value="' . htmlspecialchars( UtfNormal::cleanUp( $matches[1] ) ) . '" />';
296 * Hack to temporarily work around djvutoxml bug
297 * @return bool|string
299 function convertDumpToXML( $dump ) {
300 if ( strval( $dump ) == '' ) {
301 return false;
304 $xml = <<<EOT
305 <?xml version="1.0" ?>
306 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
307 <DjVuXML>
308 <HEAD></HEAD>
309 <BODY>
310 EOT;
312 $dump = str_replace( "\r", '', $dump );
313 $line = strtok( $dump, "\n" );
314 $m = false;
315 $good = false;
316 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
317 # Single-page
318 if ( $this->parseFormDjvu( $line, $xml ) ) {
319 $good = true;
320 } else {
321 return false;
323 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
324 # Multi-page
325 $parentLevel = strlen( $m[1] );
326 # Find DIRM
327 $line = strtok( "\n" );
328 while ( $line !== false ) {
329 $childLevel = strspn( $line, ' ' );
330 if ( $childLevel <= $parentLevel ) {
331 # End of chunk
332 break;
335 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
336 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
337 return false;
339 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
340 # Found page
341 if ( $this->parseFormDjvu( $line, $xml ) ) {
342 $good = true;
343 } else {
344 return false;
347 $line = strtok( "\n" );
350 if ( !$good ) {
351 return false;
354 $xml .= "</BODY>\n</DjVuXML>\n";
355 return $xml;
358 function parseFormDjvu( $line, &$xml ) {
359 $parentLevel = strspn( $line, ' ' );
360 $line = strtok( "\n" );
362 # Find INFO
363 while ( $line !== false ) {
364 $childLevel = strspn( $line, ' ' );
365 if ( $childLevel <= $parentLevel ) {
366 # End of chunk
367 break;
370 if ( preg_match( '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/', $line, $m ) ) {
371 $xml .= Xml::tags( 'OBJECT',
372 array(
373 #'data' => '',
374 #'type' => 'image/x.djvu',
375 'height' => $m[2],
376 'width' => $m[1],
377 #'usemap' => '',
379 "\n" .
380 Xml::element( 'PARAM', array( 'name' => 'DPI', 'value' => $m[3] ) ) . "\n" .
381 Xml::element( 'PARAM', array( 'name' => 'GAMMA', 'value' => $m[4] ) ) . "\n"
382 ) . "\n";
383 return true;
385 $line = strtok( "\n" );
387 # Not found
388 return false;