MediaWiki 1.42.0
DjVuHandler.php
Go to the documentation of this file.
1<?php
28
35 private const EXPENSIVE_SIZE_LIMIT = 10_485_760; // 10MiB
36
37 // Constants for getHandlerState
38 private const STATE_DJVU_IMAGE = 'djvuImage';
39 private const STATE_TEXT_TREE = 'djvuTextTree';
40 private const STATE_META_TREE = 'djvuMetaTree';
41 private const CACHE_VERSION = 'v2';
42
46 public function isEnabled() {
47 $djvuRenderer = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuRenderer );
48 $djvuDump = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuDump );
49 if ( !$djvuRenderer || !$djvuDump ) {
50 wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump" );
51
52 return false;
53 }
54 return true;
55 }
56
61 public function mustRender( $file ) {
62 return true;
63 }
64
70 public function isExpensiveToThumbnail( $file ) {
71 return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
72 }
73
78 public function isMultiPage( $file ) {
79 return true;
80 }
81
85 public function getParamMap() {
86 return [
87 'img_width' => 'width',
88 'img_page' => 'page',
89 ];
90 }
91
97 public function validateParam( $name, $value ) {
98 if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
99 // Extra junk on the end of page, probably actually a caption
100 // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
101 return false;
102 }
103 return in_array( $name, [ 'width', 'height', 'page' ] ) && $value > 0;
104 }
105
110 public function makeParamString( $params ) {
111 $page = $params['page'] ?? 1;
112 if ( !isset( $params['width'] ) ) {
113 return false;
114 }
115
116 return "page{$page}-{$params['width']}px";
117 }
118
123 public function parseParamString( $str ) {
124 $m = false;
125 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
126 return [ 'width' => $m[2], 'page' => $m[1] ];
127 }
128 return false;
129 }
130
135 protected function getScriptParams( $params ) {
136 return [
137 'width' => $params['width'],
138 'page' => $params['page'],
139 ];
140 }
141
150 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
151 $djvuRenderer = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuRenderer );
152 $djvuPostProcessor = MediaWikiServices::getInstance()->getMainConfig()
153 ->get( MainConfigNames::DjvuPostProcessor );
154 if ( !$this->normaliseParams( $image, $params ) ) {
155 return new TransformParameterError( $params );
156 }
157 $width = $params['width'];
158 $height = $params['height'];
159 $page = $params['page'];
160
161 if ( $flags & self::TRANSFORM_LATER ) {
162 $params = [
163 'width' => $width,
164 'height' => $height,
165 'page' => $page
166 ];
167
168 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
169 }
170
171 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
172 return new MediaTransformError(
173 'thumbnail_error',
174 $width,
175 $height,
176 wfMessage( 'thumbnail_dest_directory' )
177 );
178 }
179
180 // Get local copy source for shell scripts
181 // Thumbnail extraction is very inefficient for large files.
182 // Provide a way to pool count limit the number of downloaders.
183 if ( $image->getSize() >= 1e7 ) { // 10 MB
184 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
185 [
186 'doWork' => static function () use ( $image ) {
187 return $image->getLocalRefPath();
188 }
189 ]
190 );
191 $srcPath = $work->execute();
192 } else {
193 $srcPath = $image->getLocalRefPath();
194 }
195
196 if ( $srcPath === false ) { // Failed to get local copy
197 wfDebugLog( 'thumbnail',
198 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
199 wfHostname(), $image->getName() ) );
200
201 return new MediaTransformError( 'thumbnail_error',
202 $params['width'], $params['height'],
203 wfMessage( 'filemissing' )
204 );
205 }
206
207 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
208 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
209 $cmd = '(' . Shell::escape(
210 $djvuRenderer,
211 "-format=ppm",
212 "-page={$page}",
213 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
214 $srcPath );
215 if ( $djvuPostProcessor ) {
216 $cmd .= " | {$djvuPostProcessor}";
217 }
218 $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
219 wfDebug( __METHOD__ . ": $cmd" );
220 $retval = 0;
221 $err = wfShellExec( $cmd, $retval );
222
223 $removed = $this->removeBadFile( $dstPath, $retval );
224 if ( $retval !== 0 || $removed ) {
225 $this->logErrorForExternalProcess( $retval, $err, $cmd );
226 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
227 }
228 $params = [
229 'width' => $width,
230 'height' => $height,
231 'page' => $page
232 ];
233
234 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
235 }
236
245 private function getDjVuImage( $state, $path ) {
246 $deja = $state->getHandlerState( self::STATE_DJVU_IMAGE );
247 if ( !$deja ) {
248 $deja = new DjVuImage( $path );
249 $state->setHandlerState( self::STATE_DJVU_IMAGE, $deja );
250 }
251 return $deja;
252 }
253
261 private function getMetadataInternal( File $file, $gettext ) {
262 $itemNames = [ 'error', '_error', 'data' ];
263 if ( $gettext ) {
264 $itemNames[] = 'text';
265 }
266 $unser = $file->getMetadataItems( $itemNames );
267
268 if ( isset( $unser['error'] ) ) {
269 return false;
270 }
271 if ( isset( $unser['_error'] ) ) {
272 return false;
273 }
274 return $unser;
275 }
276
283 public function getMetaTree( $image, $gettext = false ) {
284 if ( $gettext && $image->getHandlerState( self::STATE_TEXT_TREE ) ) {
285 return $image->getHandlerState( self::STATE_TEXT_TREE );
286 }
287 if ( !$gettext && $image->getHandlerState( self::STATE_META_TREE ) ) {
288 return $image->getHandlerState( self::STATE_META_TREE );
289 }
290
291 $metadata = $this->getMetadataInternal( $image, $gettext );
292 if ( !$metadata ) {
293 return false;
294 }
295
296 if ( !$gettext ) {
297 unset( $metadata['text'] );
298 }
299 return $metadata;
300 }
301
302 public function getThumbType( $ext, $mime, $params = null ) {
303 $djvuOutputExtension = MediaWikiServices::getInstance()->getMainConfig()
304 ->get( MainConfigNames::DjvuOutputExtension );
305 static $mime;
306 if ( !isset( $mime ) ) {
307 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
308 $mime = $magic->getMimeTypeFromExtensionOrNull( $djvuOutputExtension );
309 }
310
311 return [ $djvuOutputExtension, $mime ];
312 }
313
314 public function getSizeAndMetadata( $state, $path ) {
315 wfDebug( "Getting DjVu metadata for $path" );
316
317 $djvuImage = $this->getDjVuImage( $state, $path );
318 $metadata = $djvuImage->retrieveMetaData();
319 if ( $metadata === false ) {
320 // Special value so that we don't repetitively try and decode a broken file.
321 $metadata = [ 'error' => 'Error extracting metadata' ];
322 }
323 return [ 'metadata' => $metadata ] + $djvuImage->getImageSize();
324 }
325
326 public function getMetadataType( $image ) {
327 // historical reasons
328 return 'djvuxml';
329 }
330
331 public function isFileMetadataValid( $image ) {
332 return $image->getMetadataArray() ? self::METADATA_GOOD : self::METADATA_BAD;
333 }
334
335 public function pageCount( File $image ) {
336 $info = $this->getDimensionInfo( $image );
337
338 return $info ? $info['pageCount'] : false;
339 }
340
341 public function getPageDimensions( File $image, $page ) {
342 $index = $page - 1; // MW starts pages at 1
343
344 $info = $this->getDimensionInfo( $image );
345 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
346 return $info['dimensionsByPage'][$index];
347 }
348
349 return false;
350 }
351
352 protected function getDimensionInfo( File $file ) {
353 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
354 return $cache->getWithSetCallback(
355 $cache->makeKey( 'file-djvu', 'dimensions', self::CACHE_VERSION, $file->getSha1() ),
356 $cache::TTL_INDEFINITE,
357 function () use ( $file ) {
358 $tree = $this->getMetaTree( $file );
359 return $this->getDimensionInfoFromMetaTree( $tree );
360 },
361 [ 'pcTTL' => $cache::TTL_INDEFINITE ]
362 );
363 }
364
370 protected function getDimensionInfoFromMetaTree( $metatree ) {
371 if ( !$metatree ) {
372 return false;
373 }
374 $dimsByPage = [];
375
376 if ( !isset( $metatree['data'] ) || !$metatree['data'] ) {
377 return false;
378 }
379 foreach ( $metatree['data']['pages'] as $page ) {
380 if ( !$page ) {
381 $dimsByPage[] = false;
382 } else {
383 $dimsByPage[] = [
384 'width' => (int)$page['width'],
385 'height' => (int)$page['height'],
386 ];
387 }
388 }
389 return [
390 'pageCount' => count( $metatree['data']['pages'] ),
391 'dimensionsByPage' => $dimsByPage
392 ];
393 }
394
400 public function getPageText( File $image, $page ) {
401 $tree = $this->getMetaTree( $image, true );
402 if ( !$tree ) {
403 return false;
404 }
405 if ( isset( $tree['text'] ) && isset( $tree['text'][$page - 1] ) ) {
406 return $tree['text'][$page - 1];
407 }
408 return false;
409 }
410
411 public function useSplitMetadata() {
412 return true;
413 }
414}
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.
array $params
The job parameters.
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.
getPageText(File $image, $page)
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
getSizeAndMetadata( $state, $path)
Get image size information and metadata array.
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.
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.
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:41
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:73
getSize()
Return the size of the image file, in bytes Overridden by LocalFile, UnregisteredLocalFile STUB.
Definition File.php:831
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
Definition File.php:780
getSha1()
Get the SHA-1 base 36 hash of the file.
Definition File.php:2331
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.
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:46
Media transform output for images.
Shortcut class for parameter validation errors.