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