32 private const DJVUTXT_MEMORY_LIMIT = 300_000_000;
41 $this->mFilename = $filename;
49 $info = $this->getInfo();
51 return $info !==
false;
59 $data = $this->getInfo();
61 if ( $data !==
false ) {
63 'width' => $data[
'width'],
64 'height' => $data[
'height']
76 $file = fopen( $this->mFilename,
'rb' );
77 $header = fread( $file, 12 );
78 $arr = unpack(
'a4magic/a4chunk/NchunkLength', $header );
79 $chunk = $arr[
'chunk'];
80 $chunkLength = $arr[
'chunkLength'];
81 echo
"$chunk $chunkLength\n";
82 $this->dumpForm( $file, $chunkLength, 1 );
91 private function dumpForm( $file,
int $length,
int $indent ) {
92 $start = ftell( $file );
93 $secondary = fread( $file, 4 );
94 echo str_repeat(
' ', $indent * 4 ) .
"($secondary)\n";
95 while ( ftell( $file ) - $start < $length ) {
96 $chunkHeader = fread( $file, 8 );
97 if ( $chunkHeader ==
'' ) {
100 $arr = unpack(
'a4chunk/NchunkLength', $chunkHeader );
101 $chunk = $arr[
'chunk'];
102 $chunkLength = $arr[
'chunkLength'];
103 echo str_repeat(
' ', $indent * 4 ) .
"$chunk $chunkLength\n";
105 if ( $chunk ===
'FORM' ) {
106 $this->dumpForm( $file, $chunkLength, $indent + 1 );
108 fseek( $file, $chunkLength, SEEK_CUR );
109 if ( $chunkLength & 1 ) {
111 fseek( $file, 1, SEEK_CUR );
118 private function getInfo() {
119 AtEase::suppressWarnings();
120 $file = fopen( $this->mFilename,
'rb' );
121 AtEase::restoreWarnings();
122 if ( $file ===
false ) {
123 wfDebug( __METHOD__ .
": missing or failed file read" );
128 $header = fread( $file, 16 );
131 if ( strlen( $header ) < 16 ) {
132 wfDebug( __METHOD__ .
": too short file header" );
134 $arr = unpack(
'a4magic/a4form/NformLength/a4subtype', $header );
136 $subtype = $arr[
'subtype'];
137 if ( $arr[
'magic'] !==
'AT&T' ) {
138 wfDebug( __METHOD__ .
": not a DjVu file" );
139 } elseif ( $subtype ===
'DJVU' ) {
141 $info = $this->getPageInfo( $file );
142 } elseif ( $subtype ===
'DJVM' ) {
144 $info = $this->getMultiPageInfo( $file, $arr[
'formLength'] );
146 wfDebug( __METHOD__ .
": unrecognized DJVU file type '{$arr['subtype']}'" );
157 private function readChunk( $file ): array {
158 $header = fread( $file, 8 );
159 if ( strlen( $header ) < 8 ) {
162 $arr = unpack(
'a4chunk/Nlength', $header );
164 return [ $arr[
'chunk'], $arr[
'length'] ];
171 private function skipChunk( $file,
int $chunkLength ) {
172 fseek( $file, $chunkLength, SEEK_CUR );
174 if ( ( $chunkLength & 1 ) && !feof( $file ) ) {
176 fseek( $file, 1, SEEK_CUR );
185 private function getMultiPageInfo( $file,
int $formLength ) {
188 $start = ftell( $file );
190 [ $chunk, $length ] = $this->readChunk( $file );
195 if ( $chunk ===
'FORM' ) {
196 $subtype = fread( $file, 4 );
197 if ( $subtype ===
'DJVU' ) {
198 wfDebug( __METHOD__ .
": found first subpage" );
200 return $this->getPageInfo( $file );
202 $this->skipChunk( $file, $length - 4 );
204 wfDebug( __METHOD__ .
": skipping '$chunk' chunk" );
205 $this->skipChunk( $file, $length );
207 }
while ( $length != 0 && !feof( $file ) && ftell( $file ) - $start < $formLength );
209 wfDebug( __METHOD__ .
": multi-page DJVU file contained no pages" );
218 private function getPageInfo( $file ) {
219 [ $chunk, $length ] = $this->readChunk( $file );
220 if ( $chunk !==
'INFO' ) {
221 wfDebug( __METHOD__ .
": expected INFO chunk, got '$chunk'" );
227 wfDebug( __METHOD__ .
": INFO should be 9 or 10 bytes, found $length" );
231 $data = fread( $file, $length );
232 if ( strlen( $data ) < $length ) {
233 wfDebug( __METHOD__ .
": INFO chunk cut off" );
246 # Newer files have rotation info in byte 10, but we don't use it yet.
249 'width' => $arr[
'width'],
250 'height' => $arr[
'height'],
251 'version' =>
"{$arr['major']}.{$arr['minor']}",
252 'resolution' => $arr[
'resolution'],
253 'gamma' => $arr[
'gamma'] / 10.0 ];
261 $config = MediaWikiServices::getInstance()->getMainConfig();
262 $djvuDump = $config->get( MainConfigNames::DjvuDump );
263 $djvuTxt = $config->get( MainConfigNames::DjvuTxt );
264 $djvuUseBoxedCommand = $config->get( MainConfigNames::DjvuUseBoxedCommand );
265 $shell = $config->get( MainConfigNames::ShellboxShell );
266 if ( !$this->isValid() ) {
270 if ( $djvuTxt ===
null && $djvuDump ===
null ) {
277 if ( $djvuUseBoxedCommand ) {
278 $command = MediaWikiServices::getInstance()->getShellCommandFactory()
279 ->createBoxed(
'djvu' )
281 ->firejailDefaultSeccomp()
282 ->routeName(
'djvu-metadata' )
283 ->params( $shell,
'scripts/retrieveDjvuMetaData.sh' )
285 'scripts/retrieveDjvuMetaData.sh',
286 __DIR__ .
'/scripts/retrieveDjvuMetaData.sh' )
287 ->inputFileFromFile(
'file.djvu', $this->mFilename )
288 ->memoryLimit( self::DJVUTXT_MEMORY_LIMIT );
290 if ( $djvuDump !==
null ) {
291 $env[
'DJVU_DUMP'] = $djvuDump;
292 $command->outputFileToString(
'dump' );
294 if ( $djvuTxt !==
null ) {
295 $env[
'DJVU_TXT'] = $djvuTxt;
296 $command->outputFileToString(
'txt' );
300 ->environment( $env )
302 if ( $result->getExitCode() !== 0 ) {
303 wfDebug(
'retrieveDjvuMetaData failed with exit code ' . $result->getExitCode() );
306 if ( $djvuDump !==
null ) {
307 if ( $result->wasReceived(
'dump' ) ) {
308 $dump = $result->getFileContents(
'dump' );
310 wfDebug( __METHOD__ .
": did not receive dump file" );
314 if ( $djvuTxt !==
null ) {
315 if ( $result->wasReceived(
'txt' ) ) {
316 $txt = $result->getFileContents(
'txt' );
318 wfDebug( __METHOD__ .
": did not receive text file" );
322 if ( $djvuDump !==
null ) {
323 # djvudump is faster than djvutoxml (now abandoned) as of version 3.5
325 $cmd = Shell::escape( $djvuDump ) .
' ' . Shell::escape( $this->mFilename );
328 if ( $djvuTxt !==
null ) {
329 $cmd = Shell::escape( $djvuTxt ) .
' --detail=page ' . Shell::escape( $this->mFilename );
330 wfDebug( __METHOD__ .
": $cmd" );
332 $txt =
wfShellExec( $cmd, $retval, [], [
'memory' => self::DJVUTXT_MEMORY_LIMIT ] );
333 if ( $retval !== 0 ) {
339 # Convert dump to array
341 if ( $dump !==
null ) {
342 $data = $this->convertDumpToJSON( $dump );
343 if ( $data !==
false ) {
344 $json = [
'data' => $data ];
349 if ( $txt !==
null ) {
350 # Strip some control characters
351 # Ignore carriage returns
352 $txt = preg_replace(
"/\\\\013/",
"", $txt );
353 # Replace runs of OCR region separators with a single extra line break
354 $txt = preg_replace(
"/(?:\\\\(035|037))+/",
"\n", $txt );
357 /\(page\s[\d-]*\s[\d-]*\s[\d-]*\s[\d-]*\s*
"
358 ((?> # Text to match is composed of atoms of either:
359 \\\\. # - any escaped character
360 | # - any character different from " and \
364 | # Or page can be empty ; in
this case, djvutxt dumps ()
368 preg_match_all( $reg, $txt,
$matches );
369 $json[
'text'] = array_map( $this->pageTextCallback( ... ),
$matches[1] );
377 private function pageTextCallback(
string $match ): string {
378 # Get rid of invalid UTF-8
379 $val = UtfNormal\Validator::cleanUp( stripcslashes( $match ) );
380 return str_replace(
'�',
'', $val );
387 private function convertDumpToJSON( $dump ) {
388 if ( strval( $dump ) ==
'' ) {
392 $dump = str_replace(
"\r",
'', $dump );
393 $line = strtok( $dump,
"\n" );
397 if ( preg_match(
'/^( *)FORM:DJVU/', $line, $m ) ) {
399 $parsed = $this->parseFormDjvu( $line );
405 $result[
'pages'] = [ $parsed ];
406 } elseif ( preg_match(
'/^( *)FORM:DJVM/', $line, $m ) ) {
408 $parentLevel = strlen( $m[1] );
410 $line = strtok(
"\n" );
411 $result[
'pages'] = [];
412 while ( $line !==
false ) {
413 $childLevel = strspn( $line,
' ' );
414 if ( $childLevel <= $parentLevel ) {
419 if ( preg_match(
'/^ *DIRM.*indirect/', $line ) ) {
420 wfDebug(
"Indirect multi-page DjVu document, bad for server!" );
425 if ( preg_match(
'/^ *FORM:DJVU/', $line ) ) {
427 $parsed = $this->parseFormDjvu( $line );
433 $result[
'pages'][] = $parsed;
435 $line = strtok(
"\n" );
446 private function parseFormDjvu(
string $line ) {
447 $parentLevel = strspn( $line,
' ' );
448 $line = strtok(
"\n" );
450 while ( $line !==
false ) {
451 $childLevel = strspn( $line,
' ' );
452 if ( $childLevel <= $parentLevel ) {
458 '/^ *INFO *\[\d*] *DjVu *(\d+)x(\d+), *\w*, *(\d+) *dpi, *gamma=([0-9.-]+)/',
463 'height' => (int)$m[2],
464 'width' => (
int)$m[1],
465 'dpi' => (float)$m[3],
466 'gamma' => (
float)$m[4],
469 $line = strtok(
"\n" );
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...