Merge "Add test for IRC line for legacy type block/block"
[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
147 if ( $flags & self::TRANSFORM_LATER ) {
148 $params = array(
149 'width' => $width,
150 'height' => $height,
151 'page' => $page
152 );
153
154 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
155 }
156
157 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
158 return new MediaTransformError(
159 'thumbnail_error',
160 $width,
161 $height,
162 wfMessage( 'thumbnail_dest_directory' )->text()
163 );
164 }
165
166 // Get local copy source for shell scripts
167 // Thumbnail extraction is very inefficient for large files.
168 // Provide a way to pool count limit the number of downloaders.
169 if ( $image->getSize() >= 1e7 ) { // 10MB
170 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
171 array(
172 'doWork' => function () use ( $image ) {
173 return $image->getLocalRefPath();
174 }
175 )
176 );
177 $srcPath = $work->execute();
178 } else {
179 $srcPath = $image->getLocalRefPath();
180 }
181
182 if ( $srcPath === false ) { // Failed to get local copy
183 wfDebugLog( 'thumbnail',
184 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
185 wfHostname(), $image->getName() ) );
186
187 return new MediaTransformError( 'thumbnail_error',
188 $params['width'], $params['height'],
189 wfMessage( 'filemissing' )->text()
190 );
191 }
192
193 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
194 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
195 $cmd = '(' . wfEscapeShellArg(
196 $wgDjvuRenderer,
197 "-format=ppm",
198 "-page={$page}",
199 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
200 $srcPath );
201 if ( $wgDjvuPostProcessor ) {
202 $cmd .= " | {$wgDjvuPostProcessor}";
203 }
204 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
205 wfDebug( __METHOD__ . ": $cmd\n" );
206 $retval = '';
207 $err = wfShellExec( $cmd, $retval );
208
209 $removed = $this->removeBadFile( $dstPath, $retval );
210 if ( $retval != 0 || $removed ) {
211 $this->logErrorForExternalProcess( $retval, $err, $cmd );
212 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
213 } else {
214 $params = array(
215 'width' => $width,
216 'height' => $height,
217 'page' => $page
218 );
219
220 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
221 }
222 }
223
224 /**
225 * Cache an instance of DjVuImage in an Image object, return that instance
226 *
227 * @param File $image
228 * @param string $path
229 * @return DjVuImage
230 */
231 function getDjVuImage( $image, $path ) {
232 if ( !$image ) {
233 $deja = new DjVuImage( $path );
234 } elseif ( !isset( $image->dejaImage ) ) {
235 $deja = $image->dejaImage = new DjVuImage( $path );
236 } else {
237 $deja = $image->dejaImage;
238 }
239
240 return $deja;
241 }
242
243 /**
244 * Get metadata, unserializing it if neccessary.
245 *
246 * @param File $file The DjVu file in question
247 * @return string XML metadata as a string.
248 * @throws MWException
249 */
250 private function getUnserializedMetadata( File $file ) {
251 $metadata = $file->getMetadata();
252 if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
253 // Old style. Not serialized but instead just a raw string of XML.
254 return $metadata;
255 }
256
257 wfSuppressWarnings();
258 $unser = unserialize( $metadata );
259 wfRestoreWarnings();
260 if ( is_array( $unser ) ) {
261 if ( isset( $unser['error'] ) ) {
262 return false;
263 } elseif ( isset( $unser['xml'] ) ) {
264 return $unser['xml'];
265 } else {
266 // Should never ever reach here.
267 throw new MWException( "Error unserializing DjVu metadata." );
268 }
269 }
270
271 // unserialize failed. Guess it wasn't really serialized after all,
272 return $metadata;
273 }
274
275 /**
276 * Cache a document tree for the DjVu XML metadata
277 * @param File $image
278 * @param bool $gettext DOCUMENT (Default: false)
279 * @return bool|SimpleXMLElement
280 */
281 function getMetaTree( $image, $gettext = false ) {
282 if ( $gettext && isset( $image->djvuTextTree ) ) {
283 return $image->djvuTextTree;
284 }
285 if ( !$gettext && isset( $image->dejaMetaTree ) ) {
286 return $image->dejaMetaTree;
287 }
288
289 $metadata = $this->getUnserializedMetadata( $image );
290 if ( !$this->isMetadataValid( $image, $metadata ) ) {
291 wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
292
293 return false;
294 }
295
296 wfSuppressWarnings();
297 try {
298 // Set to false rather than null to avoid further attempts
299 $image->dejaMetaTree = false;
300 $image->djvuTextTree = false;
301 $tree = new SimpleXMLElement( $metadata );
302 if ( $tree->getName() == 'mw-djvu' ) {
303 /** @var SimpleXMLElement $b */
304 foreach ( $tree->children() as $b ) {
305 if ( $b->getName() == 'DjVuTxt' ) {
306 // @todo File::djvuTextTree and File::dejaMetaTree are declared
307 // dynamically. Add a public File::$data to facilitate this?
308 $image->djvuTextTree = $b;
309 } elseif ( $b->getName() == 'DjVuXML' ) {
310 $image->dejaMetaTree = $b;
311 }
312 }
313 } else {
314 $image->dejaMetaTree = $tree;
315 }
316 } catch ( Exception $e ) {
317 wfDebug( "Bogus multipage XML metadata on '{$image->getName()}'\n" );
318 }
319 wfRestoreWarnings();
320 if ( $gettext ) {
321 return $image->djvuTextTree;
322 } else {
323 return $image->dejaMetaTree;
324 }
325 }
326
327 /**
328 * @param File $image
329 * @param string $path
330 * @return bool|array False on failure
331 */
332 function getImageSize( $image, $path ) {
333 return $this->getDjVuImage( $image, $path )->getImageSize();
334 }
335
336 function getThumbType( $ext, $mime, $params = null ) {
337 global $wgDjvuOutputExtension;
338 static $mime;
339 if ( !isset( $mime ) ) {
340 $magic = MimeMagic::singleton();
341 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
342 }
343
344 return array( $wgDjvuOutputExtension, $mime );
345 }
346
347 function getMetadata( $image, $path ) {
348 wfDebug( "Getting DjVu metadata for $path\n" );
349
350 $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
351 if ( $xml === false ) {
352 // Special value so that we don't repetitively try and decode a broken file.
353 return serialize( array( 'error' => 'Error extracting metadata' ) );
354 } else {
355 return serialize( array( 'xml' => $xml ) );
356 }
357 }
358
359 function getMetadataType( $image ) {
360 return 'djvuxml';
361 }
362
363 function isMetadataValid( $image, $metadata ) {
364 return !empty( $metadata ) && $metadata != serialize( array() );
365 }
366
367 function pageCount( $image ) {
368 $tree = $this->getMetaTree( $image );
369 if ( !$tree ) {
370 return false;
371 }
372
373 return count( $tree->xpath( '//OBJECT' ) );
374 }
375
376 function getPageDimensions( $image, $page ) {
377 $tree = $this->getMetaTree( $image );
378 if ( !$tree ) {
379 return false;
380 }
381
382 $o = $tree->BODY[0]->OBJECT[$page - 1];
383 if ( $o ) {
384 return array(
385 'width' => intval( $o['width'] ),
386 'height' => intval( $o['height'] )
387 );
388 } else {
389 return false;
390 }
391 }
392
393 /**
394 * @param File $image
395 * @param int $page Page number to get information for
396 * @return bool|string Page text or false when no text found.
397 */
398 function getPageText( $image, $page ) {
399 $tree = $this->getMetaTree( $image, true );
400 if ( !$tree ) {
401 return false;
402 }
403
404 $o = $tree->BODY[0]->PAGE[$page - 1];
405 if ( $o ) {
406 $txt = $o['value'];
407
408 return $txt;
409 } else {
410 return false;
411 }
412 }
413 }