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