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
25 * Handler for DjVu images
29 class DjVuHandler
extends ImageHandler
{
33 function isEnabled() {
34 global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML;
35 if ( !$wgDjvuRenderer ||
( !$wgDjvuDump && !$wgDjvuToXML ) ) {
36 wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump\n" );
48 function mustRender( $file ) {
56 function isMultiPage( $file ) {
63 function getParamMap() {
65 'img_width' => 'width',
75 function validateParam( $name, $value ) {
76 if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
77 // Extra junk on the end of page, probably actually a caption
78 // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
81 if ( in_array( $name, array( 'width', 'height', 'page' ) ) ) {
93 * @param array $params
96 function makeParamString( $params ) {
97 $page = isset( $params['page'] ) ?
$params['page'] : 1;
98 if ( !isset( $params['width'] ) ) {
102 return "page{$page}-{$params['width']}px";
109 function parseParamString( $str ) {
111 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
112 return array( 'width' => $m[2], 'page' => $m[1] );
119 * @param array $params
122 function getScriptParams( $params ) {
124 'width' => $params['width'],
125 'page' => $params['page'],
131 * @param string $dstPath
132 * @param string $dstUrl
133 * @param array $params
135 * @return MediaTransformError|ThumbnailImage|TransformParameterError
137 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
138 global $wgDjvuRenderer, $wgDjvuPostProcessor;
140 // Fetch XML and check it, to give a more informative error message than the one which
141 // normaliseParams will inevitably give.
142 $xml = $image->getMetadata();
144 $width = isset( $params['width'] ) ?
$params['width'] : 0;
145 $height = isset( $params['height'] ) ?
$params['height'] : 0;
147 return new MediaTransformError( 'thumbnail_error', $width, $height,
148 wfMessage( 'djvu_no_xml' )->text() );
151 if ( !$this->normaliseParams( $image, $params ) ) {
152 return new TransformParameterError( $params );
154 $width = $params['width'];
155 $height = $params['height'];
156 $page = $params['page'];
157 if ( $page > $this->pageCount( $image ) ) {
158 return new MediaTransformError(
162 wfMessage( 'djvu_page_error' )->text()
166 if ( $flags & self
::TRANSFORM_LATER
) {
173 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
176 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
177 return new MediaTransformError(
181 wfMessage( 'thumbnail_dest_directory' )->text()
185 // Get local copy source for shell scripts
186 // Thumbnail extraction is very inefficient for large files.
187 // Provide a way to pool count limit the number of downloaders.
188 if ( $image->getSize() >= 1e7
) { // 10MB
189 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
191 'doWork' => function () use ( $image ) {
192 return $image->getLocalRefPath();
196 $srcPath = $work->execute();
198 $srcPath = $image->getLocalRefPath();
201 if ( $srcPath === false ) { // Failed to get local copy
202 wfDebugLog( 'thumbnail',
203 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
204 wfHostname(), $image->getName() ) );
206 return new MediaTransformError( 'thumbnail_error',
207 $params['width'], $params['height'],
208 wfMessage( 'filemissing' )->text()
212 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
213 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
214 $cmd = '(' . wfEscapeShellArg(
218 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
220 if ( $wgDjvuPostProcessor ) {
221 $cmd .= " | {$wgDjvuPostProcessor}";
223 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
224 wfDebug( __METHOD__
. ": $cmd\n" );
226 $err = wfShellExec( $cmd, $retval );
228 $removed = $this->removeBadFile( $dstPath, $retval );
229 if ( $retval != 0 ||
$removed ) {
230 $this->logErrorForExternalProcess( $retval, $err, $cmd );
231 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
239 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
244 * Cache an instance of DjVuImage in an Image object, return that instance
247 * @param string $path
250 function getDjVuImage( $image, $path ) {
252 $deja = new DjVuImage( $path );
253 } elseif ( !isset( $image->dejaImage
) ) {
254 $deja = $image->dejaImage
= new DjVuImage( $path );
256 $deja = $image->dejaImage
;
263 * Get metadata, unserializing it if neccessary.
265 * @param File $file The DjVu file in question
266 * @return string XML metadata as a string.
267 * @throws MWException
269 private function getUnserializedMetadata( File
$file ) {
270 $metadata = $file->getMetadata();
271 if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
272 // Old style. Not serialized but instead just a raw string of XML.
276 wfSuppressWarnings();
277 $unser = unserialize( $metadata );
279 if ( is_array( $unser ) ) {
280 if ( isset( $unser['error'] ) ) {
282 } elseif ( isset( $unser['xml'] ) ) {
283 return $unser['xml'];
285 // Should never ever reach here.
286 throw new MWException( "Error unserializing DjVu metadata." );
290 // unserialize failed. Guess it wasn't really serialized after all,
295 * Cache a document tree for the DjVu XML metadata
297 * @param bool $gettext DOCUMENT (Default: false)
298 * @return bool|SimpleXMLElement
300 function getMetaTree( $image, $gettext = false ) {
301 if ( $gettext && isset( $image->djvuTextTree
) ) {
302 return $image->djvuTextTree
;
304 if ( !$gettext && isset( $image->dejaMetaTree
) ) {
305 return $image->dejaMetaTree
;
308 $metadata = $this->getUnserializedMetadata( $image );
309 if ( !$this->isMetadataValid( $image, $metadata ) ) {
310 wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
315 wfSuppressWarnings();
317 // Set to false rather than null to avoid further attempts
318 $image->dejaMetaTree
= false;
319 $image->djvuTextTree
= false;
320 $tree = new SimpleXMLElement( $metadata );
321 if ( $tree->getName() == 'mw-djvu' ) {
322 /** @var SimpleXMLElement $b */
323 foreach ( $tree->children() as $b ) {
324 if ( $b->getName() == 'DjVuTxt' ) {
325 // @todo File::djvuTextTree and File::dejaMetaTree are declared
326 // dynamically. Add a public File::$data to facilitate this?
327 $image->djvuTextTree
= $b;
328 } elseif ( $b->getName() == 'DjVuXML' ) {
329 $image->dejaMetaTree
= $b;
333 $image->dejaMetaTree
= $tree;
335 } catch ( Exception
$e ) {
336 wfDebug( "Bogus multipage XML metadata on '{$image->getName()}'\n" );
340 return $image->djvuTextTree
;
342 return $image->dejaMetaTree
;
348 * @param string $path
349 * @return bool|array False on failure
351 function getImageSize( $image, $path ) {
352 return $this->getDjVuImage( $image, $path )->getImageSize();
355 function getThumbType( $ext, $mime, $params = null ) {
356 global $wgDjvuOutputExtension;
358 if ( !isset( $mime ) ) {
359 $magic = MimeMagic
::singleton();
360 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
363 return array( $wgDjvuOutputExtension, $mime );
366 function getMetadata( $image, $path ) {
367 wfDebug( "Getting DjVu metadata for $path\n" );
369 $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
370 if ( $xml === false ) {
371 // Special value so that we don't repetitively try and decode a broken file.
372 return serialize( array( 'error' => 'Error extracting metadata' ) );
374 return serialize( array( 'xml' => $xml ) );
378 function getMetadataType( $image ) {
382 function isMetadataValid( $image, $metadata ) {
383 return !empty( $metadata ) && $metadata != serialize( array() );
386 function pageCount( $image ) {
387 $tree = $this->getMetaTree( $image );
392 return count( $tree->xpath( '//OBJECT' ) );
395 function getPageDimensions( $image, $page ) {
396 $tree = $this->getMetaTree( $image );
401 $o = $tree->BODY
[0]->OBJECT[$page - 1];
404 'width' => intval( $o['width'] ),
405 'height' => intval( $o['height'] )
414 * @param int $page Page number to get information for
415 * @return bool|string Page text or false when no text found.
417 function getPageText( $image, $page ) {
418 $tree = $this->getMetaTree( $image, true );
423 $o = $tree->BODY
[0]->PAGE
[$page - 1];