MediaWiki REL1_27
DjVuImage.php
Go to the documentation of this file.
1<?php
36class DjVuImage {
40 const DJVUTXT_MEMORY_LIMIT = 300000;
41
47 function __construct( $filename ) {
48 $this->mFilename = $filename;
49 }
50
55 public function isValid() {
56 $info = $this->getInfo();
57
58 return $info !== false;
59 }
60
65 public function getImageSize() {
66 $data = $this->getInfo();
67
68 if ( $data !== false ) {
69 $width = $data['width'];
70 $height = $data['height'];
71
72 return [ $width, $height, 'DjVu',
73 "width=\"$width\" height=\"$height\"" ];
74 }
75
76 return false;
77 }
78
79 // ---------
80
84 function dump() {
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 ) );
92 echo "$chunk $chunkLength\n";
93 $this->dumpForm( $file, $chunkLength, 1 );
94 fclose( $file );
95 }
96
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 == '' ) {
104 break;
105 }
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 ) );
111 echo str_repeat( ' ', $indent * 4 ) . "$chunk $chunkLength\n";
112
113 if ( $chunk == 'FORM' ) {
114 $this->dumpForm( $file, $chunkLength, $indent + 1 );
115 } else {
116 fseek( $file, $chunkLength, SEEK_CUR );
117 if ( $chunkLength & 1 == 1 ) {
118 // Padding byte between chunks
119 fseek( $file, 1, SEEK_CUR );
120 }
121 }
122 }
123 }
124
125 function getInfo() {
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" );
131
132 return false;
133 }
134
135 $header = fread( $file, 16 );
136 $info = false;
137
138 if ( strlen( $header ) < 16 ) {
139 wfDebug( __METHOD__ . ": too short file header\n" );
140 } else {
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 ) );
144
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 );
157 } else {
158 wfDebug( __METHOD__ . ": unrecognized DJVU file type '$formType'\n" );
159 }
160 }
161 fclose( $file );
162
163 return $info;
164 }
165
166 private function readChunk( $file ) {
167 $header = fread( $file, 8 );
168 if ( strlen( $header ) < 8 ) {
169 return [ false, 0 ];
170 } else {
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 ) );
174
177 return [ $chunk, $length ];
178 }
179 }
180
181 private function skipChunk( $file, $chunkLength ) {
182 fseek( $file, $chunkLength, SEEK_CUR );
183
184 if ( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
185 // padding byte
186 fseek( $file, 1, SEEK_CUR );
187 }
188 }
189
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 );
194 do {
195 list( $chunk, $length ) = $this->readChunk( $file );
196 if ( !$chunk ) {
197 break;
198 }
199
200 if ( $chunk == 'FORM' ) {
201 $subtype = fread( $file, 4 );
202 if ( $subtype == 'DJVU' ) {
203 wfDebug( __METHOD__ . ": found first subpage\n" );
204
205 return $this->getPageInfo( $file );
206 }
207 $this->skipChunk( $file, $length - 4 );
208 } else {
209 wfDebug( __METHOD__ . ": skipping '$chunk' chunk\n" );
210 $this->skipChunk( $file, $length );
211 }
212 } while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
213
214 wfDebug( __METHOD__ . ": multi-page DJVU file contained no pages\n" );
215
216 return false;
217 }
218
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" );
223
224 return false;
225 }
226
227 if ( $length < 9 ) {
228 wfDebug( __METHOD__ . ": INFO should be 9 or 10 bytes, found $length\n" );
229
230 return false;
231 }
232 $data = fread( $file, $length );
233 if ( strlen( $data ) < $length ) {
234 wfDebug( __METHOD__ . ": INFO chunk cut off\n" );
235
236 return false;
237 }
238
239 // @todo FIXME: Would be good to replace this extract() call with
240 // something that explicitly initializes local variables.
241 extract( unpack(
242 'nwidth/' .
243 'nheight/' .
244 'Cminor/' .
245 'Cmajor/' .
246 'vresolution/' .
247 'Cgamma', $data ) );
248
249 # Newer files have rotation info in byte 10, but we don't use it yet.
250
258 return [
259 'width' => $width,
260 'height' => $height,
261 'version' => "$major.$minor",
262 'resolution' => $resolution,
263 'gamma' => $gamma / 10.0 ];
264 }
265
270 function retrieveMetaData() {
272
273 if ( !$this->isValid() ) {
274 return false;
275 }
276
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 );
287 } else {
288 $xml = null;
289 }
290 # Text layer
291 if ( isset( $wgDjvuTxt ) ) {
292 $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename );
293 wfDebug( __METHOD__ . ": $cmd\n" );
294 $retval = '';
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 );
299 $reg = <<<EOR
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 \
304 [^"\\\\]+
305 )*?)
306 "\s*\‍)
307 | # Or page can be empty ; in this case, djvutxt dumps ()
308 \‍(\s*()\)/sx
309EOR;
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>';
314 }
315 }
316
317 return $xml;
318 }
319
321 # Get rid of invalid UTF-8, strip control characters
322 $val = htmlspecialchars( UtfNormal\Validator::cleanUp( stripcslashes( $matches[1] ) ) );
323 $val = str_replace( [ "\n", '�' ], [ '&#10;', '' ], $val );
324 return '<PAGE value="' . $val . '" />';
325 }
326
332 function convertDumpToXML( $dump ) {
333 if ( strval( $dump ) == '' ) {
334 return false;
335 }
336
337 $xml = <<<EOT
338<?xml version="1.0" ?>
339<!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
340<DjVuXML>
341<HEAD></HEAD>
342<BODY>
343EOT;
344
345 $dump = str_replace( "\r", '', $dump );
346 $line = strtok( $dump, "\n" );
347 $m = false;
348 $good = false;
349 if ( preg_match( '/^( *)FORM:DJVU/', $line, $m ) ) {
350 # Single-page
351 if ( $this->parseFormDjvu( $line, $xml ) ) {
352 $good = true;
353 } else {
354 return false;
355 }
356 } elseif ( preg_match( '/^( *)FORM:DJVM/', $line, $m ) ) {
357 # Multi-page
358 $parentLevel = strlen( $m[1] );
359 # Find DIRM
360 $line = strtok( "\n" );
361 while ( $line !== false ) {
362 $childLevel = strspn( $line, ' ' );
363 if ( $childLevel <= $parentLevel ) {
364 # End of chunk
365 break;
366 }
367
368 if ( preg_match( '/^ *DIRM.*indirect/', $line ) ) {
369 wfDebug( "Indirect multi-page DjVu document, bad for server!\n" );
370
371 return false;
372 }
373 if ( preg_match( '/^ *FORM:DJVU/', $line ) ) {
374 # Found page
375 if ( $this->parseFormDjvu( $line, $xml ) ) {
376 $good = true;
377 } else {
378 return false;
379 }
380 }
381 $line = strtok( "\n" );
382 }
383 }
384 if ( !$good ) {
385 return false;
386 }
387
388 $xml .= "</BODY>\n</DjVuXML>\n";
389
390 return $xml;
391 }
392
393 function parseFormDjvu( $line, &$xml ) {
394 $parentLevel = strspn( $line, ' ' );
395 $line = strtok( "\n" );
396
397 # Find INFO
398 while ( $line !== false ) {
399 $childLevel = strspn( $line, ' ' );
400 if ( $childLevel <= $parentLevel ) {
401 # End of chunk
402 break;
403 }
404
405 if ( preg_match(
406 '/^ *INFO *\[\d*\] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
407 $line,
408 $m
409 ) ) {
410 $xml .= Xml::tags(
411 'OBJECT',
412 [
413 # 'data' => '',
414 # 'type' => 'image/x.djvu',
415 'height' => $m[2],
416 'width' => $m[1],
417 # 'usemap' => '',
418 ],
419 "\n" .
420 Xml::element( 'PARAM', [ 'name' => 'DPI', 'value' => $m[3] ] ) . "\n" .
421 Xml::element( 'PARAM', [ 'name' => 'GAMMA', 'value' => $m[4] ] ) . "\n"
422 ) . "\n";
423
424 return true;
425 }
426 $line = strtok( "\n" );
427 }
428
429 # Not found
430 return false;
431 }
432}
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
$wgDjvuToXML
Path of the djvutoxml executable This works like djvudump except much, much slower as of version 3....
$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...
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell,...
$line
Definition cdb.php:59
Support for detecting/validating DjVu image files and getting some basic file metadata (resolution et...
Definition DjVuImage.php:36
getPageInfo( $file)
convertDumpToXML( $dump)
Hack to temporarily work around djvutoxml bug.
parseFormDjvu( $line, &$xml)
retrieveMetaData()
Return an XML string describing the DjVu image.
const DJVUTXT_MEMORY_LIMIT
@const DJVUTXT_MEMORY_LIMIT Memory limit for the DjVu description software
Definition DjVuImage.php:40
skipChunk( $file, $chunkLength)
dumpForm( $file, $length, $indent)
Definition DjVuImage.php:97
pageTextCallback( $matches)
dump()
For debugging; dump the IFF chunk structure.
Definition DjVuImage.php:84
isValid()
Check if the given file is indeed a valid DjVu image file.
Definition DjVuImage.php:55
getMultiPageInfo( $file, $formLength)
readChunk( $file)
getImageSize()
Return data in the style of getimagesize()
Definition DjVuImage.php:65
__construct( $filename)
Constructor.
Definition DjVuImage.php:47
Unicode normalization routines for working with UTF-8 strings.
Definition UtfNormal.php:48
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition Xml.php:131
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition Xml.php:39
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:268
null for the local wiki Added in
Definition hooks.txt:1421
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition hooks.txt:2388
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Prior to version