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