MediaWiki  master
DjVuHandler.php
Go to the documentation of this file.
1 <?php
25 
31 class DjVuHandler extends ImageHandler {
32  private const EXPENSIVE_SIZE_LIMIT = 10485760; // 10MiB
33 
34  // Constants for getHandlerState
35  private const STATE_DJVU_IMAGE = 'djvuImage';
36  private const STATE_TEXT_TREE = 'djvuTextTree';
37  private const STATE_META_TREE = 'djvuMetaTree';
38 
42  public function isEnabled() {
44  if ( !$wgDjvuRenderer || !$wgDjvuDump ) {
45  wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump" );
46 
47  return false;
48  } else {
49  return true;
50  }
51  }
52 
57  public function mustRender( $file ) {
58  return true;
59  }
60 
66  public function isExpensiveToThumbnail( $file ) {
67  return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
68  }
69 
74  public function isMultiPage( $file ) {
75  return true;
76  }
77 
81  public function getParamMap() {
82  return [
83  'img_width' => 'width',
84  'img_page' => 'page',
85  ];
86  }
87 
93  public function validateParam( $name, $value ) {
94  if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
95  // Extra junk on the end of page, probably actually a caption
96  // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
97  return false;
98  }
99  return in_array( $name, [ 'width', 'height', 'page' ] ) && $value > 0;
100  }
101 
106  public function makeParamString( $params ) {
107  $page = $params['page'] ?? 1;
108  if ( !isset( $params['width'] ) ) {
109  return false;
110  }
111 
112  return "page{$page}-{$params['width']}px";
113  }
114 
119  public function parseParamString( $str ) {
120  $m = false;
121  if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
122  return [ 'width' => $m[2], 'page' => $m[1] ];
123  } else {
124  return false;
125  }
126  }
127 
132  protected function getScriptParams( $params ) {
133  return [
134  'width' => $params['width'],
135  'page' => $params['page'],
136  ];
137  }
138 
147  public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
149 
150  if ( !$this->normaliseParams( $image, $params ) ) {
151  return new TransformParameterError( $params );
152  }
153  $width = $params['width'];
154  $height = $params['height'];
155  $page = $params['page'];
156 
157  if ( $flags & self::TRANSFORM_LATER ) {
158  $params = [
159  'width' => $width,
160  'height' => $height,
161  'page' => $page
162  ];
163 
164  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
165  }
166 
167  if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
168  return new MediaTransformError(
169  'thumbnail_error',
170  $width,
171  $height,
172  wfMessage( 'thumbnail_dest_directory' )
173  );
174  }
175 
176  // Get local copy source for shell scripts
177  // Thumbnail extraction is very inefficient for large files.
178  // Provide a way to pool count limit the number of downloaders.
179  if ( $image->getSize() >= 1e7 ) { // 10 MB
180  $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
181  [
182  'doWork' => static function () use ( $image ) {
183  return $image->getLocalRefPath();
184  }
185  ]
186  );
187  $srcPath = $work->execute();
188  } else {
189  $srcPath = $image->getLocalRefPath();
190  }
191 
192  if ( $srcPath === false ) { // Failed to get local copy
193  wfDebugLog( 'thumbnail',
194  sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
195  wfHostname(), $image->getName() ) );
196 
197  return new MediaTransformError( 'thumbnail_error',
198  $params['width'], $params['height'],
199  wfMessage( 'filemissing' )
200  );
201  }
202 
203  # Use a subshell (brackets) to aggregate stderr from both pipeline commands
204  # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
205  $cmd = '(' . Shell::escape(
207  "-format=ppm",
208  "-page={$page}",
209  "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
210  $srcPath );
211  if ( $wgDjvuPostProcessor ) {
212  $cmd .= " | {$wgDjvuPostProcessor}";
213  }
214  $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
215  wfDebug( __METHOD__ . ": $cmd" );
216  $retval = '';
217  $err = wfShellExec( $cmd, $retval );
218 
219  $removed = $this->removeBadFile( $dstPath, $retval );
220  if ( $retval != 0 || $removed ) {
221  $this->logErrorForExternalProcess( $retval, $err, $cmd );
222  return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
223  } else {
224  $params = [
225  'width' => $width,
226  'height' => $height,
227  'page' => $page
228  ];
229 
230  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
231  }
232  }
233 
242  private function getDjVuImage( $state, $path ) {
243  $deja = $state->getHandlerState( self::STATE_DJVU_IMAGE );
244  if ( !$deja ) {
245  $deja = new DjVuImage( $path );
246  $state->setHandlerState( self::STATE_DJVU_IMAGE, $deja );
247  }
248  return $deja;
249  }
250 
258  private function getXMLMetadata( File $file ) {
259  $unser = $file->getMetadataArray();
260  if ( isset( $unser['error'] ) ) {
261  return false;
262  } elseif ( isset( $unser['xml'] ) ) {
263  return $unser['xml'];
264  } elseif ( isset( $unser['_error'] )
265  && is_string( $unser['_error'] )
266  && substr( $unser['_error'], 0, 3 ) === '<?xml'
267  ) {
268  // Old style. Not serialized but instead just a raw string of XML.
269  return $unser['_error'];
270  } else {
271  return false;
272  }
273  }
274 
281  public function getMetaTree( $image, $gettext = false ) {
282  if ( $gettext && $image->getHandlerState( self::STATE_TEXT_TREE ) ) {
283  return $image->getHandlerState( self::STATE_TEXT_TREE );
284  }
285  if ( !$gettext && $image->getHandlerState( self::STATE_META_TREE ) ) {
286  return $image->getHandlerState( self::STATE_META_TREE );
287  }
288 
289  $xml = $this->getXMLMetadata( $image );
290  if ( !$xml ) {
291  wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow" );
292 
293  return false;
294  }
295 
296  $trees = $this->extractTreesFromXML( $xml );
297  $image->setHandlerState( self::STATE_TEXT_TREE, $trees['TextTree'] );
298  $image->setHandlerState( self::STATE_META_TREE, $trees['MetaTree'] );
299 
300  if ( $gettext ) {
301  return $trees['TextTree'];
302  } else {
303  return $trees['MetaTree'];
304  }
305  }
306 
312  protected function extractTreesFromXML( $xml ) {
313  Wikimedia\suppressWarnings();
314  try {
315  // Set to false rather than null to avoid further attempts
316  $metaTree = false;
317  $textTree = false;
318  $tree = new SimpleXMLElement( $xml, LIBXML_PARSEHUGE );
319  if ( $tree->getName() == 'mw-djvu' ) {
321  foreach ( $tree->children() as $b ) {
322  if ( $b->getName() == 'DjVuTxt' ) {
323  // @todo File::djvuTextTree and File::dejaMetaTree are declared
324  // dynamically. Add a public File::$data to facilitate this?
325  $textTree = $b;
326  } elseif ( $b->getName() == 'DjVuXML' ) {
327  $metaTree = $b;
328  }
329  }
330  } else {
331  $metaTree = $tree;
332  }
333  } catch ( Exception $e ) {
334  wfDebug( "Bogus multipage XML metadata" );
335  }
336  Wikimedia\restoreWarnings();
337 
338  return [ 'MetaTree' => $metaTree, 'TextTree' => $textTree ];
339  }
340 
341  public function getThumbType( $ext, $mime, $params = null ) {
342  global $wgDjvuOutputExtension;
343  static $mime;
344  if ( !isset( $mime ) ) {
345  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
346  $mime = $magic->getMimeTypeFromExtensionOrNull( $wgDjvuOutputExtension );
347  }
348 
349  return [ $wgDjvuOutputExtension, $mime ];
350  }
351 
352  public function getSizeAndMetadata( $state, $path ) {
353  wfDebug( "Getting DjVu metadata for $path" );
354 
355  $djvuImage = $this->getDjVuImage( $state, $path );
356  $xml = $djvuImage->retrieveMetaData();
357  if ( $xml === false ) {
358  // Special value so that we don't repetitively try and decode a broken file.
359  $metadata = [ 'error' => 'Error extracting metadata' ];
360  } else {
361  $metadata = [ 'xml' => $xml ];
362  }
363  return [ 'metadata' => $metadata ] + $djvuImage->getImageSize();
364  }
365 
366  public function getMetadataType( $image ) {
367  return 'djvuxml';
368  }
369 
370  public function isFileMetadataValid( $image ) {
371  return $image->getMetadataArray() ? self::METADATA_GOOD : self::METADATA_BAD;
372  }
373 
374  public function pageCount( File $image ) {
375  $info = $this->getDimensionInfo( $image );
376 
377  return $info ? $info['pageCount'] : false;
378  }
379 
380  public function getPageDimensions( File $image, $page ) {
381  $index = $page - 1; // MW starts pages at 1
382 
383  $info = $this->getDimensionInfo( $image );
384  if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
385  return $info['dimensionsByPage'][$index];
386  }
387 
388  return false;
389  }
390 
391  protected function getDimensionInfo( File $file ) {
392  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
393  return $cache->getWithSetCallback(
394  $cache->makeKey( 'file-djvu', 'dimensions', $file->getSha1() ),
395  $cache::TTL_INDEFINITE,
396  function () use ( $file ) {
397  $tree = $this->getMetaTree( $file );
398  return $this->getDimensionInfoFromMetaTree( $tree );
399  },
400  [ 'pcTTL' => $cache::TTL_INDEFINITE ]
401  );
402  }
403 
409  protected function getDimensionInfoFromMetaTree( $metatree ) {
410  if ( !$metatree ) {
411  return false;
412  }
413 
414  $dimsByPage = [];
415  $count = count( $metatree->xpath( '//OBJECT' ) );
416  for ( $i = 0; $i < $count; $i++ ) {
417  $o = $metatree->BODY[0]->OBJECT[$i];
418  if ( $o ) {
419  $dimsByPage[$i] = [
420  'width' => (int)$o['width'],
421  'height' => (int)$o['height'],
422  ];
423  } else {
424  $dimsByPage[$i] = false;
425  }
426  }
427 
428  return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
429  }
430 
436  public function getPageText( File $image, $page ) {
437  $tree = $this->getMetaTree( $image, true );
438  if ( !$tree ) {
439  return false;
440  }
441 
442  $o = $tree->BODY[0]->PAGE[$page - 1];
443  return $o ? (string)$o['value'] : false;
444  }
445 }
MediaHandler\removeBadFile
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Definition: MediaHandler.php:924
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
MediaTransformError
Basic media transform error class.
Definition: MediaTransformError.php:31
ThumbnailImage
Media transform output for images.
Definition: ThumbnailImage.php:29
DjVuHandler\getParamMap
getParamMap()
Definition: DjVuHandler.php:81
DjVuHandler\getDimensionInfoFromMetaTree
getDimensionInfoFromMetaTree( $metatree)
Given an XML metadata tree, returns dimension information about the document.
Definition: DjVuHandler.php:409
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:1750
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
DjVuHandler\isMultiPage
isMultiPage( $file)
Definition: DjVuHandler.php:74
DjVuHandler\parseParamString
parseParamString( $str)
Definition: DjVuHandler.php:119
$wgDjvuPostProcessor
$wgDjvuPostProcessor
Shell command for the DJVU post processor Default: pnmtojpeg, since ddjvu generates ppm output Set th...
Definition: DefaultSettings.php:1805
DjVuHandler\pageCount
pageCount(File $image)
Page count for a multi-page document, false if unsupported or unknown.
Definition: DjVuHandler.php:374
DjVuHandler\isEnabled
isEnabled()
Definition: DjVuHandler.php:42
DjVuImage
Support for detecting/validating DjVu image files and getting some basic file metadata (resolution et...
Definition: DjVuImage.php:38
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1249
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1186
PoolCounterWorkViaCallback
Convenience class for dealing with PoolCounters using callbacks.
Definition: PoolCounterWorkViaCallback.php:31
DjVuHandler\makeParamString
makeParamString( $params)
Definition: DjVuHandler.php:106
$wgDjvuRenderer
$wgDjvuRenderer
Path of the ddjvu DJVU renderer Enable this and $wgDjvuDump to enable djvu rendering example: $wgDjvu...
Definition: DefaultSettings.php:1791
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:958
DjVuHandler\EXPENSIVE_SIZE_LIMIT
const EXPENSIVE_SIZE_LIMIT
Definition: DjVuHandler.php:32
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:254
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:66
DjVuHandler\STATE_DJVU_IMAGE
const STATE_DJVU_IMAGE
Definition: DjVuHandler.php:35
PoolCounterWork\execute
execute( $skipcache=false)
Get the result of the work (whatever it is), or the result of the error() function.
Definition: PoolCounterWork.php:127
DjVuHandler\getDjVuImage
getDjVuImage( $state, $path)
Cache an instance of DjVuImage in a MediaHandlerState object, return that instance.
Definition: DjVuHandler.php:242
DjVuHandler\isFileMetadataValid
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: DjVuHandler.php:370
DjVuHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: DjVuHandler.php:380
ImageHandler
Media handler abstract base class for images.
Definition: ImageHandler.php:31
DjVuHandler\isExpensiveToThumbnail
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
Definition: DjVuHandler.php:66
DjVuHandler\validateParam
validateParam( $name, $value)
Definition: DjVuHandler.php:93
$wgDjvuOutputExtension
$wgDjvuOutputExtension
File extension for the DJVU post processor output.
Definition: DefaultSettings.php:1810
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
ImageHandler\normaliseParams
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.Should be idempotent....
Definition: ImageHandler.php:105
DjVuHandler\STATE_META_TREE
const STATE_META_TREE
Definition: DjVuHandler.php:37
TransformParameterError
Shortcut class for parameter validation errors.
Definition: TransformParameterError.php:30
DjVuHandler\getMetadataType
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: DjVuHandler.php:366
DjVuHandler\getScriptParams
getScriptParams( $params)
Definition: DjVuHandler.php:132
DjVuHandler\getSizeAndMetadata
getSizeAndMetadata( $state, $path)
Get image size information and metadata array.
Definition: DjVuHandler.php:352
DjVuHandler
Handler for DjVu images.
Definition: DjVuHandler.php:31
DjVuHandler\getXMLMetadata
getXMLMetadata(File $file)
Get metadata, unserializing it if necessary.
Definition: DjVuHandler.php:258
$cache
$cache
Definition: mcc.php:33
DjVuHandler\getThumbType
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: DjVuHandler.php:341
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:1007
DjVuHandler\doTransform
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Definition: DjVuHandler.php:147
$path
$path
Definition: NoLocalSettings.php:25
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:40
DjVuHandler\getMetaTree
getMetaTree( $image, $gettext=false)
Cache a document tree for the DjVu XML metadata.
Definition: DjVuHandler.php:281
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
$wgDjvuDump
$wgDjvuDump
Path of the djvudump executable Enable this and $wgDjvuRenderer to enable djvu rendering example: $wg...
Definition: DefaultSettings.php:1784
DjVuHandler\STATE_TEXT_TREE
const STATE_TEXT_TREE
Definition: DjVuHandler.php:36
$mime
$mime
Definition: router.php:60
DjVuHandler\getPageText
getPageText(File $image, $page)
Definition: DjVuHandler.php:436
DjVuHandler\mustRender
mustRender( $file)
Definition: DjVuHandler.php:57
DjVuHandler\getDimensionInfo
getDimensionInfo(File $file)
Definition: DjVuHandler.php:391
DjVuHandler\extractTreesFromXML
extractTreesFromXML( $xml)
Extracts metadata and text trees from metadata XML in string form.
Definition: DjVuHandler.php:312
MediaHandler\METADATA_GOOD
const METADATA_GOOD
Definition: MediaHandler.php:39
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:1912