MediaWiki master
DjVuHandler.php
Go to the documentation of this file.
1<?php
15
22 private const EXPENSIVE_SIZE_LIMIT = 10_485_760; // 10MiB
23
24 // Constants for getHandlerState
25 private const STATE_DJVU_IMAGE = 'djvuImage';
26 private const STATE_TEXT_TREE = 'djvuTextTree';
27 private const STATE_META_TREE = 'djvuMetaTree';
28 private const CACHE_VERSION = 'v2';
29
33 public function isEnabled() {
34 $djvuRenderer = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuRenderer );
35 $djvuDump = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuDump );
36 if ( !$djvuRenderer || !$djvuDump ) {
37 wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump" );
38
39 return false;
40 }
41 return true;
42 }
43
48 public function mustRender( $file ) {
49 return true;
50 }
51
57 public function isExpensiveToThumbnail( $file ) {
58 return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
59 }
60
65 public function isMultiPage( $file ) {
66 return true;
67 }
68
72 public function getParamMap() {
73 return [
74 'img_width' => 'width',
75 'img_page' => 'page',
76 ];
77 }
78
84 public function validateParam( $name, $value ) {
85 if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
86 // Extra junk on the end of page, probably actually a caption
87 // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
88 return false;
89 }
90 return in_array( $name, [ 'width', 'height', 'page' ] ) && $value > 0;
91 }
92
97 public function makeParamString( $params ) {
98 $page = $params['page'] ?? 1;
99 if ( !isset( $params['width'] ) ) {
100 return false;
101 }
102
103 return "page{$page}-{$params['width']}px";
104 }
105
110 public function parseParamString( $str ) {
111 $m = false;
112 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
113 return [ 'width' => $m[2], 'page' => $m[1] ];
114 }
115 return false;
116 }
117
122 protected function getScriptParams( $params ) {
123 return [
124 'width' => $params['width'],
125 'page' => $params['page'],
126 ];
127 }
128
137 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
138 $djvuRenderer = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuRenderer );
139 $djvuPostProcessor = MediaWikiServices::getInstance()->getMainConfig()
140 ->get( MainConfigNames::DjvuPostProcessor );
141 if ( !$this->normaliseParams( $image, $params ) ) {
142 return new TransformParameterError( $params );
143 }
144 $width = $params['width'];
145 $height = $params['height'];
146 $page = $params['page'];
147
148 if ( $flags & self::TRANSFORM_LATER ) {
149 $params = [
150 'width' => $width,
151 'height' => $height,
152 'page' => $page
153 ];
154
155 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
156 }
157
158 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
159 return new MediaTransformError(
160 'thumbnail_error',
161 $width,
162 $height,
163 wfMessage( 'thumbnail_dest_directory' )
164 );
165 }
166
167 // Get local copy source for shell scripts
168 // Thumbnail extraction is very inefficient for large files.
169 // Provide a way to pool count limit the number of downloaders.
170 if ( $image->getSize() >= 1e7 ) { // 10 MB
171 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
172 [
173 'doWork' => static function () use ( $image ) {
174 return $image->getLocalRefPath();
175 }
176 ]
177 );
178 $srcPath = $work->execute();
179 } else {
180 $srcPath = $image->getLocalRefPath();
181 }
182
183 if ( $srcPath === false ) { // Failed to get local copy
184 wfDebugLog( 'thumbnail',
185 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
186 wfHostname(), $image->getName() ) );
187
188 return new MediaTransformError( 'thumbnail_error',
189 $params['width'], $params['height'],
190 wfMessage( 'filemissing' )
191 );
192 }
193
194 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
195 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
196 $cmd = '(' . Shell::escape(
197 $djvuRenderer,
198 "-format=ppm",
199 "-page={$page}",
200 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
201 $srcPath );
202 if ( $djvuPostProcessor ) {
203 $cmd .= " | {$djvuPostProcessor}";
204 }
205 $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
206 wfDebug( __METHOD__ . ": $cmd" );
207 $retval = 0;
208 $err = wfShellExec( $cmd, $retval );
209
210 $removed = $this->removeBadFile( $dstPath, $retval );
211 if ( $retval !== 0 || $removed ) {
212 $this->logErrorForExternalProcess( $retval, $err, $cmd );
213 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
214 }
215 $params = [
216 'width' => $width,
217 'height' => $height,
218 'page' => $page
219 ];
220
221 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
222 }
223
232 private function getDjVuImage( $state, $path ) {
233 $deja = $state->getHandlerState( self::STATE_DJVU_IMAGE );
234 if ( !$deja ) {
235 $deja = new DjVuImage( $path );
236 $state->setHandlerState( self::STATE_DJVU_IMAGE, $deja );
237 }
238 return $deja;
239 }
240
248 private function getMetadataInternal( File $file, $gettext ) {
249 $itemNames = [ 'error', '_error', 'data' ];
250 if ( $gettext ) {
251 $itemNames[] = 'text';
252 }
253 $unser = $file->getMetadataItems( $itemNames );
254
255 if ( isset( $unser['error'] ) ) {
256 return false;
257 }
258 if ( isset( $unser['_error'] ) ) {
259 return false;
260 }
261 return $unser;
262 }
263
270 public function getMetaTree( $image, $gettext = false ) {
271 if ( $gettext && $image->getHandlerState( self::STATE_TEXT_TREE ) ) {
272 return $image->getHandlerState( self::STATE_TEXT_TREE );
273 }
274 if ( !$gettext && $image->getHandlerState( self::STATE_META_TREE ) ) {
275 return $image->getHandlerState( self::STATE_META_TREE );
276 }
277
278 $metadata = $this->getMetadataInternal( $image, $gettext );
279 if ( !$metadata ) {
280 return false;
281 }
282
283 if ( !$gettext ) {
284 unset( $metadata['text'] );
285 }
286 return $metadata;
287 }
288
290 public function getThumbType( $ext, $mime, $params = null ) {
291 $djvuOutputExtension = MediaWikiServices::getInstance()->getMainConfig()
292 ->get( MainConfigNames::DjvuOutputExtension );
293 static $djvuMime = null;
294 if ( $djvuMime === null ) {
295 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
296 $djvuMime = $magic->getMimeTypeFromExtensionOrNull( $djvuOutputExtension );
297 }
298
299 return [ $djvuOutputExtension, $djvuMime ];
300 }
301
303 public function getSizeAndMetadata( $state, $path ) {
304 wfDebug( "Getting DjVu metadata for $path" );
305
306 $djvuImage = $this->getDjVuImage( $state, $path );
307 $metadata = $djvuImage->retrieveMetaData();
308 if ( $metadata === false ) {
309 // Special value so that we don't repetitively try and decode a broken file.
310 $metadata = [ 'error' => 'Error extracting metadata' ];
311 }
312 return [ 'metadata' => $metadata ] + $djvuImage->getImageSize();
313 }
314
316 public function getMetadataType( $image ) {
317 // historical reasons
318 return 'djvuxml';
319 }
320
322 public function isFileMetadataValid( $image ) {
323 return $image->getMetadataArray() ? self::METADATA_GOOD : self::METADATA_BAD;
324 }
325
327 public function pageCount( File $image ) {
328 $info = $this->getDimensionInfo( $image );
329
330 return $info ? $info['pageCount'] : false;
331 }
332
334 public function getPageDimensions( File $image, $page ) {
335 $index = $page - 1; // MW starts pages at 1
336
337 $info = $this->getDimensionInfo( $image );
338 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
339 return $info['dimensionsByPage'][$index];
340 }
341
342 return false;
343 }
344
346 protected function getDimensionInfo( File $file ) {
347 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
348 return $cache->getWithSetCallback(
349 $cache->makeKey( 'file-djvu', 'dimensions', self::CACHE_VERSION, $file->getSha1() ),
350 $cache::TTL_INDEFINITE,
351 function () use ( $file ) {
352 $tree = $this->getMetaTree( $file );
353 return $this->getDimensionInfoFromMetaTree( $tree );
354 },
355 [ 'pcTTL' => $cache::TTL_INDEFINITE ]
356 );
357 }
358
364 protected function getDimensionInfoFromMetaTree( $metatree ) {
365 if ( !$metatree ) {
366 return false;
367 }
368 $dimsByPage = [];
369
370 if ( !isset( $metatree['data'] ) || !$metatree['data'] ) {
371 return false;
372 }
373 foreach ( $metatree['data']['pages'] as $page ) {
374 if ( !$page ) {
375 $dimsByPage[] = false;
376 } else {
377 $dimsByPage[] = [
378 'width' => (int)$page['width'],
379 'height' => (int)$page['height'],
380 ];
381 }
382 }
383 return [
384 'pageCount' => count( $metatree['data']['pages'] ),
385 'dimensionsByPage' => $dimsByPage
386 ];
387 }
388
394 public function getPageText( File $image, $page ) {
395 $tree = $this->getMetaTree( $image, true );
396 if ( !$tree ) {
397 return false;
398 }
399 if ( isset( $tree['text'] ) && isset( $tree['text'][$page - 1] ) ) {
400 return $tree['text'][$page - 1];
401 }
402 return false;
403 }
404
406 public function useSplitMetadata() {
407 return true;
408 }
409}
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...
wfHostname()
Get host name of the current machine, for use in error reporting.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Handler for DjVu images.
getDimensionInfoFromMetaTree( $metatree)
Given the metadata, returns dimension information about the document.
makeParamString( $params)
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
validateParam( $name, $value)
isMultiPage( $file)
getDimensionInfo(File $file)
getScriptParams( $params)
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
pageCount(File $image)
Page count for a multi-page document, false if unsupported or unknown.to overrideint|false
getPageText(File $image, $page)
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.If it returns MediaHandler::METADATA_BAD (or false),...
getSizeAndMetadata( $state, $path)
Get image size information and metadata array.If this returns null, the caller will fall back to getI...
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.to overrideThis method is currentl...
getMetaTree( $image, $gettext=false)
Cache a document tree for the DjVu metadata.
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.to overridearray Thumbnail ext...
useSplitMetadata()
If this returns true, LocalFile may split metadata up and store its constituent items separately....
mustRender( $file)
parseParamString( $str)
Support for detecting/validating DjVu image files and getting some basic file metadata (resolution et...
Definition DjVuImage.php:27
Media handler abstract base class for images.
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.Should be idempotent....
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
const METADATA_GOOD
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Basic media transform error class.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
Definition File.php:802
getSha1()
Get the SHA-1 base 36 hash of the file.
Definition File.php:2397
getSize()
Return the size of the image file, in bytes Overridden by LocalFile, UnregisteredLocalFile STUB.
Definition File.php:853
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Convenience class for dealing with PoolCounter using callbacks.
execute( $skipcache=false)
Get the result of the work (whatever it is), or the result of the error() function.
Executes shell commands.
Definition Shell.php:32
Media transform output for images.
Shortcut class for parameter validation errors.