5 * Copyright © 2006 Brion Vibber <brion@pobox.com>
6 * https://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
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/
38 * @const DJVUTXT_MEMORY_LIMIT Memory limit for the DjVu description software
40 const DJVUTXT_MEMORY_LIMIT
= 300000;
45 * @param string $filename The DjVu file name.
47 function __construct( $filename ) {
48 $this->mFilename
= $filename;
52 * Check if the given file is indeed a valid DjVu image file
55 public function isValid() {
56 $info = $this->getInfo();
58 return $info !== false;
62 * Return data in the style of getimagesize()
63 * @return array|bool Array or false on failure
65 public function getImageSize() {
66 $data = $this->getInfo();
68 if ( $data !== false ) {
69 $width = $data['width'];
70 $height = $data['height'];
72 return [ $width, $height, 'DjVu',
73 "width=\"$width\" height=\"$height\"" ];
82 * For debugging; dump the IFF chunk structure
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 /** @var string $chunk
91 * @var string $chunkLength */
92 echo "$chunk $chunkLength\n";
93 $this->dumpForm( $file, $chunkLength, 1 );
97 private function dumpForm( $file, $length, $indent ) {
98 $start = ftell( $file );
99 $secondary = fread( $file, 4 );
100 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
101 while ( ftell( $file ) - $start < $length ) {
102 $chunkHeader = fread( $file, 8 );
103 if ( $chunkHeader == '' ) {
106 // @todo FIXME: Would be good to replace this extract() call with
107 // something that explicitly initializes local variables.
108 extract( unpack( 'a4chunk/NchunkLength', $chunkHeader ) );
109 /** @var string $chunk
110 * @var string $chunkLength */
111 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
113 if ( $chunk == 'FORM' ) {
114 $this->dumpForm( $file, $chunkLength, $indent +
1 );
116 fseek( $file, $chunkLength, SEEK_CUR
);
117 if ( $chunkLength & 1 == 1 ) {
118 // Padding byte between chunks
119 fseek( $file, 1, SEEK_CUR
);
126 MediaWiki\
suppressWarnings();
127 $file = fopen( $this->mFilename
, 'rb' );
128 MediaWiki\restoreWarnings
();
129 if ( $file === false ) {
130 wfDebug( __METHOD__
. ": missing or failed file read\n" );
135 $header = fread( $file, 16 );
138 if ( strlen( $header ) < 16 ) {
139 wfDebug( __METHOD__
. ": too short file header\n" );
141 // @todo FIXME: Would be good to replace this extract() call with
142 // something that explicitly initializes local variables.
143 extract( unpack( 'a4magic/a4form/NformLength/a4subtype', $header ) );
145 /** @var string $magic
146 * @var string $subtype
147 * @var string $formLength
148 * @var string $formType */
149 if ( $magic != 'AT&T' ) {
150 wfDebug( __METHOD__
. ": not a DjVu file\n" );
151 } elseif ( $subtype == 'DJVU' ) {
152 // Single-page document
153 $info = $this->getPageInfo( $file );
154 } elseif ( $subtype == 'DJVM' ) {
155 // Multi-page document
156 $info = $this->getMultiPageInfo( $file, $formLength );
158 wfDebug( __METHOD__
. ": unrecognized DJVU file type '$formType'\n" );
166 private function readChunk( $file ) {
167 $header = fread( $file, 8 );
168 if ( strlen( $header ) < 8 ) {
171 // @todo FIXME: Would be good to replace this extract() call with
172 // something that explicitly initializes local variables.
173 extract( unpack( 'a4chunk/Nlength', $header ) );
175 /** @var string $chunk
176 * @var string $length */
177 return [ $chunk, $length ];
181 private function skipChunk( $file, $chunkLength ) {
182 fseek( $file, $chunkLength, SEEK_CUR
);
184 if ( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
186 fseek( $file, 1, SEEK_CUR
);
190 private function getMultiPageInfo( $file, $formLength ) {
191 // For now, we'll just look for the first page in the file
192 // and report its information, hoping others are the same size.
193 $start = ftell( $file );
195 list( $chunk, $length ) = $this->readChunk( $file );
200 if ( $chunk == 'FORM' ) {
201 $subtype = fread( $file, 4 );
202 if ( $subtype == 'DJVU' ) {
203 wfDebug( __METHOD__
. ": found first subpage\n" );
205 return $this->getPageInfo( $file );
207 $this->skipChunk( $file, $length - 4 );
209 wfDebug( __METHOD__
. ": skipping '$chunk' chunk\n" );
210 $this->skipChunk( $file, $length );
212 } while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
214 wfDebug( __METHOD__
. ": multi-page DJVU file contained no pages\n" );
219 private function getPageInfo( $file ) {
220 list( $chunk, $length ) = $this->readChunk( $file );
221 if ( $chunk != 'INFO' ) {
222 wfDebug( __METHOD__
. ": expected INFO chunk, got '$chunk'\n" );
228 wfDebug( __METHOD__
. ": INFO should be 9 or 10 bytes, found $length\n" );
232 $data = fread( $file, $length );
233 if ( strlen( $data ) < $length ) {
234 wfDebug( __METHOD__
. ": INFO chunk cut off\n" );
239 // @todo FIXME: Would be good to replace this extract() call with
240 // something that explicitly initializes local variables.
249 # Newer files have rotation info in byte 10, but we don't use it yet.
251 /** @var string $width
252 * @var string $height
255 * @var string $resolution
256 * @var string $length
257 * @var string $gamma */
261 'version' => "$major.$minor",
262 'resolution' => $resolution,
263 'gamma' => $gamma / 10.0 ];
267 * Return an XML string describing the DjVu image
268 * @return string|bool
270 function retrieveMetaData() {
271 global $wgDjvuToXML, $wgDjvuDump, $wgDjvuTxt;
273 if ( !$this->isValid() ) {
277 if ( isset( $wgDjvuDump ) ) {
278 # djvudump is faster as of version 3.5
279 # http://sourceforge.net/tracker/index.php?func=detail&aid=1704049&group_id=32953&atid=406583
280 $cmd = wfEscapeShellArg( $wgDjvuDump ) . ' ' . wfEscapeShellArg( $this->mFilename
);
281 $dump = wfShellExec( $cmd );
282 $xml = $this->convertDumpToXML( $dump );
283 } elseif ( isset( $wgDjvuToXML ) ) {
284 $cmd = wfEscapeShellArg( $wgDjvuToXML ) . ' --without-anno --without-text ' .
285 wfEscapeShellArg( $this->mFilename
);
286 $xml = wfShellExec( $cmd );
291 if ( isset( $wgDjvuTxt ) ) {
292 $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename
);
293 wfDebug( __METHOD__
. ": $cmd\n" );
295 $txt = wfShellExec( $cmd, $retval, [], [ 'memory' => self
::DJVUTXT_MEMORY_LIMIT
] );
296 if ( $retval == 0 ) {
297 # Strip some control characters
298 $txt = preg_replace( "/[\013\035\037]/", "", $txt );
300 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
301 ((?> # Text to match is composed of atoms of either:
302 \\\\. # - any escaped character
303 | # - any character different from " and \
307 | # Or page can be empty ; in this case, djvutxt dumps ()
310 $txt = preg_replace_callback( $reg, [ $this, 'pageTextCallback' ], $txt );
311 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
312 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 );
313 $xml = $xml . $txt . '</mw-djvu>';
320 function pageTextCallback( $matches ) {
321 # Get rid of invalid UTF-8, strip control characters
322 $val = htmlspecialchars( UtfNormal\Validator
::cleanUp( stripcslashes( $matches[1] ) ) );
323 $val = str_replace( [ "\n", '�' ], [ ' ', '' ], $val );
324 return '<PAGE value="' . $val . '" />';
328 * Hack to temporarily work around djvutoxml bug
329 * @param string $dump
332 function convertDumpToXML( $dump ) {
333 if ( strval( $dump ) == '' ) {
338 <?xml version="1.0" ?>
339 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
345 $dump = str_replace( "\r", '', $dump );
346 $line = strtok( $dump, "\n" );
349 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
351 if ( $this->parseFormDjvu( $line, $xml ) ) {
356 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
358 $parentLevel = strlen( $m[1] );
360 $line = strtok( "\n" );
361 while ( $line !== false ) {
362 $childLevel = strspn( $line, ' ' );
363 if ( $childLevel <= $parentLevel ) {
368 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
369 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
373 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
375 if ( $this->parseFormDjvu( $line, $xml ) ) {
381 $line = strtok( "\n" );
388 $xml .= "</BODY>\n</DjVuXML>\n";
393 function parseFormDjvu( $line, &$xml ) {
394 $parentLevel = strspn( $line, ' ' );
395 $line = strtok( "\n" );
398 while ( $line !== false ) {
399 $childLevel = strspn( $line, ' ' );
400 if ( $childLevel <= $parentLevel ) {
406 '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
414 # 'type' => 'image/x.djvu',
420 Xml
::element( 'PARAM', [ 'name' => 'DPI', 'value' => $m[3] ] ) . "\n" .
421 Xml
::element( 'PARAM', [ 'name' => 'GAMMA', 'value' => $m[4] ] ) . "\n"
426 $line = strtok( "\n" );