3 * Handler for DjVu images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
26 * Handler for DjVu images
30 class DjVuHandler
extends ImageHandler
{
31 const EXPENSIVE_SIZE_LIMIT
= 10485760; // 10MiB
36 public function isEnabled() {
37 global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML;
38 if ( !$wgDjvuRenderer ||
( !$wgDjvuDump && !$wgDjvuToXML ) ) {
39 wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump\n" );
51 public function mustRender( $file ) {
56 * True if creating thumbnails from the file is large or otherwise resource-intensive.
60 public function isExpensiveToThumbnail( $file ) {
61 return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT
;
68 public function isMultiPage( $file ) {
75 public function getParamMap() {
77 'img_width' => 'width',
87 public function validateParam( $name, $value ) {
88 if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
89 // Extra junk on the end of page, probably actually a caption
90 // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
93 if ( in_array( $name, [ 'width', 'height', 'page' ] ) ) {
105 * @param array $params
106 * @return bool|string
108 public function makeParamString( $params ) {
109 $page = $params['page'] ??
1;
110 if ( !isset( $params['width'] ) ) {
114 return "page{$page}-{$params['width']}px";
121 public function parseParamString( $str ) {
123 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
124 return [ 'width' => $m[2], 'page' => $m[1] ];
131 * @param array $params
134 protected function getScriptParams( $params ) {
136 'width' => $params['width'],
137 'page' => $params['page'],
143 * @param string $dstPath
144 * @param string $dstUrl
145 * @param array $params
147 * @return MediaTransformError|ThumbnailImage|TransformParameterError
149 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
150 global $wgDjvuRenderer, $wgDjvuPostProcessor;
152 if ( !$this->normaliseParams( $image, $params ) ) {
153 return new TransformParameterError( $params );
155 $width = $params['width'];
156 $height = $params['height'];
157 $page = $params['page'];
159 if ( $flags & self
::TRANSFORM_LATER
) {
166 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
169 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
170 return new MediaTransformError(
174 wfMessage( 'thumbnail_dest_directory' )
178 // Get local copy source for shell scripts
179 // Thumbnail extraction is very inefficient for large files.
180 // Provide a way to pool count limit the number of downloaders.
181 if ( $image->getSize() >= 1e7
) { // 10MB
182 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
184 'doWork' => function () use ( $image ) {
185 return $image->getLocalRefPath();
189 $srcPath = $work->execute();
191 $srcPath = $image->getLocalRefPath();
194 if ( $srcPath === false ) { // Failed to get local copy
195 wfDebugLog( 'thumbnail',
196 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
197 wfHostname(), $image->getName() ) );
199 return new MediaTransformError( 'thumbnail_error',
200 $params['width'], $params['height'],
201 wfMessage( 'filemissing' )
205 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
206 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
207 $cmd = '(' . wfEscapeShellArg(
211 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
213 if ( $wgDjvuPostProcessor ) {
214 $cmd .= " | {$wgDjvuPostProcessor}";
216 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
217 wfDebug( __METHOD__
. ": $cmd\n" );
219 $err = wfShellExec( $cmd, $retval );
221 $removed = $this->removeBadFile( $dstPath, $retval );
222 if ( $retval != 0 ||
$removed ) {
223 $this->logErrorForExternalProcess( $retval, $err, $cmd );
224 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
232 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
237 * Cache an instance of DjVuImage in an Image object, return that instance
239 * @param File|FSFile $image
240 * @param string $path
243 function getDjVuImage( $image, $path ) {
245 $deja = new DjVuImage( $path );
246 } elseif ( !isset( $image->dejaImage
) ) {
247 $deja = $image->dejaImage
= new DjVuImage( $path );
249 $deja = $image->dejaImage
;
256 * Get metadata, unserializing it if necessary.
258 * @param File $file The DjVu file in question
259 * @return string XML metadata as a string.
260 * @throws MWException
262 private function getUnserializedMetadata( File
$file ) {
263 $metadata = $file->getMetadata();
264 if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
265 // Old style. Not serialized but instead just a raw string of XML.
269 Wikimedia\
suppressWarnings();
270 $unser = unserialize( $metadata );
271 Wikimedia\restoreWarnings
();
272 if ( is_array( $unser ) ) {
273 if ( isset( $unser['error'] ) ) {
275 } elseif ( isset( $unser['xml'] ) ) {
276 return $unser['xml'];
278 // Should never ever reach here.
279 throw new MWException( "Error unserializing DjVu metadata." );
283 // unserialize failed. Guess it wasn't really serialized after all,
288 * Cache a document tree for the DjVu XML metadata
290 * @param bool $gettext DOCUMENT (Default: false)
291 * @return bool|SimpleXMLElement
293 public function getMetaTree( $image, $gettext = false ) {
294 if ( $gettext && isset( $image->djvuTextTree
) ) {
295 return $image->djvuTextTree
;
297 if ( !$gettext && isset( $image->dejaMetaTree
) ) {
298 return $image->dejaMetaTree
;
301 $metadata = $this->getUnserializedMetadata( $image );
302 if ( !$this->isMetadataValid( $image, $metadata ) ) {
303 wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
308 $trees = $this->extractTreesFromMetadata( $metadata );
309 $image->djvuTextTree
= $trees['TextTree'];
310 $image->dejaMetaTree
= $trees['MetaTree'];
313 return $image->djvuTextTree
;
315 return $image->dejaMetaTree
;
320 * Extracts metadata and text trees from metadata XML in string form
321 * @param string $metadata XML metadata as a string
324 protected function extractTreesFromMetadata( $metadata ) {
325 Wikimedia\
suppressWarnings();
327 // Set to false rather than null to avoid further attempts
330 $tree = new SimpleXMLElement( $metadata, LIBXML_PARSEHUGE
);
331 if ( $tree->getName() == 'mw-djvu' ) {
332 /** @var SimpleXMLElement $b */
333 foreach ( $tree->children() as $b ) {
334 if ( $b->getName() == 'DjVuTxt' ) {
335 // @todo File::djvuTextTree and File::dejaMetaTree are declared
336 // dynamically. Add a public File::$data to facilitate this?
338 } elseif ( $b->getName() == 'DjVuXML' ) {
345 } catch ( Exception
$e ) {
346 wfDebug( "Bogus multipage XML metadata\n" );
348 Wikimedia\restoreWarnings
();
350 return [ 'MetaTree' => $metaTree, 'TextTree' => $textTree ];
353 function getImageSize( $image, $path ) {
354 return $this->getDjVuImage( $image, $path )->getImageSize();
357 public function getThumbType( $ext, $mime, $params = null ) {
358 global $wgDjvuOutputExtension;
360 if ( !isset( $mime ) ) {
361 $magic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
362 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
365 return [ $wgDjvuOutputExtension, $mime ];
368 public function getMetadata( $image, $path ) {
369 wfDebug( "Getting DjVu metadata for $path\n" );
371 $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
372 if ( $xml === false ) {
373 // Special value so that we don't repetitively try and decode a broken file.
374 return serialize( [ 'error' => 'Error extracting metadata' ] );
376 return serialize( [ 'xml' => $xml ] );
380 function getMetadataType( $image ) {
384 public function isMetadataValid( $image, $metadata ) {
385 return !empty( $metadata ) && $metadata != serialize( [] );
388 public function pageCount( File
$image ) {
389 $info = $this->getDimensionInfo( $image );
391 return $info ?
$info['pageCount'] : false;
394 public function getPageDimensions( File
$image, $page ) {
395 $index = $page - 1; // MW starts pages at 1
397 $info = $this->getDimensionInfo( $image );
398 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
399 return $info['dimensionsByPage'][$index];
405 protected function getDimensionInfo( File
$file ) {
406 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
407 return $cache->getWithSetCallback(
408 $cache->makeKey( 'file-djvu', 'dimensions', $file->getSha1() ),
409 $cache::TTL_INDEFINITE
,
410 function () use ( $file ) {
411 $tree = $this->getMetaTree( $file );
412 return $this->getDimensionInfoFromMetaTree( $tree );
414 [ 'pcTTL' => $cache::TTL_INDEFINITE
]
419 * Given an XML metadata tree, returns dimension information about the document
420 * @param bool|SimpleXMLElement $metatree The file's XML metadata tree
423 protected function getDimensionInfoFromMetaTree( $metatree ) {
429 $count = count( $metatree->xpath( '//OBJECT' ) );
430 for ( $i = 0; $i < $count; $i++
) {
431 $o = $metatree->BODY
[0]->OBJECT[$i];
434 'width' => (int)$o['width'],
435 'height' => (int)$o['height'],
438 $dimsByPage[$i] = false;
442 return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
447 * @param int $page Page number to get information for
448 * @return bool|string Page text or false when no text found.
450 function getPageText( File
$image, $page ) {
451 $tree = $this->getMetaTree( $image, true );
456 $o = $tree->BODY
[0]->PAGE
[$page - 1];