Merge "Increase parity between api search and on-wiki search"
[lhc/web/wiklou.git] / includes / media / DjVu.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
24 /**
25 * Handler for DjVu images
26 *
27 * @ingroup Media
28 */
29 class DjVuHandler extends ImageHandler {
30 /**
31 * @return bool
32 */
33 function isEnabled() {
34 global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML;
35 if ( !$wgDjvuRenderer || ( !$wgDjvuDump && !$wgDjvuToXML ) ) {
36 wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump\n" );
37
38 return false;
39 } else {
40 return true;
41 }
42 }
43
44 /**
45 * @param File $file
46 * @return bool
47 */
48 function mustRender( $file ) {
49 return true;
50 }
51
52 /**
53 * @param File $file
54 * @return bool
55 */
56 function isMultiPage( $file ) {
57 return true;
58 }
59
60 /**
61 * @return array
62 */
63 function getParamMap() {
64 return array(
65 'img_width' => 'width',
66 'img_page' => 'page',
67 );
68 }
69
70 /**
71 * @param string $name
72 * @param mixed $value
73 * @return bool
74 */
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]]
79 return false;
80 }
81 if ( in_array( $name, array( 'width', 'height', 'page' ) ) ) {
82 if ( $value <= 0 ) {
83 return false;
84 } else {
85 return true;
86 }
87 } else {
88 return false;
89 }
90 }
91
92 /**
93 * @param array $params
94 * @return bool|string
95 */
96 function makeParamString( $params ) {
97 $page = isset( $params['page'] ) ? $params['page'] : 1;
98 if ( !isset( $params['width'] ) ) {
99 return false;
100 }
101
102 return "page{$page}-{$params['width']}px";
103 }
104
105 /**
106 * @param string $str
107 * @return array|bool
108 */
109 function parseParamString( $str ) {
110 $m = false;
111 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
112 return array( 'width' => $m[2], 'page' => $m[1] );
113 } else {
114 return false;
115 }
116 }
117
118 /**
119 * @param array $params
120 * @return array
121 */
122 function getScriptParams( $params ) {
123 return array(
124 'width' => $params['width'],
125 'page' => $params['page'],
126 );
127 }
128
129 /**
130 * @param File $image
131 * @param string $dstPath
132 * @param string $dstUrl
133 * @param array $params
134 * @param int $flags
135 * @return MediaTransformError|ThumbnailImage|TransformParameterError
136 */
137 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
138 global $wgDjvuRenderer, $wgDjvuPostProcessor;
139
140 if ( !$this->normaliseParams( $image, $params ) ) {
141 return new TransformParameterError( $params );
142 }
143 $width = $params['width'];
144 $height = $params['height'];
145 $page = $params['page'];
146 if ( $page > $this->pageCount( $image ) ) {
147 return new MediaTransformError(
148 'thumbnail_error',
149 $width,
150 $height,
151 wfMessage( 'djvu_page_error' )->text()
152 );
153 }
154
155 if ( $flags & self::TRANSFORM_LATER ) {
156 $params = array(
157 'width' => $width,
158 'height' => $height,
159 'page' => $page
160 );
161
162 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
163 }
164
165 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
166 return new MediaTransformError(
167 'thumbnail_error',
168 $width,
169 $height,
170 wfMessage( 'thumbnail_dest_directory' )->text()
171 );
172 }
173
174 // Get local copy source for shell scripts
175 // Thumbnail extraction is very inefficient for large files.
176 // Provide a way to pool count limit the number of downloaders.
177 if ( $image->getSize() >= 1e7 ) { // 10MB
178 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
179 array(
180 'doWork' => function () use ( $image ) {
181 return $image->getLocalRefPath();
182 }
183 )
184 );
185 $srcPath = $work->execute();
186 } else {
187 $srcPath = $image->getLocalRefPath();
188 }
189
190 if ( $srcPath === false ) { // Failed to get local copy
191 wfDebugLog( 'thumbnail',
192 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
193 wfHostname(), $image->getName() ) );
194
195 return new MediaTransformError( 'thumbnail_error',
196 $params['width'], $params['height'],
197 wfMessage( 'filemissing' )->text()
198 );
199 }
200
201 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
202 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
203 $cmd = '(' . wfEscapeShellArg(
204 $wgDjvuRenderer,
205 "-format=ppm",
206 "-page={$page}",
207 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
208 $srcPath );
209 if ( $wgDjvuPostProcessor ) {
210 $cmd .= " | {$wgDjvuPostProcessor}";
211 }
212 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
213 wfDebug( __METHOD__ . ": $cmd\n" );
214 $retval = '';
215 $err = wfShellExec( $cmd, $retval );
216
217 $removed = $this->removeBadFile( $dstPath, $retval );
218 if ( $retval != 0 || $removed ) {
219 $this->logErrorForExternalProcess( $retval, $err, $cmd );
220 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
221 } else {
222 $params = array(
223 'width' => $width,
224 'height' => $height,
225 'page' => $page
226 );
227
228 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
229 }
230 }
231
232 /**
233 * Cache an instance of DjVuImage in an Image object, return that instance
234 *
235 * @param File $image
236 * @param string $path
237 * @return DjVuImage
238 */
239 function getDjVuImage( $image, $path ) {
240 if ( !$image ) {
241 $deja = new DjVuImage( $path );
242 } elseif ( !isset( $image->dejaImage ) ) {
243 $deja = $image->dejaImage = new DjVuImage( $path );
244 } else {
245 $deja = $image->dejaImage;
246 }
247
248 return $deja;
249 }
250
251 /**
252 * Get metadata, unserializing it if neccessary.
253 *
254 * @param File $file The DjVu file in question
255 * @return string XML metadata as a string.
256 * @throws MWException
257 */
258 private function getUnserializedMetadata( File $file ) {
259 $metadata = $file->getMetadata();
260 if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
261 // Old style. Not serialized but instead just a raw string of XML.
262 return $metadata;
263 }
264
265 wfSuppressWarnings();
266 $unser = unserialize( $metadata );
267 wfRestoreWarnings();
268 if ( is_array( $unser ) ) {
269 if ( isset( $unser['error'] ) ) {
270 return false;
271 } elseif ( isset( $unser['xml'] ) ) {
272 return $unser['xml'];
273 } else {
274 // Should never ever reach here.
275 throw new MWException( "Error unserializing DjVu metadata." );
276 }
277 }
278
279 // unserialize failed. Guess it wasn't really serialized after all,
280 return $metadata;
281 }
282
283 /**
284 * Cache a document tree for the DjVu XML metadata
285 * @param File $image
286 * @param bool $gettext DOCUMENT (Default: false)
287 * @return bool|SimpleXMLElement
288 */
289 function getMetaTree( $image, $gettext = false ) {
290 if ( $gettext && isset( $image->djvuTextTree ) ) {
291 return $image->djvuTextTree;
292 }
293 if ( !$gettext && isset( $image->dejaMetaTree ) ) {
294 return $image->dejaMetaTree;
295 }
296
297 $metadata = $this->getUnserializedMetadata( $image );
298 if ( !$this->isMetadataValid( $image, $metadata ) ) {
299 wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
300
301 return false;
302 }
303
304 wfSuppressWarnings();
305 try {
306 // Set to false rather than null to avoid further attempts
307 $image->dejaMetaTree = false;
308 $image->djvuTextTree = false;
309 $tree = new SimpleXMLElement( $metadata );
310 if ( $tree->getName() == 'mw-djvu' ) {
311 /** @var SimpleXMLElement $b */
312 foreach ( $tree->children() as $b ) {
313 if ( $b->getName() == 'DjVuTxt' ) {
314 // @todo File::djvuTextTree and File::dejaMetaTree are declared
315 // dynamically. Add a public File::$data to facilitate this?
316 $image->djvuTextTree = $b;
317 } elseif ( $b->getName() == 'DjVuXML' ) {
318 $image->dejaMetaTree = $b;
319 }
320 }
321 } else {
322 $image->dejaMetaTree = $tree;
323 }
324 } catch ( Exception $e ) {
325 wfDebug( "Bogus multipage XML metadata on '{$image->getName()}'\n" );
326 }
327 wfRestoreWarnings();
328 if ( $gettext ) {
329 return $image->djvuTextTree;
330 } else {
331 return $image->dejaMetaTree;
332 }
333 }
334
335 /**
336 * @param File $image
337 * @param string $path
338 * @return bool|array False on failure
339 */
340 function getImageSize( $image, $path ) {
341 return $this->getDjVuImage( $image, $path )->getImageSize();
342 }
343
344 function getThumbType( $ext, $mime, $params = null ) {
345 global $wgDjvuOutputExtension;
346 static $mime;
347 if ( !isset( $mime ) ) {
348 $magic = MimeMagic::singleton();
349 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
350 }
351
352 return array( $wgDjvuOutputExtension, $mime );
353 }
354
355 function getMetadata( $image, $path ) {
356 wfDebug( "Getting DjVu metadata for $path\n" );
357
358 $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
359 if ( $xml === false ) {
360 // Special value so that we don't repetitively try and decode a broken file.
361 return serialize( array( 'error' => 'Error extracting metadata' ) );
362 } else {
363 return serialize( array( 'xml' => $xml ) );
364 }
365 }
366
367 function getMetadataType( $image ) {
368 return 'djvuxml';
369 }
370
371 function isMetadataValid( $image, $metadata ) {
372 return !empty( $metadata ) && $metadata != serialize( array() );
373 }
374
375 function pageCount( $image ) {
376 $tree = $this->getMetaTree( $image );
377 if ( !$tree ) {
378 return false;
379 }
380
381 return count( $tree->xpath( '//OBJECT' ) );
382 }
383
384 function getPageDimensions( $image, $page ) {
385 $tree = $this->getMetaTree( $image );
386 if ( !$tree ) {
387 return false;
388 }
389
390 $o = $tree->BODY[0]->OBJECT[$page - 1];
391 if ( $o ) {
392 return array(
393 'width' => intval( $o['width'] ),
394 'height' => intval( $o['height'] )
395 );
396 } else {
397 return false;
398 }
399 }
400
401 /**
402 * @param File $image
403 * @param int $page Page number to get information for
404 * @return bool|string Page text or false when no text found.
405 */
406 function getPageText( $image, $page ) {
407 $tree = $this->getMetaTree( $image, true );
408 if ( !$tree ) {
409 return false;
410 }
411
412 $o = $tree->BODY[0]->PAGE[$page - 1];
413 if ( $o ) {
414 $txt = $o['value'];
415
416 return $txt;
417 } else {
418 return false;
419 }
420 }
421 }