Make DjVu metadata be stored as serialized PHP array.
[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 ( in_array( $name, array( 'width', 'height', 'page' ) ) ) {
77 if ( $value <= 0 ) {
78 return false;
79 } else {
80 return true;
81 }
82 } else {
83 return false;
84 }
85 }
86
87 /**
88 * @param array $params
89 * @return bool|string
90 */
91 function makeParamString( $params ) {
92 $page = isset( $params['page'] ) ? $params['page'] : 1;
93 if ( !isset( $params['width'] ) ) {
94 return false;
95 }
96
97 return "page{$page}-{$params['width']}px";
98 }
99
100 /**
101 * @param string $str
102 * @return array|bool
103 */
104 function parseParamString( $str ) {
105 $m = false;
106 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
107 return array( 'width' => $m[2], 'page' => $m[1] );
108 } else {
109 return false;
110 }
111 }
112
113 /**
114 * @param array $params
115 * @return array
116 */
117 function getScriptParams( $params ) {
118 return array(
119 'width' => $params['width'],
120 'page' => $params['page'],
121 );
122 }
123
124 /**
125 * @param File $image
126 * @param string $dstPath
127 * @param string $dstUrl
128 * @param array $params
129 * @param int $flags
130 * @return MediaTransformError|ThumbnailImage|TransformParameterError
131 */
132 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
133 global $wgDjvuRenderer, $wgDjvuPostProcessor;
134
135 // Fetch XML and check it, to give a more informative error message than the one which
136 // normaliseParams will inevitably give.
137 $xml = $image->getMetadata();
138 if ( !$xml ) {
139 $width = isset( $params['width'] ) ? $params['width'] : 0;
140 $height = isset( $params['height'] ) ? $params['height'] : 0;
141
142 return new MediaTransformError( 'thumbnail_error', $width, $height,
143 wfMessage( 'djvu_no_xml' )->text() );
144 }
145
146 if ( !$this->normaliseParams( $image, $params ) ) {
147 return new TransformParameterError( $params );
148 }
149 $width = $params['width'];
150 $height = $params['height'];
151 $page = $params['page'];
152 if ( $page > $this->pageCount( $image ) ) {
153 return new MediaTransformError(
154 'thumbnail_error',
155 $width,
156 $height,
157 wfMessage( 'djvu_page_error' )->text()
158 );
159 }
160
161 if ( $flags & self::TRANSFORM_LATER ) {
162 $params = array(
163 'width' => $width,
164 'height' => $height,
165 'page' => $page
166 );
167
168 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
169 }
170
171 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
172 return new MediaTransformError(
173 'thumbnail_error',
174 $width,
175 $height,
176 wfMessage( 'thumbnail_dest_directory' )->text()
177 );
178 }
179
180 $srcPath = $image->getLocalRefPath();
181 # Use a subshell (brackets) to aggregate stderr from both pipeline commands
182 # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
183 $cmd = '(' . wfEscapeShellArg(
184 $wgDjvuRenderer,
185 "-format=ppm",
186 "-page={$page}",
187 "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
188 $srcPath );
189 if ( $wgDjvuPostProcessor ) {
190 $cmd .= " | {$wgDjvuPostProcessor}";
191 }
192 $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
193 wfProfileIn( 'ddjvu' );
194 wfDebug( __METHOD__ . ": $cmd\n" );
195 $retval = '';
196 $err = wfShellExec( $cmd, $retval );
197 wfProfileOut( 'ddjvu' );
198
199 $removed = $this->removeBadFile( $dstPath, $retval );
200 if ( $retval != 0 || $removed ) {
201 $this->logErrorForExternalProcess( $retval, $err, $cmd );
202 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
203 } else {
204 $params = array(
205 'width' => $width,
206 'height' => $height,
207 'page' => $page
208 );
209
210 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
211 }
212 }
213
214 /**
215 * Cache an instance of DjVuImage in an Image object, return that instance
216 *
217 * @param File $image
218 * @param string $path
219 * @return DjVuImage
220 */
221 function getDjVuImage( $image, $path ) {
222 if ( !$image ) {
223 $deja = new DjVuImage( $path );
224 } elseif ( !isset( $image->dejaImage ) ) {
225 $deja = $image->dejaImage = new DjVuImage( $path );
226 } else {
227 $deja = $image->dejaImage;
228 }
229
230 return $deja;
231 }
232
233 /**
234 * Get metadata, unserializing it if neccessary.
235 *
236 * @param File $file The DjVu file in question
237 * @return String XML metadata as a string.
238 */
239 private function getUnserializedMetadata( File $file ) {
240 $metadata = $file->getMetadata();
241 if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
242 // Old style. Not serialized but instead just a raw string of XML.
243 return $metadata;
244 }
245
246 wfSuppressWarnings();
247 $unser = unserialize( $metadata );
248 wfRestoreWarnings();
249 if ( is_array( $unser ) ) {
250 return $unser['xml'];
251 }
252
253 // unserialize failed. Guess it wasn't really serialized after all,
254 return $metadata;
255 }
256
257 /**
258 * Cache a document tree for the DjVu XML metadata
259 * @param File $image
260 * @param bool $gettext DOCUMENT (Default: false)
261 * @return bool|SimpleXMLElement
262 */
263 function getMetaTree( $image, $gettext = false ) {
264 if ( $gettext && isset( $image->djvuTextTree ) ) {
265 return $image->djvuTextTree;
266 }
267 if ( !$gettext && isset( $image->dejaMetaTree ) ) {
268 return $image->dejaMetaTree;
269 }
270
271 $metadata = $this->getUnserializedMetadata( $image );
272 if ( !$this->isMetadataValid( $image, $metadata ) ) {
273 wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
274
275 return false;
276 }
277 wfProfileIn( __METHOD__ );
278
279 wfSuppressWarnings();
280 try {
281 // Set to false rather than null to avoid further attempts
282 $image->dejaMetaTree = false;
283 $image->djvuTextTree = false;
284 $tree = new SimpleXMLElement( $metadata );
285 if ( $tree->getName() == 'mw-djvu' ) {
286 /** @var SimpleXMLElement $b */
287 foreach ( $tree->children() as $b ) {
288 if ( $b->getName() == 'DjVuTxt' ) {
289 // @todo File::djvuTextTree and File::dejaMetaTree are declared
290 // dynamically. Add a public File::$data to facilitate this?
291 $image->djvuTextTree = $b;
292 } elseif ( $b->getName() == 'DjVuXML' ) {
293 $image->dejaMetaTree = $b;
294 }
295 }
296 } else {
297 $image->dejaMetaTree = $tree;
298 }
299 } catch ( Exception $e ) {
300 wfDebug( "Bogus multipage XML metadata on '{$image->getName()}'\n" );
301 }
302 wfRestoreWarnings();
303 wfProfileOut( __METHOD__ );
304 if ( $gettext ) {
305 return $image->djvuTextTree;
306 } else {
307 return $image->dejaMetaTree;
308 }
309 }
310
311 /**
312 * @param File $image
313 * @param string $path
314 * @return bool|array False on failure
315 */
316 function getImageSize( $image, $path ) {
317 return $this->getDjVuImage( $image, $path )->getImageSize();
318 }
319
320 function getThumbType( $ext, $mime, $params = null ) {
321 global $wgDjvuOutputExtension;
322 static $mime;
323 if ( !isset( $mime ) ) {
324 $magic = MimeMagic::singleton();
325 $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
326 }
327
328 return array( $wgDjvuOutputExtension, $mime );
329 }
330
331 function getMetadata( $image, $path ) {
332 wfDebug( "Getting DjVu metadata for $path\n" );
333
334 $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
335 if ( $xml === false ) {
336 return false;
337 } else {
338 return serialize( array( 'xml' => $xml ) );
339 }
340 }
341
342 function getMetadataType( $image ) {
343 return 'djvuxml';
344 }
345
346 function isMetadataValid( $image, $metadata ) {
347 return !empty( $metadata ) && $metadata != serialize( array() );
348 }
349
350 function pageCount( $image ) {
351 $tree = $this->getMetaTree( $image );
352 if ( !$tree ) {
353 return false;
354 }
355
356 return count( $tree->xpath( '//OBJECT' ) );
357 }
358
359 function getPageDimensions( $image, $page ) {
360 $tree = $this->getMetaTree( $image );
361 if ( !$tree ) {
362 return false;
363 }
364
365 $o = $tree->BODY[0]->OBJECT[$page - 1];
366 if ( $o ) {
367 return array(
368 'width' => intval( $o['width'] ),
369 'height' => intval( $o['height'] )
370 );
371 } else {
372 return false;
373 }
374 }
375
376 /**
377 * @param File $image
378 * @param int $page Page number to get information for
379 * @return bool|string Page text or false when no text found.
380 */
381 function getPageText( $image, $page ) {
382 $tree = $this->getMetaTree( $image, true );
383 if ( !$tree ) {
384 return false;
385 }
386
387 $o = $tree->BODY[0]->PAGE[$page - 1];
388 if ( $o ) {
389 $txt = $o['value'];
390
391 return $txt;
392 } else {
393 return false;
394 }
395 }
396 }