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