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