Debian Codegraph @

includes/media/DjVuHandler.php

raw symbols SCIP
1 <?php
2 /**
3 * Handler for DjVu images.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 use MediaWiki\MainConfigNames;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\PoolCounter\PoolCounterWorkViaCallback;
27 use MediaWiki\Shell\Shell;
28
29 /**
30 * Handler for DjVu images
31 *
32 * @ingroup Media
33 */
34 class DjVuHandler extends ImageHandler {
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
43 /**
44 * @return bool
45 */
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
57 /**
58 * @param File $file
59 * @return bool
60 */
61 public function mustRender( $file ) {
62 return true;
63 }
64
65 /**
66 * True if creating thumbnails from the file is large or otherwise resource-intensive.
67 * @param File $file
68 * @return bool
69 */
70 public function isExpensiveToThumbnail( $file ) {
71 return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
72 }
73
74 /**
75 * @param File $file
76 * @return bool
77 */
78 public function isMultiPage( $file ) {
79 return true;
80 }
81
82 /**
83 * @return array
84 */
85 public function getParamMap() {
86 return [
87 'img_width' => 'width',
88 'img_page' => 'page',
89 ];
90 }
91
92 /**
93 * @param string $name
94 * @param mixed $value
95 * @return bool
96 */
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', 'physicalWidth', 'physicalHeight' ] ) && $value > 0;
104 }
105
106 /**
107 * @param array $params
108 * @return string|false
109 */
110 public function makeParamString( $params ) {
111 $page = $params['page'] ?? 1;
112 $width = $params['physicalWidth'] ?? $params['width'] ?? null;
113 if ( !$width ) {
114 return false;
115 }
116
117 return "page{$page}-{$width}px";
118 }
119
120 /**
121 * @param string $str
122 * @return array|false
123 */
124 public function parseParamString( $str ) {
125 $m = false;
126 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
127 return [ 'width' => $m[2], 'page' => $m[1] ];
128 }
129 return false;
130 }
131
132 /**
133 * @inheritDoc
134 */
135 public function normaliseParams( $image, &$params ) {
136 // Copy-paste from TransformationalImageHandler::normaliseParams() and PdfHandler
137 // Probably should be trait or subclass.
138 if ( !parent::normaliseParams( $image, $params ) ) {
139 return false;
140 }
141 $srcWidth = $image->getWidth( $params['page'] );
142 $srcHeight = $image->getHeight( $params['page'] );
143 $params['physicalWidth'] = $this->getSteppedThumbWidth(
144 $image, $params['physicalWidth'], $srcWidth, $srcHeight
145 );
146 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $params['physicalWidth'] );
147 return true;
148 }
149
150 /**
151 * @param array $params
152 * @return array
153 */
154 protected function getScriptParams( $params ) {
155 return [
156 'width' => $params['width'],
157 'page' => $params['page'],
158 ];
159 }
160
161 /**
162 * @param File $image
163 * @param string $dstPath
164 * @param string $dstUrl
165 * @param array $params
166 * @param int $flags
167 * @return MediaTransformError|ThumbnailImage|TransformParameterError
168 */
169 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
170 $djvuRenderer = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DjvuRenderer );
171 $djvuPostProcessor = MediaWikiServices::getInstance()->getMainConfig()
172 ->get( MainConfigNames::DjvuPostProcessor );
173 if ( !$this->normaliseParams( $image, $params ) ) {
174 return new TransformParameterError( $params );
175 }
176 $width = $params['width'];
177 $height = $params['height'];
178 $page = $params['page'];
179
180 if ( $flags & self::TRANSFORM_LATER ) {
181 $params = [
182 'width' => $width,
183 'height' => $height,
184 'page' => $page
185 ];
186
187 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
188 }
189
190 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
191 return new MediaTransformError(
192 'thumbnail_error',
193 $width,
194 $height,
195 wfMessage( 'thumbnail_dest_directory' )
196 );
197 }
198
199 // Get local copy source for shell scripts
200 // Thumbnail extraction is very inefficient for large files.
201 // Provide a way to pool count limit the number of downloaders.
202 if ( $image->getSize() >= 1e7 ) { // 10 MB
203 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
204 [
205 'doWork' => static function () use ( $image ) {
206 return $image->getLocalRefPath();
207 }
208 ]
209 );
210 $srcPath = $work->execute();
211 } else {
212 $srcPath = $image->getLocalRefPath();
213 }
214
215 if ( $srcPath === false ) { // Failed to get local copy
216 wfDebugLog( 'thumbnail',
217 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
218 wfHostname(), $image->getName() ) );
219
220 return new MediaTransformError( 'thumbnail_error',
221 $params['width'], $params['height'],
222 wfMessage( 'filemissing' )
223 );
224 }
225
226 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
227 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
228 $cmd = '(' . Shell::escape(
229 $djvuRenderer,
230 "-format=ppm",
231 "-page={$page}",
232 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
233 $srcPath );
234 if ( $djvuPostProcessor ) {
235 $cmd .= " | {$djvuPostProcessor}";
236 }
237 $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
238 wfDebug( __METHOD__ . ": $cmd" );
239 $retval = 0;
240 $err = wfShellExec( $cmd, $retval );
241
242 $removed = $this->removeBadFile( $dstPath, $retval );
243 if ( $retval !== 0 || $removed ) {
244 $this->logErrorForExternalProcess( $retval, $err, $cmd );
245 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
246 }
247 $params = [
248 'width' => $width,
249 'height' => $height,
250 'page' => $page
251 ];
252
253 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
254 }
255
256 /**
257 * Cache an instance of DjVuImage in a MediaHandlerState object, return
258 * that instance
259 *
260 * @param MediaHandlerState $state
261 * @param string $path
262 * @return DjVuImage
263 */
264 private function getDjVuImage( $state, $path ) {
265 $deja = $state->getHandlerState( self::STATE_DJVU_IMAGE );
266 if ( !$deja ) {
267 $deja = new DjVuImage( $path );
268 $state->setHandlerState( self::STATE_DJVU_IMAGE, $deja );
269 }
270 return $deja;
271 }
272
273 /**
274 * Get metadata, unserializing it if necessary.
275 *
276 * @param File $file The DjVu file in question
277 * @param bool $gettext
278 * @return string|false|array metadata
279 */
280 private function getMetadataInternal( File $file, $gettext ) {
281 $itemNames = [ 'error', '_error', 'data' ];
282 if ( $gettext ) {
283 $itemNames[] = 'text';
284 }
285 $unser = $file->getMetadataItems( $itemNames );
286
287 if ( isset( $unser['error'] ) ) {
288 return false;
289 }
290 if ( isset( $unser['_error'] ) ) {
291 return false;
292 }
293 return $unser;
294 }
295
296 /**
297 * Cache a document tree for the DjVu metadata
298 * @param File $image
299 * @param bool $gettext DOCUMENT (Default: false)
300 * @return false|array
301 */
302 public function getMetaTree( $image, $gettext = false ) {
303 if ( $gettext && $image->getHandlerState( self::STATE_TEXT_TREE ) ) {
304 return $image->getHandlerState( self::STATE_TEXT_TREE );
305 }
306 if ( !$gettext && $image->getHandlerState( self::STATE_META_TREE ) ) {
307 return $image->getHandlerState( self::STATE_META_TREE );
308 }
309
310 $metadata = $this->getMetadataInternal( $image, $gettext );
311 if ( !$metadata ) {
312 return false;
313 }
314
315 if ( !$gettext ) {
316 unset( $metadata['text'] );
317 }
318 return $metadata;
319 }
320
321 public function getThumbType( $ext, $mime, $params = null ) {
322 $djvuOutputExtension = MediaWikiServices::getInstance()->getMainConfig()
323 ->get( MainConfigNames::DjvuOutputExtension );
324 static $mime;
325 if ( !isset( $mime ) ) {
326 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
327 $mime = $magic->getMimeTypeFromExtensionOrNull( $djvuOutputExtension );
328 }
329
330 return [ $djvuOutputExtension, $mime ];
331 }
332
333 public function getSizeAndMetadata( $state, $path ) {
334 wfDebug( "Getting DjVu metadata for $path" );
335
336 $djvuImage = $this->getDjVuImage( $state, $path );
337 $metadata = $djvuImage->retrieveMetaData();
338 if ( $metadata === false ) {
339 // Special value so that we don't repetitively try and decode a broken file.
340 $metadata = [ 'error' => 'Error extracting metadata' ];
341 }
342 return [ 'metadata' => $metadata ] + $djvuImage->getImageSize();
343 }
344
345 public function getMetadataType( $image ) {
346 // historical reasons
347 return 'djvuxml';
348 }
349
350 public function isFileMetadataValid( $image ) {
351 return $image->getMetadataArray() ? self::METADATA_GOOD : self::METADATA_BAD;
352 }
353
354 public function pageCount( File $image ) {
355 $info = $this->getDimensionInfo( $image );
356
357 return $info ? $info['pageCount'] : false;
358 }
359
360 public function getPageDimensions( File $image, $page ) {
361 $index = $page - 1; // MW starts pages at 1
362
363 $info = $this->getDimensionInfo( $image );
364 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
365 return $info['dimensionsByPage'][$index];
366 }
367
368 return false;
369 }
370
371 protected function getDimensionInfo( File $file ) {
372 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
373 return $cache->getWithSetCallback(
374 $cache->makeKey( 'file-djvu', 'dimensions', self::CACHE_VERSION, $file->getSha1() ),
375 $cache::TTL_INDEFINITE,
376 function () use ( $file ) {
377 $tree = $this->getMetaTree( $file );
378 return $this->getDimensionInfoFromMetaTree( $tree );
379 },
380 [ 'pcTTL' => $cache::TTL_INDEFINITE ]
381 );
382 }
383
384 /**
385 * Given the metadata, returns dimension information about the document
386 * @param false|array $metatree The file's metadata tree
387 * @return array|false
388 */
389 protected function getDimensionInfoFromMetaTree( $metatree ) {
390 if ( !$metatree ) {
391 return false;
392 }
393 $dimsByPage = [];
394
395 if ( !isset( $metatree['data'] ) || !$metatree['data'] ) {
396 return false;
397 }
398 foreach ( $metatree['data']['pages'] as $page ) {
399 if ( !$page ) {
400 $dimsByPage[] = false;
401 } else {
402 $dimsByPage[] = [
403 'width' => (int)$page['width'],
404 'height' => (int)$page['height'],
405 ];
406 }
407 }
408 return [
409 'pageCount' => count( $metatree['data']['pages'] ),
410 'dimensionsByPage' => $dimsByPage
411 ];
412 }
413
414 /**
415 * @param File $image
416 * @param int $page Page number to get information for
417 * @return string|false Page text or false when no text found.
418 */
419 public function getPageText( File $image, $page ) {
420 $tree = $this->getMetaTree( $image, true );
421 if ( !$tree ) {
422 return false;
423 }
424 if ( isset( $tree['text'] ) && isset( $tree['text'][$page - 1] ) ) {
425 return $tree['text'][$page - 1];
426 }
427 return false;
428 }
429
430 public function useSplitMetadata() {
431 return true;
432 }
433 }