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
27 use MediaWiki\Shell\Shell
;
30 * Support for detecting/validating DjVu image files and getting
31 * some basic file metadata (resolution etc)
33 * File format docs are available in source package for DjVuLibre:
34 * http://djvulibre.djvuzone.org/
41 * Memory limit for the DjVu description software
43 const DJVUTXT_MEMORY_LIMIT
= 300000;
49 * @param string $filename The DjVu file name.
51 function __construct( $filename ) {
52 $this->mFilename
= $filename;
56 * Check if the given file is indeed a valid DjVu image file
59 public function isValid() {
60 $info = $this->getInfo();
62 return $info !== false;
66 * Return data in the style of getimagesize()
67 * @return array|false Array or false on failure
69 public function getImageSize() {
70 $data = $this->getInfo();
72 if ( $data !== false ) {
73 $width = $data['width'];
74 $height = $data['height'];
76 return [ $width, $height, 'DjVu',
77 "width=\"$width\" height=\"$height\"" ];
86 * For debugging; dump the IFF chunk structure
89 $file = fopen( $this->mFilename
, 'rb' );
90 $header = fread( $file, 12 );
91 $arr = unpack( 'a4magic/a4chunk/NchunkLength', $header );
92 $chunk = $arr['chunk'];
93 $chunkLength = $arr['chunkLength'];
94 echo "$chunk $chunkLength\n";
95 $this->dumpForm( $file, $chunkLength, 1 );
99 private function dumpForm( $file, $length, $indent ) {
100 $start = ftell( $file );
101 $secondary = fread( $file, 4 );
102 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
103 while ( ftell( $file ) - $start < $length ) {
104 $chunkHeader = fread( $file, 8 );
105 if ( $chunkHeader == '' ) {
108 $arr = unpack( 'a4chunk/NchunkLength', $chunkHeader );
109 $chunk = $arr['chunk'];
110 $chunkLength = $arr['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 ) {
118 // Padding byte between chunks
119 fseek( $file, 1, SEEK_CUR
);
126 Wikimedia\
suppressWarnings();
127 $file = fopen( $this->mFilename
, 'rb' );
128 Wikimedia\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 $arr = unpack( 'a4magic/a4form/NformLength/a4subtype', $header );
143 $subtype = $arr['subtype'];
144 if ( $arr['magic'] != 'AT&T' ) {
145 wfDebug( __METHOD__
. ": not a DjVu file\n" );
146 } elseif ( $subtype == 'DJVU' ) {
147 // Single-page document
148 $info = $this->getPageInfo( $file );
149 } elseif ( $subtype == 'DJVM' ) {
150 // Multi-page document
151 $info = $this->getMultiPageInfo( $file, $arr['formLength'] );
153 wfDebug( __METHOD__
. ": unrecognized DJVU file type '{$arr['subtype']}'\n" );
161 private function readChunk( $file ) {
162 $header = fread( $file, 8 );
163 if ( strlen( $header ) < 8 ) {
166 $arr = unpack( 'a4chunk/Nlength', $header );
168 return [ $arr['chunk'], $arr['length'] ];
172 private function skipChunk( $file, $chunkLength ) {
173 fseek( $file, $chunkLength, SEEK_CUR
);
175 if ( ( $chunkLength & 1 ) && !feof( $file ) ) {
177 fseek( $file, 1, SEEK_CUR
);
181 private function getMultiPageInfo( $file, $formLength ) {
182 // For now, we'll just look for the first page in the file
183 // and report its information, hoping others are the same size.
184 $start = ftell( $file );
186 list( $chunk, $length ) = $this->readChunk( $file );
191 if ( $chunk == 'FORM' ) {
192 $subtype = fread( $file, 4 );
193 if ( $subtype == 'DJVU' ) {
194 wfDebug( __METHOD__
. ": found first subpage\n" );
196 return $this->getPageInfo( $file );
198 $this->skipChunk( $file, $length - 4 );
200 wfDebug( __METHOD__
. ": skipping '$chunk' chunk\n" );
201 $this->skipChunk( $file, $length );
203 } while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
205 wfDebug( __METHOD__
. ": multi-page DJVU file contained no pages\n" );
210 private function getPageInfo( $file ) {
211 list( $chunk, $length ) = $this->readChunk( $file );
212 if ( $chunk != 'INFO' ) {
213 wfDebug( __METHOD__
. ": expected INFO chunk, got '$chunk'\n" );
219 wfDebug( __METHOD__
. ": INFO should be 9 or 10 bytes, found $length\n" );
223 $data = fread( $file, $length );
224 if ( strlen( $data ) < $length ) {
225 wfDebug( __METHOD__
. ": INFO chunk cut off\n" );
238 # Newer files have rotation info in byte 10, but we don't use it yet.
241 'width' => $arr['width'],
242 'height' => $arr['height'],
243 'version' => "{$arr['major']}.{$arr['minor']}",
244 'resolution' => $arr['resolution'],
245 'gamma' => $arr['gamma'] / 10.0 ];
249 * Return an XML string describing the DjVu image
250 * @return string|bool
252 function retrieveMetaData() {
253 global $wgDjvuToXML, $wgDjvuDump, $wgDjvuTxt;
255 if ( !$this->isValid() ) {
259 if ( isset( $wgDjvuDump ) ) {
260 # djvudump is faster as of version 3.5
261 # https://sourceforge.net/p/djvu/bugs/71/
262 $cmd = Shell
::escape( $wgDjvuDump ) . ' ' . Shell
::escape( $this->mFilename
);
263 $dump = wfShellExec( $cmd );
264 $xml = $this->convertDumpToXML( $dump );
265 } elseif ( isset( $wgDjvuToXML ) ) {
266 $cmd = Shell
::escape( $wgDjvuToXML ) . ' --without-anno --without-text ' .
267 Shell
::escape( $this->mFilename
);
268 $xml = wfShellExec( $cmd );
273 if ( isset( $wgDjvuTxt ) ) {
274 $cmd = Shell
::escape( $wgDjvuTxt ) . ' --detail=page ' . Shell
::escape( $this->mFilename
);
275 wfDebug( __METHOD__
. ": $cmd\n" );
277 $txt = wfShellExec( $cmd, $retval, [], [ 'memory' => self
::DJVUTXT_MEMORY_LIMIT
] );
278 if ( $retval == 0 ) {
279 # Strip some control characters
280 $txt = preg_replace( "/[\013\035\037]/", "", $txt );
282 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
283 ((?> # Text to match is composed of atoms of either:
284 \\\\. # - any escaped character
285 | # - any character different from " and \
289 | # Or page can be empty ; in this case, djvutxt dumps ()
292 $txt = preg_replace_callback( $reg, [ $this, 'pageTextCallback' ], $txt );
293 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
294 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 ) .
303 function pageTextCallback( $matches ) {
304 # Get rid of invalid UTF-8, strip control characters
305 $val = htmlspecialchars( UtfNormal\Validator
::cleanUp( stripcslashes( $matches[1] ) ) );
306 $val = str_replace( [ "\n", '�' ], [ ' ', '' ], $val );
307 return '<PAGE value="' . $val . '" />';
311 * Hack to temporarily work around djvutoxml bug
312 * @param string $dump
315 function convertDumpToXML( $dump ) {
316 if ( strval( $dump ) == '' ) {
321 <?xml version="1.0" ?>
322 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
328 $dump = str_replace( "\r", '', $dump );
329 $line = strtok( $dump, "\n" );
332 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
334 if ( $this->parseFormDjvu( $line, $xml ) ) {
339 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
341 $parentLevel = strlen( $m[1] );
343 $line = strtok( "\n" );
344 while ( $line !== false ) {
345 $childLevel = strspn( $line, ' ' );
346 if ( $childLevel <= $parentLevel ) {
351 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
352 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
356 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
358 if ( $this->parseFormDjvu( $line, $xml ) ) {
364 $line = strtok( "\n" );
371 $xml .= "</BODY>\n</DjVuXML>\n";
376 function parseFormDjvu( $line, &$xml ) {
377 $parentLevel = strspn( $line, ' ' );
378 $line = strtok( "\n" );
381 while ( $line !== false ) {
382 $childLevel = strspn( $line, ' ' );
383 if ( $childLevel <= $parentLevel ) {
389 '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
397 # 'type' => 'image/x.djvu',
403 Xml
::element( 'PARAM', [ 'name' => 'DPI', 'value' => $m[3] ] ) . "\n" .
404 Xml
::element( 'PARAM', [ 'name' => 'GAMMA', 'value' => $m[4] ] ) . "\n"
409 $line = strtok( "\n" );