]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/media/Generic.php
MediaWiki 1.17.0
[autoinstallsdev/mediawiki.git] / includes / media / Generic.php
1 <?php
2 /**
3  * Media-handling base classes and generic functionality
4  *
5  * @file
6  * @ingroup Media
7  */
8
9 /**
10  * Base media handler class
11  *
12  * @ingroup Media
13  */
14 abstract class MediaHandler {
15         const TRANSFORM_LATER = 1;
16
17         /**
18          * Instance cache
19          */
20         static $handlers = array();
21
22         /**
23          * Get a MediaHandler for a given MIME type from the instance cache
24          */
25         static function getHandler( $type ) {
26                 global $wgMediaHandlers;
27                 if ( !isset( $wgMediaHandlers[$type] ) ) {
28                         wfDebug( __METHOD__ . ": no handler found for $type.\n");
29                         return false;
30                 }
31                 $class = $wgMediaHandlers[$type];
32                 if ( !isset( self::$handlers[$class] ) ) {
33                         self::$handlers[$class] = new $class;
34                         if ( !self::$handlers[$class]->isEnabled() ) {
35                                 self::$handlers[$class] = false;
36                         }
37                 }
38                 return self::$handlers[$class];
39         }
40
41         /**
42          * Get an associative array mapping magic word IDs to parameter names.
43          * Will be used by the parser to identify parameters.
44          */
45         abstract function getParamMap();
46
47         /*
48          * Validate a thumbnail parameter at parse time.
49          * Return true to accept the parameter, and false to reject it.
50          * If you return false, the parser will do something quiet and forgiving.
51          */
52         abstract function validateParam( $name, $value );
53
54         /**
55          * Merge a parameter array into a string appropriate for inclusion in filenames
56          */
57         abstract function makeParamString( $params );
58
59         /**
60          * Parse a param string made with makeParamString back into an array
61          */
62         abstract function parseParamString( $str );
63
64         /**
65          * Changes the parameter array as necessary, ready for transformation.
66          * Should be idempotent.
67          * Returns false if the parameters are unacceptable and the transform should fail
68          */
69         abstract function normaliseParams( $image, &$params );
70
71         /**
72          * Get an image size array like that returned by getimagesize(), or false if it
73          * can't be determined.
74          *
75          * @param $image File: the image object, or false if there isn't one
76          * @param $path String: the filename
77          * @return Array
78          */
79         abstract function getImageSize( $image, $path );
80
81         /**
82          * Get handler-specific metadata which will be saved in the img_metadata field.
83          *
84          * @param $image File: the image object, or false if there isn't one.
85          *   Warning, File::getPropsFromPath might pass an (object)array() instead (!)
86          * @param $path String: the filename
87          * @return String
88          */
89         function getMetadata( $image, $path ) { return ''; }
90
91         /**
92          * Get a string describing the type of metadata, for display purposes.
93          */
94         function getMetadataType( $image ) { return false; }
95
96         /**
97          * Check if the metadata string is valid for this handler.
98          * If it returns false, Image will reload the metadata from the file and update the database
99          */
100         function isMetadataValid( $image, $metadata ) { return true; }
101
102
103         /**
104          * Get a MediaTransformOutput object representing an alternate of the transformed
105          * output which will call an intermediary thumbnail assist script.
106          *
107          * Used when the repository has a thumbnailScriptUrl option configured.
108          *
109          * Return false to fall back to the regular getTransform().
110          */
111         function getScriptedTransform( $image, $script, $params ) {
112                 return false;
113         }
114
115         /**
116          * Get a MediaTransformOutput object representing the transformed output. Does not
117          * actually do the transform.
118          *
119          * @param $image File: the image object
120          * @param $dstPath String: filesystem destination path
121          * @param $dstUrl String: Destination URL to use in output HTML
122          * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
123          */
124         function getTransform( $image, $dstPath, $dstUrl, $params ) {
125                 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
126         }
127
128         /**
129          * Get a MediaTransformOutput object representing the transformed output. Does the
130          * transform unless $flags contains self::TRANSFORM_LATER.
131          *
132          * @param $image File: the image object
133          * @param $dstPath String: filesystem destination path
134          * @param $dstUrl String: destination URL to use in output HTML
135          * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
136          * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
137          */
138         abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
139
140         /**
141          * Get the thumbnail extension and MIME type for a given source MIME type
142          * @return array thumbnail extension and MIME type
143          */
144         function getThumbType( $ext, $mime, $params = null ) {
145                 return array( $ext, $mime );
146         }
147
148         /**
149          * True if the handled types can be transformed
150          */
151         function canRender( $file ) { return true; }
152         /**
153          * True if handled types cannot be displayed directly in a browser
154          * but can be rendered
155          */
156         function mustRender( $file ) { return false; }
157         /**
158          * True if the type has multi-page capabilities
159          */
160         function isMultiPage( $file ) { return false; }
161         /**
162          * Page count for a multi-page document, false if unsupported or unknown
163          */
164         function pageCount( $file ) { return false; }
165         /**
166          * The material is vectorized and thus scaling is lossless
167          */
168         function isVectorized( $file ) { return false; }
169         /**
170          * False if the handler is disabled for all files
171          */
172         function isEnabled() { return true; }
173
174         /**
175          * Get an associative array of page dimensions
176          * Currently "width" and "height" are understood, but this might be
177          * expanded in the future.
178          * Returns false if unknown or if the document is not multi-page.
179          */
180         function getPageDimensions( $image, $page ) {
181                 $gis = $this->getImageSize( $image, $image->getPath() );
182                 return array(
183                         'width' => $gis[0],
184                         'height' => $gis[1]
185                 );
186         }
187
188         /**
189          * Generic getter for text layer.
190          * Currently overloaded by PDF and DjVu handlers
191          */
192         function getPageText( $image, $page ) {
193                 return false;
194         }
195
196         /**
197          * Get an array structure that looks like this:
198          *
199          * array(
200          *    'visible' => array(
201          *       'Human-readable name' => 'Human readable value',
202          *       ...
203          *    ),
204          *    'collapsed' => array(
205          *       'Human-readable name' => 'Human readable value',
206          *       ...
207          *    )
208          * )
209          * The UI will format this into a table where the visible fields are always
210          * visible, and the collapsed fields are optionally visible.
211          *
212          * The function should return false if there is no metadata to display.
213          */
214
215         /**
216          * FIXME: I don't really like this interface, it's not very flexible
217          * I think the media handler should generate HTML instead. It can do
218          * all the formatting according to some standard. That makes it possible
219          * to do things like visual indication of grouped and chained streams
220          * in ogg container files.
221          */
222         function formatMetadata( $image ) {
223                 return false;
224         }
225
226         /**
227          * @todo Fixme: document this!
228          * 'value' thingy goes into a wikitext table; it used to be escaped but
229          * that was incompatible with previous practice of customized display
230          * with wikitext formatting via messages such as 'exif-model-value'.
231          * So the escaping is taken back out, but generally this seems a confusing
232          * interface.
233          */
234         protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
235                 $array[$visibility][] = array(
236                         'id' => "$type-$id",
237                         'name' => wfMsg( "$type-$id", $param ),
238                         'value' => $value
239                 );
240         }
241
242         function getShortDesc( $file ) {
243                 global $wgLang;
244                 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
245                         $wgLang->formatNum( $file->getSize() ) );
246                 return "$nbytes";
247         }
248
249         function getLongDesc( $file ) {
250                 global $wgUser;
251                 $sk = $wgUser->getSkin();
252                 return wfMsgExt( 'file-info', 'parseinline',
253                         $sk->formatSize( $file->getSize() ),
254                         $file->getMimeType() );
255         }
256         
257         static function getGeneralShortDesc( $file ) {
258                 global $wgLang;
259                 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
260                         $wgLang->formatNum( $file->getSize() ) );
261                 return "$nbytes";
262         }
263
264         static function getGeneralLongDesc( $file ) {
265                 global $wgUser;
266                 $sk = $wgUser->getSkin();
267                 return wfMsgExt( 'file-info', 'parseinline',
268                         $sk->formatSize( $file->getSize() ),
269                         $file->getMimeType() );
270         }
271
272         function getDimensionsString( $file ) {
273                 return '';
274         }
275
276         /**
277          * Modify the parser object post-transform
278          */
279         function parserTransformHook( $parser, $file ) {}
280
281         /**
282          * File validation hook called on upload.
283          *
284          * If the file at the given local path is not valid, or its MIME type does not 
285          * match the handler class, a Status object should be returned containing
286          * relevant errors.
287          * 
288          * @param $fileName The local path to the file.
289          * @return Status object
290          */
291         function verifyUpload( $fileName ) {
292                 return Status::newGood();
293         }
294
295         /**
296          * Check for zero-sized thumbnails. These can be generated when
297          * no disk space is available or some other error occurs
298          *
299          * @param $dstPath The location of the suspect file
300          * @param $retval Return value of some shell process, file will be deleted if this is non-zero
301          * @return true if removed, false otherwise
302          */
303         function removeBadFile( $dstPath, $retval = 0 ) {
304                 if( file_exists( $dstPath ) ) {
305                         $thumbstat = stat( $dstPath );
306                         if( $thumbstat['size'] == 0 || $retval != 0 ) {
307                                 wfDebugLog( 'thumbnail',
308                                         sprintf( 'Removing bad %d-byte thumbnail "%s"',
309                                                 $thumbstat['size'], $dstPath ) );
310                                 unlink( $dstPath );
311                                 return true;
312                         }
313                 }
314                 return false;
315         }
316 }
317
318 /**
319  * Media handler abstract base class for images
320  *
321  * @ingroup Media
322  */
323 abstract class ImageHandler extends MediaHandler {
324         function canRender( $file ) {
325                 if ( $file->getWidth() && $file->getHeight() ) {
326                         return true;
327                 } else {
328                         return false;
329                 }
330         }
331
332         function getParamMap() {
333                 return array( 'img_width' => 'width' );
334         }
335
336         function validateParam( $name, $value ) {
337                 if ( in_array( $name, array( 'width', 'height' ) ) ) {
338                         if ( $value <= 0 ) {
339                                 return false;
340                         } else {
341                                 return true;
342                         }
343                 } else {
344                         return false;
345                 }
346         }
347
348         function makeParamString( $params ) {
349                 if ( isset( $params['physicalWidth'] ) ) {
350                         $width = $params['physicalWidth'];
351                 } elseif ( isset( $params['width'] ) ) {
352                         $width = $params['width'];
353                 } else {
354                         throw new MWException( 'No width specified to '.__METHOD__ );
355                 }
356                 # Removed for ProofreadPage
357                 #$width = intval( $width );
358                 return "{$width}px";
359         }
360
361         function parseParamString( $str ) {
362                 $m = false;
363                 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
364                         return array( 'width' => $m[1] );
365                 } else {
366                         return false;
367                 }
368         }
369
370         function getScriptParams( $params ) {
371                 return array( 'width' => $params['width'] );
372         }
373
374         function normaliseParams( $image, &$params ) {
375                 $mimeType = $image->getMimeType();
376
377                 if ( !isset( $params['width'] ) ) {
378                         return false;
379                 }
380
381                 if ( !isset( $params['page'] ) ) {
382                         $params['page'] = 1;
383                 } else  {
384                         if ( $params['page'] > $image->pageCount() ) {
385                                 $params['page'] = $image->pageCount();
386                         }
387
388                         if ( $params['page'] < 1 ) {
389                                 $params['page'] = 1;
390                         }
391                 }
392
393                 $srcWidth = $image->getWidth( $params['page'] );
394                 $srcHeight = $image->getHeight( $params['page'] );
395                 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
396                         if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
397                                 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
398                         }
399                 }
400                 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
401                 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
402                         return false;
403                 }
404                 return true;
405         }
406
407         /**
408          * Get a transform output object without actually doing the transform
409          */
410         function getTransform( $image, $dstPath, $dstUrl, $params ) {
411                 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
412         }
413
414         /**
415          * Validate thumbnail parameters and fill in the correct height
416          *
417          * @param $width Integer: specified width (input/output)
418          * @param $height Integer: height (output only)
419          * @param $srcWidth Integer: width of the source image
420          * @param $srcHeight Integer: height of the source image
421          * @param $mimeType Unused
422          * @return false to indicate that an error should be returned to the user.
423          */
424         function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
425                 $width = intval( $width );
426
427                 # Sanity check $width
428                 if( $width <= 0) {
429                         wfDebug( __METHOD__.": Invalid destination width: $width\n" );
430                         return false;
431                 }
432                 if ( $srcWidth <= 0 ) {
433                         wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
434                         return false;
435                 }
436
437                 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
438                 return true;
439         }
440
441         function getScriptedTransform( $image, $script, $params ) {
442                 if ( !$this->normaliseParams( $image, $params ) ) {
443                         return false;
444                 }
445                 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
446                 $page = isset( $params['page'] ) ? $params['page'] : false;
447
448                 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
449                         return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
450                 }
451         }
452
453         function getImageSize( $image, $path ) {
454                 wfSuppressWarnings();
455                 $gis = getimagesize( $path );
456                 wfRestoreWarnings();
457                 return $gis;
458         }
459
460         function isAnimatedImage( $image ) {
461                 return false;
462         }
463
464         function getShortDesc( $file ) {
465                 global $wgLang;
466                 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
467                         $wgLang->formatNum( $file->getSize() ) );
468                 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
469
470                 return "$widthheight ($nbytes)";
471         }
472
473         function getLongDesc( $file ) {
474                 global $wgLang;
475                 return wfMsgExt('file-info-size', 'parseinline',
476                         $wgLang->formatNum( $file->getWidth() ),
477                         $wgLang->formatNum( $file->getHeight() ),
478                         $wgLang->formatSize( $file->getSize() ),
479                         $file->getMimeType() );
480         }
481
482         function getDimensionsString( $file ) {
483                 global $wgLang;
484                 $pages = $file->pageCount();
485                 $width = $wgLang->formatNum( $file->getWidth() );
486                 $height = $wgLang->formatNum( $file->getHeight() );
487                 $pagesFmt = $wgLang->formatNum( $pages );
488
489                 if ( $pages > 1 ) {
490                         return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
491                 } else {
492                         return wfMsg( 'widthheight', $width, $height );
493                 }
494         }
495 }