Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / media / DjVuHandler.php
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 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Handler for DjVu images
27 *
28 * @ingroup Media
29 */
30 class DjVuHandler extends ImageHandler {
31 const EXPENSIVE_SIZE_LIMIT = 10485760; // 10MiB
32
33 /**
34 * @return bool
35 */
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" );
40
41 return false;
42 } else {
43 return true;
44 }
45 }
46
47 /**
48 * @param File $file
49 * @return bool
50 */
51 public function mustRender( $file ) {
52 return true;
53 }
54
55 /**
56 * True if creating thumbnails from the file is large or otherwise resource-intensive.
57 * @param File $file
58 * @return bool
59 */
60 public function isExpensiveToThumbnail( $file ) {
61 return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
62 }
63
64 /**
65 * @param File $file
66 * @return bool
67 */
68 public function isMultiPage( $file ) {
69 return true;
70 }
71
72 /**
73 * @return array
74 */
75 public function getParamMap() {
76 return [
77 'img_width' => 'width',
78 'img_page' => 'page',
79 ];
80 }
81
82 /**
83 * @param string $name
84 * @param mixed $value
85 * @return bool
86 */
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]]
91 return false;
92 }
93 if ( in_array( $name, [ 'width', 'height', 'page' ] ) ) {
94 if ( $value <= 0 ) {
95 return false;
96 } else {
97 return true;
98 }
99 } else {
100 return false;
101 }
102 }
103
104 /**
105 * @param array $params
106 * @return bool|string
107 */
108 public function makeParamString( $params ) {
109 $page = $params['page'] ?? 1;
110 if ( !isset( $params['width'] ) ) {
111 return false;
112 }
113
114 return "page{$page}-{$params['width']}px";
115 }
116
117 /**
118 * @param string $str
119 * @return array|bool
120 */
121 public function parseParamString( $str ) {
122 $m = false;
123 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
124 return [ 'width' => $m[2], 'page' => $m[1] ];
125 } else {
126 return false;
127 }
128 }
129
130 /**
131 * @param array $params
132 * @return array
133 */
134 protected function getScriptParams( $params ) {
135 return [
136 'width' => $params['width'],
137 'page' => $params['page'],
138 ];
139 }
140
141 /**
142 * @param File $image
143 * @param string $dstPath
144 * @param string $dstUrl
145 * @param array $params
146 * @param int $flags
147 * @return MediaTransformError|ThumbnailImage|TransformParameterError
148 */
149 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
150 global $wgDjvuRenderer, $wgDjvuPostProcessor;
151
152 if ( !$this->normaliseParams( $image, $params ) ) {
153 return new TransformParameterError( $params );
154 }
155 $width = $params['width'];
156 $height = $params['height'];
157 $page = $params['page'];
158
159 if ( $flags & self::TRANSFORM_LATER ) {
160 $params = [
161 'width' => $width,
162 'height' => $height,
163 'page' => $page
164 ];
165
166 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
167 }
168
169 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
170 return new MediaTransformError(
171 'thumbnail_error',
172 $width,
173 $height,
174 wfMessage( 'thumbnail_dest_directory' )
175 );
176 }
177
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() ),
183 [
184 'doWork' => function () use ( $image ) {
185 return $image->getLocalRefPath();
186 }
187 ]
188 );
189 $srcPath = $work->execute();
190 } else {
191 $srcPath = $image->getLocalRefPath();
192 }
193
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() ) );
198
199 return new MediaTransformError( 'thumbnail_error',
200 $params['width'], $params['height'],
201 wfMessage( 'filemissing' )
202 );
203 }
204
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(
208 $wgDjvuRenderer,
209 "-format=ppm",
210 "-page={$page}",
211 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
212 $srcPath );
213 if ( $wgDjvuPostProcessor ) {
214 $cmd .= " | {$wgDjvuPostProcessor}";
215 }
216 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
217 wfDebug( __METHOD__ . ": $cmd\n" );
218 $retval = '';
219 $err = wfShellExec( $cmd, $retval );
220
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 );
225 } else {
226 $params = [
227 'width' => $width,
228 'height' => $height,
229 'page' => $page
230 ];
231
232 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
233 }
234 }
235
236 /**
237 * Cache an instance of DjVuImage in an Image object, return that instance
238 *
239 * @param File|FSFile $image
240 * @param string $path
241 * @return DjVuImage
242 */
243 function getDjVuImage( $image, $path ) {
244 if ( !$image ) {
245 $deja = new DjVuImage( $path );
246 } elseif ( !isset( $image->dejaImage ) ) {
247 $deja = $image->dejaImage = new DjVuImage( $path );
248 } else {
249 $deja = $image->dejaImage;
250 }
251
252 return $deja;
253 }
254
255 /**
256 * Get metadata, unserializing it if necessary.
257 *
258 * @param File $file The DjVu file in question
259 * @return string XML metadata as a string.
260 * @throws MWException
261 */
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.
266 return $metadata;
267 }
268
269 Wikimedia\suppressWarnings();
270 $unser = unserialize( $metadata );
271 Wikimedia\restoreWarnings();
272 if ( is_array( $unser ) ) {
273 if ( isset( $unser['error'] ) ) {
274 return false;
275 } elseif ( isset( $unser['xml'] ) ) {
276 return $unser['xml'];
277 } else {
278 // Should never ever reach here.
279 throw new MWException( "Error unserializing DjVu metadata." );
280 }
281 }
282
283 // unserialize failed. Guess it wasn't really serialized after all,
284 return $metadata;
285 }
286
287 /**
288 * Cache a document tree for the DjVu XML metadata
289 * @param File $image
290 * @param bool $gettext DOCUMENT (Default: false)
291 * @return bool|SimpleXMLElement
292 */
293 public function getMetaTree( $image, $gettext = false ) {
294 if ( $gettext && isset( $image->djvuTextTree ) ) {
295 return $image->djvuTextTree;
296 }
297 if ( !$gettext && isset( $image->dejaMetaTree ) ) {
298 return $image->dejaMetaTree;
299 }
300
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" );
304
305 return false;
306 }
307
308 $trees = $this->extractTreesFromMetadata( $metadata );
309 $image->djvuTextTree = $trees['TextTree'];
310 $image->dejaMetaTree = $trees['MetaTree'];
311
312 if ( $gettext ) {
313 return $image->djvuTextTree;
314 } else {
315 return $image->dejaMetaTree;
316 }
317 }
318
319 /**
320 * Extracts metadata and text trees from metadata XML in string form
321 * @param string $metadata XML metadata as a string
322 * @return array
323 */
324 protected function extractTreesFromMetadata( $metadata ) {
325 Wikimedia\suppressWarnings();
326 try {
327 // Set to false rather than null to avoid further attempts
328 $metaTree = false;
329 $textTree = false;
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?
337 $textTree = $b;
338 } elseif ( $b->getName() == 'DjVuXML' ) {
339 $metaTree = $b;
340 }
341 }
342 } else {
343 $metaTree = $tree;
344 }
345 } catch ( Exception $e ) {
346 wfDebug( "Bogus multipage XML metadata\n" );
347 }
348 Wikimedia\restoreWarnings();
349
350 return [ 'MetaTree' => $metaTree, 'TextTree' => $textTree ];
351 }
352
353 function getImageSize( $image, $path ) {
354 return $this->getDjVuImage( $image, $path )->getImageSize();
355 }
356
357 public function getThumbType( $ext, $mime, $params = null ) {
358 global $wgDjvuOutputExtension;
359 static $mime;
360 if ( !isset( $mime ) ) {
361 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
362 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
363 }
364
365 return [ $wgDjvuOutputExtension, $mime ];
366 }
367
368 public function getMetadata( $image, $path ) {
369 wfDebug( "Getting DjVu metadata for $path\n" );
370
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' ] );
375 } else {
376 return serialize( [ 'xml' => $xml ] );
377 }
378 }
379
380 function getMetadataType( $image ) {
381 return 'djvuxml';
382 }
383
384 public function isMetadataValid( $image, $metadata ) {
385 return !empty( $metadata ) && $metadata != serialize( [] );
386 }
387
388 public function pageCount( File $image ) {
389 $info = $this->getDimensionInfo( $image );
390
391 return $info ? $info['pageCount'] : false;
392 }
393
394 public function getPageDimensions( File $image, $page ) {
395 $index = $page - 1; // MW starts pages at 1
396
397 $info = $this->getDimensionInfo( $image );
398 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
399 return $info['dimensionsByPage'][$index];
400 }
401
402 return false;
403 }
404
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 );
413 },
414 [ 'pcTTL' => $cache::TTL_INDEFINITE ]
415 );
416 }
417
418 /**
419 * Given an XML metadata tree, returns dimension information about the document
420 * @param bool|SimpleXMLElement $metatree The file's XML metadata tree
421 * @return bool|array
422 */
423 protected function getDimensionInfoFromMetaTree( $metatree ) {
424 if ( !$metatree ) {
425 return false;
426 }
427
428 $dimsByPage = [];
429 $count = count( $metatree->xpath( '//OBJECT' ) );
430 for ( $i = 0; $i < $count; $i++ ) {
431 $o = $metatree->BODY[0]->OBJECT[$i];
432 if ( $o ) {
433 $dimsByPage[$i] = [
434 'width' => (int)$o['width'],
435 'height' => (int)$o['height'],
436 ];
437 } else {
438 $dimsByPage[$i] = false;
439 }
440 }
441
442 return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
443 }
444
445 /**
446 * @param File $image
447 * @param int $page Page number to get information for
448 * @return bool|string Page text or false when no text found.
449 */
450 function getPageText( File $image, $page ) {
451 $tree = $this->getMetaTree( $image, true );
452 if ( !$tree ) {
453 return false;
454 }
455
456 $o = $tree->BODY[0]->PAGE[$page - 1];
457 if ( $o ) {
458 $txt = $o['value'];
459
460 return $txt;
461 } else {
462 return false;
463 }
464 }
465 }