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