MediaWiki REL1_37
DjVuImage.php
Go to the documentation of this file.
1<?php
28
38class DjVuImage {
39
43 private const DJVUTXT_MEMORY_LIMIT = 300000;
44
46 private $mFilename;
47
51 public function __construct( $filename ) {
52 $this->mFilename = $filename;
53 }
54
59 public function isValid() {
60 $info = $this->getInfo();
61
62 return $info !== false;
63 }
64
69 public function getImageSize() {
70 $data = $this->getInfo();
71
72 if ( $data !== false ) {
73 return [
74 'width' => $data['width'],
75 'height' => $data['height']
76 ];
77 } else {
78 return [];
79 }
80 }
81
82 // ---------
83
87 public function dump() {
88 $file = fopen( $this->mFilename, 'rb' );
89 $header = fread( $file, 12 );
90 $arr = unpack( 'a4magic/a4chunk/NchunkLength', $header );
91 $chunk = $arr['chunk'];
92 $chunkLength = $arr['chunkLength'];
93 echo "$chunk $chunkLength\n";
94 $this->dumpForm( $file, $chunkLength, 1 );
95 fclose( $file );
96 }
97
98 private function dumpForm( $file, $length, $indent ) {
99 $start = ftell( $file );
100 $secondary = fread( $file, 4 );
101 echo str_repeat( ' ', $indent * 4 ) . "($secondary)\n";
102 while ( ftell( $file ) - $start < $length ) {
103 $chunkHeader = fread( $file, 8 );
104 if ( $chunkHeader == '' ) {
105 break;
106 }
107 $arr = unpack( 'a4chunk/NchunkLength', $chunkHeader );
108 $chunk = $arr['chunk'];
109 $chunkLength = $arr['chunkLength'];
110 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
111
112 if ( $chunk == 'FORM' ) {
113 $this->dumpForm( $file, $chunkLength, $indent + 1 );
114 } else {
115 fseek( $file, $chunkLength, SEEK_CUR );
116 if ( $chunkLength & 1 ) {
117 // Padding byte between chunks
118 fseek( $file, 1, SEEK_CUR );
119 }
120 }
121 }
122 }
123
124 private function getInfo() {
125 Wikimedia\suppressWarnings();
126 $file = fopen( $this->mFilename, 'rb' );
127 Wikimedia\restoreWarnings();
128 if ( $file === false ) {
129 wfDebug( __METHOD__ . ": missing or failed file read" );
130
131 return false;
132 }
133
134 $header = fread( $file, 16 );
135 $info = false;
136
137 if ( strlen( $header ) < 16 ) {
138 wfDebug( __METHOD__ . ": too short file header" );
139 } else {
140 $arr = unpack( 'a4magic/a4form/NformLength/a4subtype', $header );
141
142 $subtype = $arr['subtype'];
143 if ( $arr['magic'] != 'AT&T' ) {
144 wfDebug( __METHOD__ . ": not a DjVu file" );
145 } elseif ( $subtype == 'DJVU' ) {
146 // Single-page document
147 $info = $this->getPageInfo( $file );
148 } elseif ( $subtype == 'DJVM' ) {
149 // Multi-page document
150 $info = $this->getMultiPageInfo( $file, $arr['formLength'] );
151 } else {
152 wfDebug( __METHOD__ . ": unrecognized DJVU file type '{$arr['subtype']}'" );
153 }
154 }
155 fclose( $file );
156
157 return $info;
158 }
159
160 private function readChunk( $file ) {
161 $header = fread( $file, 8 );
162 if ( strlen( $header ) < 8 ) {
163 return [ false, 0 ];
164 } else {
165 $arr = unpack( 'a4chunk/Nlength', $header );
166
167 return [ $arr['chunk'], $arr['length'] ];
168 }
169 }
170
171 private function skipChunk( $file, $chunkLength ) {
172 fseek( $file, $chunkLength, SEEK_CUR );
173
174 if ( ( $chunkLength & 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" );
194
195 return $this->getPageInfo( $file );
196 }
197 $this->skipChunk( $file, $length - 4 );
198 } else {
199 wfDebug( __METHOD__ . ": skipping '$chunk' chunk" );
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" );
205
206 return false;
207 }
208
209 private function getPageInfo( $file ) {
210 list( $chunk, $length ) = $this->readChunk( $file );
211 if ( $chunk != 'INFO' ) {
212 wfDebug( __METHOD__ . ": expected INFO chunk, got '$chunk'" );
213
214 return false;
215 }
216
217 if ( $length < 9 ) {
218 wfDebug( __METHOD__ . ": INFO should be 9 or 10 bytes, found $length" );
219
220 return false;
221 }
222 $data = fread( $file, $length );
223 if ( strlen( $data ) < $length ) {
224 wfDebug( __METHOD__ . ": INFO chunk cut off" );
225
226 return false;
227 }
228
229 $arr = unpack(
230 'nwidth/' .
231 'nheight/' .
232 'Cminor/' .
233 'Cmajor/' .
234 'vresolution/' .
235 'Cgamma', $data );
236
237 # Newer files have rotation info in byte 10, but we don't use it yet.
238
239 return [
240 'width' => $arr['width'],
241 'height' => $arr['height'],
242 'version' => "{$arr['major']}.{$arr['minor']}",
243 'resolution' => $arr['resolution'],
244 'gamma' => $arr['gamma'] / 10.0 ];
245 }
246
251 public function retrieveMetaData() {
252 global $wgDjvuDump, $wgDjvuTxt;
253
254 if ( !$this->isValid() ) {
255 return false;
256 }
257
258 if ( isset( $wgDjvuDump ) ) {
259 # djvudump is faster than djvutoxml (now abandoned) as of version 3.5
260 # https://sourceforge.net/p/djvu/bugs/71/
261 $cmd = Shell::escape( $wgDjvuDump ) . ' ' . Shell::escape( $this->mFilename );
262 $dump = wfShellExec( $cmd );
263 $xml = $this->convertDumpToXML( $dump );
264 } else {
265 $xml = null;
266 }
267 # Text layer
268 if ( isset( $wgDjvuTxt ) ) {
269 $cmd = Shell::escape( $wgDjvuTxt ) . ' --detail=page ' . Shell::escape( $this->mFilename );
270 wfDebug( __METHOD__ . ": $cmd" );
271 $retval = '';
272 $txt = wfShellExec( $cmd, $retval, [], [ 'memory' => self::DJVUTXT_MEMORY_LIMIT ] );
273 if ( $retval == 0 ) {
274 # Strip some control characters
275 # Ignore carriage returns
276 $txt = preg_replace( "/\\\\013/", "", $txt );
277 # Replace runs of OCR region separators with a single extra line break
278 $txt = preg_replace( "/(?:\\\\(035|037))+/", "\n", $txt );
279
280 $reg = <<<EOR
281 /\‍(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*"
282 ((?> # Text to match is composed of atoms of either:
283 \\\\. # - any escaped character
284 | # - any character different from " and \
285 [^"\\\\]+
286 )*?)
287 "\s*\‍)
288 | # Or page can be empty ; in this case, djvutxt dumps ()
289 \‍(\s*()\)/sx
290EOR;
291 $txt = preg_replace_callback( $reg, [ $this, 'pageTextCallback' ], $txt );
292 $txt = "<DjVuTxt>\n<HEAD></HEAD>\n<BODY>\n" . $txt . "</BODY>\n</DjVuTxt>\n";
293 $xml = preg_replace( "/<DjVuXML>/", "<mw-djvu><DjVuXML>", $xml, 1 ) .
294 $txt .
295 '</mw-djvu>';
296 }
297 }
298
299 return $xml;
300 }
301
302 private function pageTextCallback( $matches ) {
303 # Get rid of invalid UTF-8, strip control characters
304 $val = htmlspecialchars( UtfNormal\Validator::cleanUp( stripcslashes( $matches[1] ) ) );
305 $val = str_replace( [ "\n", '�' ], [ '&#10;', '' ], $val );
306 return '<PAGE value="' . $val . '" />';
307 }
308
314 private function convertDumpToXML( $dump ) {
315 if ( strval( $dump ) == '' ) {
316 return false;
317 }
318
319 $xml = <<<EOT
320<?xml version="1.0" ?>
321<!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
322<DjVuXML>
323<HEAD></HEAD>
324<BODY>
325EOT;
326
327 $dump = str_replace( "\r", '', $dump );
328 $line = strtok( $dump, "\n" );
329 $m = false;
330 $good = false;
331 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
332 # Single-page
333 if ( $this->parseFormDjvu( $line, $xml ) ) {
334 $good = true;
335 } else {
336 return false;
337 }
338 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
339 # Multi-page
340 $parentLevel = strlen( $m[1] );
341 # Find DIRM
342 $line = strtok( "\n" );
343 while ( $line !== false ) {
344 $childLevel = strspn( $line, ' ' );
345 if ( $childLevel <= $parentLevel ) {
346 # End of chunk
347 break;
348 }
349
350 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
351 wfDebug( "Indirect multi-page DjVu document, bad for server!" );
352
353 return false;
354 }
355 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
356 # Found page
357 if ( $this->parseFormDjvu( $line, $xml ) ) {
358 $good = true;
359 } else {
360 return false;
361 }
362 }
363 $line = strtok( "\n" );
364 }
365 }
366 if ( !$good ) {
367 return false;
368 }
369
370 $xml .= "</BODY>\n</DjVuXML>\n";
371
372 return $xml;
373 }
374
375 private function parseFormDjvu( $line, &$xml ) {
376 $parentLevel = strspn( $line, ' ' );
377 $line = strtok( "\n" );
378
379 # Find INFO
380 while ( $line !== false ) {
381 $childLevel = strspn( $line, ' ' );
382 if ( $childLevel <= $parentLevel ) {
383 # End of chunk
384 break;
385 }
386
387 if ( preg_match(
388 '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
389 $line,
390 $m
391 ) ) {
392 $xml .= Xml::tags(
393 'OBJECT',
394 [
395 # 'data' => '',
396 # 'type' => 'image/x.djvu',
397 'height' => $m[2],
398 'width' => $m[1],
399 # 'usemap' => '',
400 ],
401 "\n" .
402 Xml::element( 'PARAM', [ 'name' => 'DPI', 'value' => $m[3] ] ) . "\n" .
403 Xml::element( 'PARAM', [ 'name' => 'GAMMA', 'value' => $m[4] ] ) . "\n"
404 ) . "\n";
405
406 return true;
407 }
408 $line = strtok( "\n" );
409 }
410
411 # Not found
412 return false;
413 }
414}
$wgDjvuTxt
Path of the djvutxt DJVU text extraction utility Enable this and $wgDjvuDump to enable text layer ext...
$wgDjvuDump
Path of the djvudump executable Enable this and $wgDjvuRenderer to enable djvu rendering example: $wg...
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Support for detecting/validating DjVu image files and getting some basic file metadata (resolution et...
Definition DjVuImage.php:38
getPageInfo( $file)
convertDumpToXML( $dump)
Hack to temporarily work around djvutoxml bug.
string $mFilename
Definition DjVuImage.php:46
parseFormDjvu( $line, &$xml)
retrieveMetaData()
Return an XML string describing the DjVu image.
const DJVUTXT_MEMORY_LIMIT
Memory limit for the DjVu description software.
Definition DjVuImage.php:43
skipChunk( $file, $chunkLength)
dumpForm( $file, $length, $indent)
Definition DjVuImage.php:98
pageTextCallback( $matches)
dump()
For debugging; dump the IFF chunk structure.
Definition DjVuImage.php:87
isValid()
Check if the given file is indeed a valid DjVu image file.
Definition DjVuImage.php:59
getMultiPageInfo( $file, $formLength)
readChunk( $file)
getImageSize()
Return width and height.
Definition DjVuImage.php:69
__construct( $filename)
Definition DjVuImage.php:51
Executes shell commands.
Definition Shell.php:45
$line
Definition mcc.php:119
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
$header