ae28c721628f7fbf2bd442484fbd07ff8cf6860d
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 # NOTE FOR WINDOWS USERS:
7 # To enable EXIF functions, add the folloing lines to the
8 # "Windows extensions" section of php.ini:
9 #
10 # extension=extensions/php_mbstring.dll
11 # extension=extensions/php_exif.dll
12
13 if ($wgShowEXIF)
14 require_once('Exif.php');
15
16
17 /**
18 * Class to represent an image
19 *
20 * Provides methods to retrieve paths (physical, logical, URL),
21 * to generate thumbnails or for uploading.
22 * @package MediaWiki
23 */
24 class Image
25 {
26 /**#@+
27 * @access private
28 */
29 var $name, # name of the image (constructor)
30 $imagePath, # Path of the image (loadFromXxx)
31 $url, # Image URL (accessor)
32 $title, # Title object for this image (constructor)
33 $fileExists, # does the image file exist on disk? (loadFromXxx)
34 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
35 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
36 $historyRes, # result of the query for the image's history (nextHistoryLine)
37 $width, # \
38 $height, # |
39 $bits, # --- returned by getimagesize (loadFromXxx)
40 $type, # |
41 $attr, # /
42 $size, # Size in bytes (loadFromXxx)
43 $metadata, # Metadata
44 $exif, # The Exif class
45 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
46
47
48 /**#@-*/
49
50 /**
51 * Create an Image object from an image name
52 *
53 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
54 * @access public
55 */
56 function newFromName( $name ) {
57 $title = Title::makeTitleSafe( NS_IMAGE, $name );
58 return new Image( $title );
59 }
60
61 /**
62 * Obsolete factory function, use constructor
63 */
64 function newFromTitle( $title ) {
65 return new Image( $title );
66 }
67
68 function Image( $title ) {
69 global $wgShowEXIF;
70
71 $this->title =& $title;
72 $this->name = $title->getDBkey();
73 $this->metadata = serialize ( array() ) ;
74
75 $n = strrpos( $this->name, '.' );
76 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
77 $this->historyLine = 0;
78
79 $this->dataLoaded = false;
80
81 if ($wgShowEXIF)
82 $this->exif = new Exif;
83 }
84
85 /**
86 * Get the memcached keys
87 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
88 */
89 function getCacheKeys( $shared = false ) {
90 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
91
92 $foundCached = false;
93 $hashedName = md5($this->name);
94 $keys = array( "$wgDBname:Image:$hashedName" );
95 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
96 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
97 }
98 return $keys;
99 }
100
101 /**
102 * Try to load image metadata from memcached. Returns true on success.
103 */
104 function loadFromCache() {
105 global $wgUseSharedUploads, $wgMemc;
106 $fname = 'Image::loadFromMemcached';
107 wfProfileIn( $fname );
108 $this->dataLoaded = false;
109 $keys = $this->getCacheKeys();
110 $cachedValues = $wgMemc->get( $keys[0] );
111
112 // Check if the key existed and belongs to this version of MediaWiki
113 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width'])
114 && $cachedValues['fileExists'] && isset( $cachedValues['metadata'] ) )
115 {
116 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
117 # if this is shared file, we need to check if image
118 # in shared repository has not changed
119 if ( isset( $keys[1] ) ) {
120 $commonsCachedValues = $wgMemc->get( $keys[1] );
121 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
122 $this->name = $commonsCachedValues['name'];
123 $this->imagePath = $commonsCachedValues['imagePath'];
124 $this->fileExists = $commonsCachedValues['fileExists'];
125 $this->width = $commonsCachedValues['width'];
126 $this->height = $commonsCachedValues['height'];
127 $this->bits = $commonsCachedValues['bits'];
128 $this->type = $commonsCachedValues['type'];
129 $this->metadata = $commonsCachedValues['metadata'];
130 $this->size = $commonsCachedValues['size'];
131 $this->fromSharedDirectory = true;
132 $this->dataLoaded = true;
133 $this->imagePath = $this->getFullPath(true);
134 }
135 }
136 }
137 else {
138 $this->name = $cachedValues['name'];
139 $this->imagePath = $cachedValues['imagePath'];
140 $this->fileExists = $cachedValues['fileExists'];
141 $this->width = $cachedValues['width'];
142 $this->height = $cachedValues['height'];
143 $this->bits = $cachedValues['bits'];
144 $this->type = $cachedValues['type'];
145 $this->metadata = $cachedValues['metadata'];
146 $this->size = $cachedValues['size'];
147 $this->fromSharedDirectory = false;
148 $this->dataLoaded = true;
149 $this->imagePath = $this->getFullPath();
150 }
151 }
152
153 wfProfileOut( $fname );
154 return $this->dataLoaded;
155 }
156
157 /**
158 * Save the image metadata to memcached
159 */
160 function saveToCache() {
161 global $wgMemc;
162 $this->load();
163 // We can't cache metadata for non-existent files, because if the file later appears
164 // in commons, the local keys won't be purged.
165 if ( $this->fileExists ) {
166 $keys = $this->getCacheKeys();
167
168 $cachedValues = array('name' => $this->name,
169 'imagePath' => $this->imagePath,
170 'fileExists' => $this->fileExists,
171 'fromShared' => $this->fromSharedDirectory,
172 'width' => $this->width,
173 'height' => $this->height,
174 'bits' => $this->bits,
175 'type' => $this->type,
176 'metadata' => $this->metadata,
177 'size' => $this->size);
178
179 $wgMemc->set( $keys[0], $cachedValues );
180 }
181 }
182
183 /**
184 * Load metadata from the file itself
185 */
186 function loadFromFile() {
187 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
188 $fname = 'Image::loadFromFile';
189 wfProfileIn( $fname );
190 $this->imagePath = $this->getFullPath();
191 $this->fileExists = file_exists( $this->imagePath );
192 $this->fromSharedDirectory = false;
193 $gis = false;
194
195 # If the file is not found, and a shared upload directory is used, look for it there.
196 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
197 # In case we're on a wgCapitalLinks=false wiki, we
198 # capitalize the first letter of the filename before
199 # looking it up in the shared repository.
200 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
201 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
202 if ( $this->fileExists ) {
203 $this->name = $sharedImage->name;
204 $this->imagePath = $this->getFullPath(true);
205 $this->fromSharedDirectory = true;
206 }
207 }
208
209 if ( $this->fileExists ) {
210 # Get size in bytes
211 $this->size = filesize( $this->imagePath );
212
213 # Height and width
214 # Don't try to get the width and height of sound and video files, that's bad for performance
215 if ( !Image::isKnownImageExtension( $this->extension ) ) {
216 $gis = false;
217 } elseif( $this->extension == 'svg' ) {
218 wfSuppressWarnings();
219 $gis = wfGetSVGsize( $this->imagePath );
220 wfRestoreWarnings();
221 } else {
222 wfSuppressWarnings();
223 $gis = getimagesize( $this->imagePath );
224 wfRestoreWarnings();
225 }
226 }
227 if( $gis === false ) {
228 $this->width = 0;
229 $this->height = 0;
230 $this->bits = 0;
231 $this->type = 0;
232 $this->metadata = serialize ( array() ) ;
233 } else {
234 $this->width = $gis[0];
235 $this->height = $gis[1];
236 $this->type = $gis[2];
237 $this->metadata = serialize ( $this->retrieveExifData() ) ;
238 if ( isset( $gis['bits'] ) ) {
239 $this->bits = $gis['bits'];
240 } else {
241 $this->bits = 0;
242 }
243 }
244 $this->dataLoaded = true;
245 wfProfileOut( $fname );
246 }
247
248 /**
249 * Load image metadata from the DB
250 */
251 function loadFromDB() {
252 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
253 $fname = 'Image::loadFromDB';
254 wfProfileIn( $fname );
255
256 $dbr =& wfGetDB( DB_SLAVE );
257 $row = $dbr->selectRow( 'image',
258 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
259 array( 'img_name' => $this->name ), $fname );
260 if ( $row ) {
261 $this->fromSharedDirectory = false;
262 $this->fileExists = true;
263 $this->loadFromRow( $row );
264 $this->imagePath = $this->getFullPath();
265 // Check for rows from a previous schema, quietly upgrade them
266 if ( $this->type == -1 ) {
267 $this->upgradeRow();
268 }
269 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
270 # In case we're on a wgCapitalLinks=false wiki, we
271 # capitalize the first letter of the filename before
272 # looking it up in the shared repository.
273 $name = $wgLang->ucfirst($this->name);
274
275 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
276 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
277 array( 'img_name' => $name ), $fname );
278 if ( $row ) {
279 $this->fromSharedDirectory = true;
280 $this->fileExists = true;
281 $this->imagePath = $this->getFullPath(true);
282 $this->name = $name;
283 $this->loadFromRow( $row );
284
285 // Check for rows from a previous schema, quietly upgrade them
286 if ( $this->type == -1 ) {
287 $this->upgradeRow();
288 }
289 }
290 }
291
292 if ( !$row ) {
293 $this->size = 0;
294 $this->width = 0;
295 $this->height = 0;
296 $this->bits = 0;
297 $this->type = 0;
298 $this->fileExists = false;
299 $this->fromSharedDirectory = false;
300 $this->metadata = serialize ( array() ) ;
301 }
302
303 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
304 $this->dataLoaded = true;
305 }
306
307 /*
308 * Load image metadata from a DB result row
309 */
310 function loadFromRow( &$row ) {
311 $this->size = $row->img_size;
312 $this->width = $row->img_width;
313 $this->height = $row->img_height;
314 $this->bits = $row->img_bits;
315 $this->type = $row->img_type;
316 $this->metadata = $row->img_metadata;
317 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
318 $this->dataLoaded = true;
319 }
320
321 /**
322 * Load image metadata from cache or DB, unless already loaded
323 */
324 function load() {
325 global $wgSharedUploadDBname, $wgUseSharedUploads;
326 if ( !$this->dataLoaded ) {
327 if ( !$this->loadFromCache() ) {
328 $this->loadFromDB();
329 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
330 $this->loadFromFile();
331 } elseif ( $this->fileExists ) {
332 $this->saveToCache();
333 }
334 }
335 $this->dataLoaded = true;
336 }
337 }
338
339 /**
340 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
341 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
342 */
343 function upgradeRow() {
344 global $wgDBname, $wgSharedUploadDBname;
345 $fname = 'Image::upgradeRow';
346 $this->loadFromFile();
347 $dbw =& wfGetDB( DB_MASTER );
348
349 if ( $this->fromSharedDirectory ) {
350 if ( !$wgSharedUploadDBname ) {
351 return;
352 }
353
354 // Write to the other DB using selectDB, not database selectors
355 // This avoids breaking replication in MySQL
356 $dbw->selectDB( $wgSharedUploadDBname );
357 }
358 $dbw->update( 'image',
359 array(
360 'img_width' => $this->width,
361 'img_height' => $this->height,
362 'img_bits' => $this->bits,
363 'img_type' => $this->type,
364 'img_metadata' => $this->metadata,
365 ), array( 'img_name' => $this->name ), $fname
366 );
367 if ( $this->fromSharedDirectory ) {
368 $dbw->selectDB( $wgDBname );
369 }
370 }
371
372 /**
373 * Return the name of this image
374 * @access public
375 */
376 function getName() {
377 return $this->name;
378 }
379
380 /**
381 * Return the associated title object
382 * @access public
383 */
384 function getTitle() {
385 return $this->title;
386 }
387
388 /**
389 * Return the URL of the image file
390 * @access public
391 */
392 function getURL() {
393 if ( !$this->url ) {
394 $this->load();
395 if($this->fileExists) {
396 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
397 } else {
398 $this->url = '';
399 }
400 }
401 return $this->url;
402 }
403
404 function getViewURL() {
405 if( $this->mustRender() ) {
406 return $this->createThumb( $this->getWidth() );
407 } else {
408 return $this->getURL();
409 }
410 }
411
412 /**
413 * Return the image path of the image in the
414 * local file system as an absolute path
415 * @access public
416 */
417 function getImagePath() {
418 $this->load();
419 return $this->imagePath;
420 }
421
422 /**
423 * Return the width of the image
424 *
425 * Returns -1 if the file specified is not a known image type
426 * @access public
427 */
428 function getWidth() {
429 $this->load();
430 return $this->width;
431 }
432
433 /**
434 * Return the height of the image
435 *
436 * Returns -1 if the file specified is not a known image type
437 * @access public
438 */
439 function getHeight() {
440 $this->load();
441 return $this->height;
442 }
443
444 /**
445 * Return the size of the image file, in bytes
446 * @access public
447 */
448 function getSize() {
449 $this->load();
450 return $this->size;
451 }
452
453 /**
454 * Return the type of the image
455 *
456 * - 1 GIF
457 * - 2 JPG
458 * - 3 PNG
459 * - 15 WBMP
460 * - 16 XBM
461 */
462 function getType() {
463 $this->load();
464 return $this->type;
465 }
466
467 /**
468 * Return the escapeLocalURL of this image
469 * @access public
470 */
471 function getEscapeLocalURL() {
472 $this->getTitle();
473 return $this->title->escapeLocalURL();
474 }
475
476 /**
477 * Return the escapeFullURL of this image
478 * @access public
479 */
480 function getEscapeFullURL() {
481 $this->getTitle();
482 return $this->title->escapeFullURL();
483 }
484
485 /**
486 * Return the URL of an image, provided its name.
487 *
488 * @param string $name Name of the image, without the leading "Image:"
489 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
490 * @access public
491 * @static
492 */
493 function imageUrl( $name, $fromSharedDirectory = false ) {
494 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
495 if($fromSharedDirectory) {
496 $base = '';
497 $path = $wgSharedUploadPath;
498 } else {
499 $base = $wgUploadBaseUrl;
500 $path = $wgUploadPath;
501 }
502 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
503 return wfUrlencode( $url );
504 }
505
506 /**
507 * Returns true if the image file exists on disk.
508 *
509 * @access public
510 */
511 function exists() {
512 $this->load();
513 return $this->fileExists;
514 }
515
516 /**
517 *
518 * @access private
519 */
520 function thumbUrl( $width, $subdir='thumb') {
521 global $wgUploadPath, $wgUploadBaseUrl,
522 $wgSharedUploadPath,$wgSharedUploadDirectory,
523 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
524
525 // Generate thumb.php URL if possible
526 $script = false;
527 $url = false;
528
529 if ( $this->fromSharedDirectory ) {
530 if ( $wgSharedThumbnailScriptPath ) {
531 $script = $wgSharedThumbnailScriptPath;
532 }
533 } else {
534 if ( $wgThumbnailScriptPath ) {
535 $script = $wgThumbnailScriptPath;
536 }
537 }
538 if ( $script ) {
539 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
540 } else {
541 $name = $this->thumbName( $width );
542 if($this->fromSharedDirectory) {
543 $base = '';
544 $path = $wgSharedUploadPath;
545 } else {
546 $base = $wgUploadBaseUrl;
547 $path = $wgUploadPath;
548 }
549 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
550 $url = "{$base}{$path}/{$subdir}" .
551 wfGetHashPath($this->name, $this->fromSharedDirectory)
552 . $this->name.'/'.$name;
553 $url = wfUrlencode( $url );
554 } else {
555 $url = "{$base}{$path}/{$subdir}/{$name}";
556 }
557 }
558 return array( $script !== false, $url );
559 }
560
561 /**
562 * Return the file name of a thumbnail of the specified width
563 *
564 * @param integer $width Width of the thumbnail image
565 * @param boolean $shared Does the thumbnail come from the shared repository?
566 * @access private
567 */
568 function thumbName( $width ) {
569 $thumb = $width."px-".$this->name;
570 if( $this->extension == 'svg' ) {
571 # Rasterize SVG vector images to PNG
572 $thumb .= '.png';
573 }
574 return $thumb;
575 }
576
577 /**
578 * Create a thumbnail of the image having the specified width/height.
579 * The thumbnail will not be created if the width is larger than the
580 * image's width. Let the browser do the scaling in this case.
581 * The thumbnail is stored on disk and is only computed if the thumbnail
582 * file does not exist OR if it is older than the image.
583 * Returns the URL.
584 *
585 * Keeps aspect ratio of original image. If both width and height are
586 * specified, the generated image will be no bigger than width x height,
587 * and will also have correct aspect ratio.
588 *
589 * @param integer $width maximum width of the generated thumbnail
590 * @param integer $height maximum height of the image (optional)
591 * @access public
592 */
593 function createThumb( $width, $height=-1 ) {
594 $thumb = $this->getThumbnail( $width, $height );
595 if( is_null( $thumb ) ) return '';
596 return $thumb->getUrl();
597 }
598
599 /**
600 * As createThumb, but returns a ThumbnailImage object. This can
601 * provide access to the actual file, the real size of the thumb,
602 * and can produce a convenient <img> tag for you.
603 *
604 * @param integer $width maximum width of the generated thumbnail
605 * @param integer $height maximum height of the image (optional)
606 * @return ThumbnailImage
607 * @access public
608 */
609 function &getThumbnail( $width, $height=-1 ) {
610 if ( $height == -1 ) {
611 return $this->renderThumb( $width );
612 }
613 $this->load();
614 if ( $width < $this->width ) {
615 $thumbheight = $this->height * $width / $this->width;
616 $thumbwidth = $width;
617 } else {
618 $thumbheight = $this->height;
619 $thumbwidth = $this->width;
620 }
621 if ( $thumbheight > $height ) {
622 $thumbwidth = $thumbwidth * $height / $thumbheight;
623 $thumbheight = $height;
624 }
625 $thumb = $this->renderThumb( $thumbwidth );
626 if( is_null( $thumb ) ) {
627 $thumb = $this->iconThumb();
628 }
629 return $thumb;
630 }
631
632 /**
633 * @return ThumbnailImage
634 */
635 function iconThumb() {
636 global $wgStylePath, $wgStyleDirectory;
637
638 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
639 foreach( $try as $icon ) {
640 $path = '/common/images/icons/' . $icon;
641 $filepath = $wgStyleDirectory . $path;
642 if( file_exists( $filepath ) ) {
643 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
644 }
645 }
646 return null;
647 }
648
649 /**
650 * Create a thumbnail of the image having the specified width.
651 * The thumbnail will not be created if the width is larger than the
652 * image's width. Let the browser do the scaling in this case.
653 * The thumbnail is stored on disk and is only computed if the thumbnail
654 * file does not exist OR if it is older than the image.
655 * Returns an object which can return the pathname, URL, and physical
656 * pixel size of the thumbnail -- or null on failure.
657 *
658 * @return ThumbnailImage
659 * @access private
660 */
661 function renderThumb( $width, $useScript = true ) {
662 global $wgUseSquid, $wgInternalServer;
663 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
664
665 $width = IntVal( $width );
666
667 $this->load();
668 if ( ! $this->exists() )
669 {
670 # If there is no image, there will be no thumbnail
671 return null;
672 }
673
674 # Sanity check $width
675 if( $width <= 0 ) {
676 # BZZZT
677 return null;
678 }
679
680 if( $width > $this->width && !$this->mustRender() ) {
681 # Don't make an image bigger than the source
682 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
683 }
684
685 $height = floor( $this->height * ( $width/$this->width ) );
686
687 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
688 if ( $isScriptUrl && $useScript ) {
689 // Use thumb.php to render the image
690 return new ThumbnailImage( $url, $width, $height );
691 }
692
693 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
694 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
695
696 if ( !file_exists( $thumbPath ) ) {
697 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
698 '/'.$thumbName;
699 $done = false;
700 if ( file_exists( $oldThumbPath ) ) {
701 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
702 rename( $oldThumbPath, $thumbPath );
703 $done = true;
704 } else {
705 unlink( $oldThumbPath );
706 }
707 }
708 if ( !$done ) {
709 $this->reallyRenderThumb( $thumbPath, $width, $height );
710
711 # Purge squid
712 # This has to be done after the image is updated and present for all machines on NFS,
713 # or else the old version might be stored into the squid again
714 if ( $wgUseSquid ) {
715 if ( substr( $url, 0, 4 ) == 'http' ) {
716 $urlArr = array( $url );
717 } else {
718 $urlArr = array( $wgInternalServer.$url );
719 }
720 wfPurgeSquidServers($urlArr);
721 }
722 }
723 }
724 return new ThumbnailImage( $url, $width, $height, $thumbPath );
725 } // END OF function renderThumb
726
727 /**
728 * Really render a thumbnail
729 *
730 * @access private
731 */
732 function reallyRenderThumb( $thumbPath, $width, $height ) {
733 global $wgSVGConverters, $wgSVGConverter,
734 $wgUseImageMagick, $wgImageMagickConvertCommand;
735
736 $this->load();
737
738 if( $this->extension == 'svg' ) {
739 global $wgSVGConverters, $wgSVGConverter;
740 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
741 global $wgSVGConverterPath;
742 $cmd = str_replace(
743 array( '$path/', '$width', '$input', '$output' ),
744 array( $wgSVGConverterPath,
745 $width,
746 escapeshellarg( $this->imagePath ),
747 escapeshellarg( $thumbPath ) ),
748 $wgSVGConverters[$wgSVGConverter] );
749 $conv = shell_exec( $cmd );
750 } else {
751 $conv = false;
752 }
753 } elseif ( $wgUseImageMagick ) {
754 # use ImageMagick
755 # Specify white background color, will be used for transparent images
756 # in Internet Explorer/Windows instead of default black.
757 $cmd = $wgImageMagickConvertCommand .
758 " -quality 85 -background white -geometry {$width} ".
759 escapeshellarg($this->imagePath) . " " .
760 escapeshellarg($thumbPath);
761 $conv = shell_exec( $cmd );
762 } else {
763 # Use PHP's builtin GD library functions.
764 #
765 # First find out what kind of file this is, and select the correct
766 # input routine for this.
767
768 $truecolor = false;
769
770 switch( $this->type ) {
771 case 1: # GIF
772 $src_image = imagecreatefromgif( $this->imagePath );
773 break;
774 case 2: # JPG
775 $src_image = imagecreatefromjpeg( $this->imagePath );
776 $truecolor = true;
777 break;
778 case 3: # PNG
779 $src_image = imagecreatefrompng( $this->imagePath );
780 $truecolor = ( $this->bits > 8 );
781 break;
782 case 15: # WBMP for WML
783 $src_image = imagecreatefromwbmp( $this->imagePath );
784 break;
785 case 16: # XBM
786 $src_image = imagecreatefromxbm( $this->imagePath );
787 break;
788 default:
789 return 'Image type not supported';
790 break;
791 }
792 if ( $truecolor ) {
793 $dst_image = imagecreatetruecolor( $width, $height );
794 } else {
795 $dst_image = imagecreate( $width, $height );
796 }
797 imagecopyresampled( $dst_image, $src_image,
798 0,0,0,0,
799 $width, $height, $this->width, $this->height );
800 switch( $this->type ) {
801 case 1: # GIF
802 case 3: # PNG
803 case 15: # WBMP
804 case 16: # XBM
805 imagepng( $dst_image, $thumbPath );
806 break;
807 case 2: # JPEG
808 imageinterlace( $dst_image );
809 imagejpeg( $dst_image, $thumbPath, 95 );
810 break;
811 default:
812 break;
813 }
814 imagedestroy( $dst_image );
815 imagedestroy( $src_image );
816 }
817 #
818 # Check for zero-sized thumbnails. Those can be generated when
819 # no disk space is available or some other error occurs
820 #
821 if( file_exists( $thumbPath ) ) {
822 $thumbstat = stat( $thumbPath );
823 if( $thumbstat['size'] == 0 ) {
824 unlink( $thumbPath );
825 }
826 }
827 }
828
829 /**
830 * Get all thumbnail names previously generated for this image
831 */
832 function getThumbnails( $shared = false ) {
833 if ( Image::isHashed( $shared ) ) {
834 $this->load();
835 $files = array();
836 $dir = wfImageThumbDir( $this->name, $shared );
837
838 // This generates an error on failure, hence the @
839 $handle = @opendir( $dir );
840
841 if ( $handle ) {
842 while ( false !== ( $file = readdir($handle) ) ) {
843 if ( $file{0} != '.' ) {
844 $files[] = $file;
845 }
846 }
847 closedir( $handle );
848 }
849 } else {
850 $files = array();
851 }
852
853 return $files;
854 }
855
856 /**
857 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
858 */
859 function purgeCache( $archiveFiles = array(), $shared = false ) {
860 global $wgInternalServer, $wgUseSquid;
861
862 // Refresh metadata cache
863 clearstatcache();
864 $this->loadFromFile();
865 $this->saveToCache();
866
867 // Delete thumbnails
868 $files = $this->getThumbnails( $shared );
869 $dir = wfImageThumbDir( $this->name, $shared );
870 $urls = array();
871 foreach ( $files as $file ) {
872 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
873 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
874 @unlink( "$dir/$file" );
875 }
876 }
877
878 // Purge the squid
879 if ( $wgUseSquid ) {
880 $urls[] = $wgInternalServer . $this->getViewURL();
881 foreach ( $archiveFiles as $file ) {
882 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
883 }
884 wfPurgeSquidServers( $urls );
885 }
886 }
887
888 /**
889 * Return the image history of this image, line by line.
890 * starts with current version, then old versions.
891 * uses $this->historyLine to check which line to return:
892 * 0 return line for current version
893 * 1 query for old versions, return first one
894 * 2, ... return next old version from above query
895 *
896 * @access public
897 */
898 function nextHistoryLine() {
899 $fname = 'Image::nextHistoryLine()';
900 $dbr =& wfGetDB( DB_SLAVE );
901 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
902 $this->historyRes = $dbr->select( 'image',
903 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
904 array( 'img_name' => $this->title->getDBkey() ),
905 $fname
906 );
907 if ( 0 == wfNumRows( $this->historyRes ) ) {
908 return FALSE;
909 }
910 } else if ( $this->historyLine == 1 ) {
911 $this->historyRes = $dbr->select( 'oldimage',
912 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
913 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
914 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
915 );
916 }
917 $this->historyLine ++;
918
919 return $dbr->fetchObject( $this->historyRes );
920 }
921
922 /**
923 * Reset the history pointer to the first element of the history
924 * @access public
925 */
926 function resetHistory() {
927 $this->historyLine = 0;
928 }
929
930 /**
931 * Return true if the file is of a type that can't be directly
932 * rendered by typical browsers and needs to be re-rasterized.
933 * @return bool
934 */
935 function mustRender() {
936 $this->load();
937 return ( $this->extension == 'svg' );
938 }
939
940 /**
941 * Return the full filesystem path to the file. Note that this does
942 * not mean that a file actually exists under that location.
943 *
944 * This path depends on whether directory hashing is active or not,
945 * i.e. whether the images are all found in the same directory,
946 * or in hashed paths like /images/3/3c.
947 *
948 * @access public
949 * @param boolean $fromSharedDirectory Return the path to the file
950 * in a shared repository (see $wgUseSharedRepository and related
951 * options in DefaultSettings.php) instead of a local one.
952 *
953 */
954 function getFullPath( $fromSharedRepository = false ) {
955 global $wgUploadDirectory, $wgSharedUploadDirectory;
956 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
957
958 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
959 $wgUploadDirectory;
960
961 // $wgSharedUploadDirectory may be false, if thumb.php is used
962 if ( $dir ) {
963 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
964 } else {
965 $fullpath = false;
966 }
967
968 return $fullpath;
969 }
970
971 /**
972 * @return bool
973 * @static
974 */
975 function isHashed( $shared ) {
976 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
977 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
978 }
979
980 /**
981 * @return bool
982 * @static
983 */
984 function isKnownImageExtension( $ext ) {
985 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
986 return in_array( $ext, $extensions );
987 }
988
989 /**
990 * Record an image upload in the upload log and the image table
991 */
992 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
993 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
994 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
995
996 $fname = 'Image::recordUpload';
997 $dbw =& wfGetDB( DB_MASTER );
998
999 # img_name must be unique
1000 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
1001 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1002 }
1003
1004 // Delete thumbnails and refresh the metadata cache
1005 $this->purgeCache();
1006
1007 // Fail now if the image isn't there
1008 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1009 return false;
1010 }
1011
1012 if ( $wgUseCopyrightUpload ) {
1013 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1014 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1015 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1016 } else {
1017 $textdesc = $desc;
1018 }
1019
1020 $now = $dbw->timestamp();
1021
1022 # Test to see if the row exists using INSERT IGNORE
1023 # This avoids race conditions by locking the row until the commit, and also
1024 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1025 $dbw->insert( 'image',
1026 array(
1027 'img_name' => $this->name,
1028 'img_size'=> $this->size,
1029 'img_width' => $this->width,
1030 'img_height' => $this->height,
1031 'img_bits' => $this->bits,
1032 'img_type' => $this->type,
1033 'img_timestamp' => $now,
1034 'img_description' => $desc,
1035 'img_user' => $wgUser->getID(),
1036 'img_user_text' => $wgUser->getName(),
1037 'img_metadata' => $this->metadata,
1038 ), $fname, 'IGNORE'
1039 );
1040 $descTitle = $this->getTitle();
1041 $purgeURLs = array();
1042
1043 if ( $dbw->affectedRows() ) {
1044 # Successfully inserted, this is a new image
1045 $id = $descTitle->getArticleID();
1046
1047 if ( $id == 0 ) {
1048 $article = new Article( $descTitle );
1049 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1050 }
1051 } else {
1052 # Collision, this is an update of an image
1053 # Insert previous contents into oldimage
1054 $dbw->insertSelect( 'oldimage', 'image',
1055 array(
1056 'oi_name' => 'img_name',
1057 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1058 'oi_size' => 'img_size',
1059 'oi_width' => 'img_width',
1060 'oi_height' => 'img_height',
1061 'oi_bits' => 'img_bits',
1062 'oi_type' => 'img_type',
1063 'oi_timestamp' => 'img_timestamp',
1064 'oi_description' => 'img_description',
1065 'oi_user' => 'img_user',
1066 'oi_user_text' => 'img_user_text',
1067 ), array( 'img_name' => $this->name ), $fname
1068 );
1069
1070 # Update the current image row
1071 $dbw->update( 'image',
1072 array( /* SET */
1073 'img_size' => $this->size,
1074 'img_width' => $this->width,
1075 'img_height' => $this->height,
1076 'img_bits' => $this->bits,
1077 'img_type' => $this->type,
1078 'img_timestamp' => $now,
1079 'img_user' => $wgUser->getID(),
1080 'img_user_text' => $wgUser->getName(),
1081 'img_description' => $desc,
1082 'img_metadata' => $this->metadata,
1083 ), array( /* WHERE */
1084 'img_name' => $this->name
1085 ), $fname
1086 );
1087
1088 # Invalidate the cache for the description page
1089 $descTitle->invalidateCache();
1090 $purgeURLs[] = $descTitle->getInternalURL();
1091 }
1092
1093 # Invalidate cache for all pages using this image
1094 $linksTo = $this->getLinksTo();
1095
1096 if ( $wgUseSquid ) {
1097 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1098 array_push( $wgPostCommitUpdateList, $u );
1099 }
1100 Title::touchArray( $linksTo );
1101
1102 $log = new LogPage( 'upload' );
1103 $log->addEntry( 'upload', $descTitle, $desc );
1104
1105 return true;
1106 }
1107
1108 /**
1109 * Get an array of Title objects which are articles which use this image
1110 * Also adds their IDs to the link cache
1111 *
1112 * This is mostly copied from Title::getLinksTo()
1113 */
1114 function getLinksTo( $options = '' ) {
1115 global $wgLinkCache;
1116 $fname = 'Image::getLinksTo';
1117 wfProfileIn( $fname );
1118
1119 if ( $options ) {
1120 $db =& wfGetDB( DB_MASTER );
1121 } else {
1122 $db =& wfGetDB( DB_SLAVE );
1123 }
1124
1125 extract( $db->tableNames( 'page', 'imagelinks' ) );
1126 $encName = $db->addQuotes( $this->name );
1127 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1128 $res = $db->query( $sql, $fname );
1129
1130 $retVal = array();
1131 if ( $db->numRows( $res ) ) {
1132 while ( $row = $db->fetchObject( $res ) ) {
1133 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1134 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1135 $retVal[] = $titleObj;
1136 }
1137 }
1138 }
1139 $db->freeResult( $res );
1140 return $retVal;
1141 }
1142 /**
1143 * Retrive Exif data from the database
1144 *
1145 * Retrive Exif data from the database and prune unrecognized tags
1146 * and/or tags with invalid contents
1147 *
1148 * @return array
1149 */
1150 function retrieveExifData () {
1151 if ( $this->type !== '2' ) return array ();
1152
1153 $exif = exif_read_data( $this->imagePath );
1154 foreach($exif as $k => $v) {
1155 if ( !in_array($k, array_keys($this->exif->mFlatExif)) ) {
1156 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1157 unset($exif[$k]);
1158 }
1159 }
1160
1161 foreach($exif as $k => $v) {
1162 if ( !$this->exif->validate($k, $v) ) {
1163 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1164 unset($exif[$k]);
1165 }
1166 }
1167 return $exif;
1168 }
1169
1170 function getExifData () {
1171 global $wgRequest;
1172 if ( $this->metadata === '0' )
1173 return array();
1174
1175 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1176 $ret = unserialize ( $this->metadata );
1177
1178 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1179 $newver = $this->exif->version();
1180
1181 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1182 $this->updateExifData( $newver );
1183 }
1184 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1185 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1186
1187 foreach($ret as $k => $v) {
1188 $ret[$k] = $this->exif->format($k, $v);
1189 }
1190
1191 return $ret;
1192 }
1193
1194 function updateExifData( $version ) {
1195 $fname = 'Image:updateExifData';
1196
1197 if ( $this->getImagePath() === false ) # Not a local image
1198 return;
1199
1200 # Get EXIF data from image
1201 $exif = $this->retrieveExifData();
1202 if ( count( $exif ) ) {
1203 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1204 $this->metadata = serialize( $exif );
1205 } else {
1206 $this->metadata = '0';
1207 }
1208
1209 # Update EXIF data in database
1210 $dbw =& wfGetDB( DB_MASTER );
1211 $dbw->update( 'image',
1212 array( 'img_metadata' => $this->metadata ),
1213 array( 'img_name' => $this->name ),
1214 $fname
1215 );
1216 }
1217
1218 } //class
1219
1220
1221 /**
1222 * Returns the image directory of an image
1223 * If the directory does not exist, it is created.
1224 * The result is an absolute path.
1225 *
1226 * This function is called from thumb.php before Setup.php is included
1227 *
1228 * @param string $fname file name of the image file
1229 * @access public
1230 */
1231 function wfImageDir( $fname ) {
1232 global $wgUploadDirectory, $wgHashedUploadDirectory;
1233
1234 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1235
1236 $hash = md5( $fname );
1237 $oldumask = umask(0);
1238 $dest = $wgUploadDirectory . '/' . $hash{0};
1239 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1240 $dest .= '/' . substr( $hash, 0, 2 );
1241 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1242
1243 umask( $oldumask );
1244 return $dest;
1245 }
1246
1247 /**
1248 * Returns the image directory of an image's thubnail
1249 * If the directory does not exist, it is created.
1250 * The result is an absolute path.
1251 *
1252 * This function is called from thumb.php before Setup.php is included
1253 *
1254 * @param string $fname file name of the original image file
1255 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1256 * @param boolean $shared (optional) use the shared upload directory
1257 * @access public
1258 */
1259 function wfImageThumbDir( $fname, $shared = false ) {
1260 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1261 if ( Image::isHashed( $shared ) ) {
1262 $dir = "$base/$fname";
1263
1264 if ( !is_dir( $base ) ) {
1265 $oldumask = umask(0);
1266 @mkdir( $base, 0777 );
1267 umask( $oldumask );
1268 }
1269
1270 if ( ! is_dir( $dir ) ) {
1271 $oldumask = umask(0);
1272 @mkdir( $dir, 0777 );
1273 umask( $oldumask );
1274 }
1275 } else {
1276 $dir = $base;
1277 }
1278
1279 return $dir;
1280 }
1281
1282 /**
1283 * Old thumbnail directory, kept for conversion
1284 */
1285 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1286 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1287 }
1288
1289 /**
1290 * Returns the image directory of an image's old version
1291 * If the directory does not exist, it is created.
1292 * The result is an absolute path.
1293 *
1294 * This function is called from thumb.php before Setup.php is included
1295 *
1296 * @param string $fname file name of the thumbnail file, including file size prefix
1297 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1298 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1299 * @access public
1300 */
1301 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1302 global $wgUploadDirectory, $wgHashedUploadDirectory,
1303 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1304 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1305 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1306 if (!$hashdir) { return $dir.'/'.$subdir; }
1307 $hash = md5( $fname );
1308 $oldumask = umask(0);
1309
1310 # Suppress warning messages here; if the file itself can't
1311 # be written we'll worry about it then.
1312 wfSuppressWarnings();
1313
1314 $archive = $dir.'/'.$subdir;
1315 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1316 $archive .= '/' . $hash{0};
1317 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1318 $archive .= '/' . substr( $hash, 0, 2 );
1319 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1320
1321 wfRestoreWarnings();
1322 umask( $oldumask );
1323 return $archive;
1324 }
1325
1326
1327 /*
1328 * Return the hash path component of an image path (URL or filesystem),
1329 * e.g. "/3/3c/", or just "/" if hashing is not used.
1330 *
1331 * @param $dbkey The filesystem / database name of the file
1332 * @param $fromSharedDirectory Use the shared file repository? It may
1333 * use different hash settings from the local one.
1334 */
1335 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1336 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1337 global $wgHashedUploadDirectory;
1338
1339 if( Image::isHashed( $fromSharedDirectory ) ) {
1340 $hash = md5($dbkey);
1341 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1342 } else {
1343 return '/';
1344 }
1345 }
1346
1347 /**
1348 * Returns the image URL of an image's old version
1349 *
1350 * @param string $fname file name of the image file
1351 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1352 * @access public
1353 */
1354 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1355 global $wgUploadPath, $wgHashedUploadDirectory;
1356
1357 if ($wgHashedUploadDirectory) {
1358 $hash = md5( substr( $name, 15) );
1359 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1360 substr( $hash, 0, 2 ) . '/'.$name;
1361 } else {
1362 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1363 }
1364 return wfUrlencode($url);
1365 }
1366
1367 /**
1368 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1369 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1370 *
1371 * @param string $length
1372 * @return int Length in pixels
1373 */
1374 function wfScaleSVGUnit( $length ) {
1375 static $unitLength = array(
1376 'px' => 1.0,
1377 'pt' => 1.25,
1378 'pc' => 15.0,
1379 'mm' => 3.543307,
1380 'cm' => 35.43307,
1381 'in' => 90.0,
1382 '' => 1.0, // "User units" pixels by default
1383 '%' => 2.0, // Fake it!
1384 );
1385 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1386 $length = FloatVal( $matches[1] );
1387 $unit = $matches[2];
1388 return round( $length * $unitLength[$unit] );
1389 } else {
1390 // Assume pixels
1391 return round( FloatVal( $length ) );
1392 }
1393 }
1394
1395 /**
1396 * Compatible with PHP getimagesize()
1397 * @todo support gzipped SVGZ
1398 * @todo check XML more carefully
1399 * @todo sensible defaults
1400 *
1401 * @param string $filename
1402 * @return array
1403 */
1404 function wfGetSVGsize( $filename ) {
1405 $width = 256;
1406 $height = 256;
1407
1408 // Read a chunk of the file
1409 $f = fopen( $filename, "rt" );
1410 if( !$f ) return false;
1411 $chunk = fread( $f, 4096 );
1412 fclose( $f );
1413
1414 // Uber-crappy hack! Run through a real XML parser.
1415 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1416 return false;
1417 }
1418 $tag = $matches[1];
1419 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1420 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1421 }
1422 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1423 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1424 }
1425
1426 return array( $width, $height, 'SVG',
1427 "width=\"$width\" height=\"$height\"" );
1428 }
1429
1430 /**
1431 * Determine if an image exists on the 'bad image list'
1432 *
1433 * @param string $name The image to check
1434 * @return bool
1435 */
1436 function wfIsBadImage( $name ) {
1437 global $wgContLang;
1438 static $titleList = false;
1439 if ( $titleList === false ) {
1440 $titleList = array();
1441
1442 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1443 foreach ( $lines as $line ) {
1444 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1445 $t = Title::newFromText( $m[1] );
1446 $titleList[$t->getDBkey()] = 1;
1447 }
1448 }
1449 }
1450
1451 return array_key_exists( $name, $titleList );
1452 }
1453
1454
1455
1456 /**
1457 * Wrapper class for thumbnail images
1458 * @package MediaWiki
1459 */
1460 class ThumbnailImage {
1461 /**
1462 * @param string $path Filesystem path to the thumb
1463 * @param string $url URL path to the thumb
1464 * @access private
1465 */
1466 function ThumbnailImage( $url, $width, $height, $path = false ) {
1467 $this->url = $url;
1468 $this->width = $width;
1469 $this->height = $height;
1470 $this->path = $path;
1471 }
1472
1473 /**
1474 * @return string The thumbnail URL
1475 */
1476 function getUrl() {
1477 return $this->url;
1478 }
1479
1480 /**
1481 * Return HTML <img ... /> tag for the thumbnail, will include
1482 * width and height attributes and a blank alt text (as required).
1483 *
1484 * You can set or override additional attributes by passing an
1485 * associative array of name => data pairs. The data will be escaped
1486 * for HTML output, so should be in plaintext.
1487 *
1488 * @param array $attribs
1489 * @return string
1490 * @access public
1491 */
1492 function toHtml( $attribs = array() ) {
1493 $attribs['src'] = $this->url;
1494 $attribs['width'] = $this->width;
1495 $attribs['height'] = $this->height;
1496 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1497
1498 $html = '<img ';
1499 foreach( $attribs as $name => $data ) {
1500 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1501 }
1502 $html .= '/>';
1503 return $html;
1504 }
1505
1506 }
1507 ?>