Conversion from 1.4 schema, zero downtime
[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 // Check for rows from a previous schema, quietly upgrade them
241 if ( $this->type == -1 ) {
242 $this->upgradeRow();
243 }
244 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
245 # In case we're on a wgCapitalLinks=false wiki, we
246 # capitalize the first letter of the filename before
247 # looking it up in the shared repository.
248 $name = $wgLang->ucfirst($this->name);
249
250 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
251 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
252 array( 'img_name' => $name ), $fname );
253 if ( $row ) {
254 $this->fromSharedDirectory = true;
255 $this->fileExists = true;
256 $this->imagePath = $this->getFullPath(true);
257 $this->name = $name;
258 $this->loadFromRow( $row );
259
260 // Check for rows from a previous schema, quietly upgrade them
261 if ( $this->type == -1 ) {
262 $this->upgradeRow();
263 }
264 }
265 }
266
267 if ( !$row ) {
268 $this->size = 0;
269 $this->width = 0;
270 $this->height = 0;
271 $this->bits = 0;
272 $this->type = 0;
273 $this->fileExists = false;
274 $this->fromSharedDirectory = false;
275 }
276
277 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
278 $this->dataLoaded = true;
279 }
280
281 /*
282 * Load image metadata from a DB result row
283 */
284 function loadFromRow( &$row ) {
285 $this->size = $row->img_size;
286 $this->width = $row->img_width;
287 $this->height = $row->img_height;
288 $this->bits = $row->img_bits;
289 $this->type = $row->img_type;
290 $this->dataLoaded = true;
291 }
292
293 /**
294 * Load image metadata from cache or DB, unless already loaded
295 */
296 function load() {
297 global $wgSharedUploadDBname, $wgUseSharedUploads;
298 if ( !$this->dataLoaded ) {
299 if ( !$this->loadFromCache() ) {
300 $this->loadFromDB();
301 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
302 $this->loadFromFile();
303 } elseif ( $this->fileExists ) {
304 $this->saveToCache();
305 }
306 }
307 $this->dataLoaded = true;
308 }
309 }
310
311 /**
312 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
313 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
314 */
315 function upgradeRow() {
316 global $wgDBname, $wgSharedUploadDBname;
317 $fname = 'Image::upgradeRow';
318 $this->loadFromFile();
319 $dbw =& wfGetDB( DB_MASTER );
320
321 if ( $this->fromSharedDirectory ) {
322 if ( !$wgSharedUploadDBname ) {
323 return;
324 }
325
326 // Write to the other DB using selectDB, not database selectors
327 // This avoids breaking replication in MySQL
328 $dbw->selectDB( $wgSharedUploadDBname );
329 }
330 $dbw->update( '`image`',
331 array(
332 'img_width' => $this->width,
333 'img_height' => $this->height,
334 'img_bits' => $this->bits,
335 'img_type' => $this->type,
336 ), array( 'img_name' => $this->name ), $fname
337 );
338 if ( $this->fromSharedDirectory ) {
339 $dbw->selectDB( $wgDBname );
340 }
341 }
342
343 /**
344 * Return the name of this image
345 * @access public
346 */
347 function getName() {
348 return $this->name;
349 }
350
351 /**
352 * Return the associated title object
353 * @access public
354 */
355 function getTitle() {
356 return $this->title;
357 }
358
359 /**
360 * Return the URL of the image file
361 * @access public
362 */
363 function getURL() {
364 if ( !$this->url ) {
365 $this->load();
366 if($this->fileExists) {
367 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
368 } else {
369 $this->url = '';
370 }
371 }
372 return $this->url;
373 }
374
375 function getViewURL() {
376 if( $this->mustRender() ) {
377 return $this->createThumb( $this->getWidth() );
378 } else {
379 return $this->getURL();
380 }
381 }
382
383 /**
384 * Return the image path of the image in the
385 * local file system as an absolute path
386 * @access public
387 */
388 function getImagePath() {
389 $this->load();
390 return $this->imagePath;
391 }
392
393 /**
394 * Return the width of the image
395 *
396 * Returns -1 if the file specified is not a known image type
397 * @access public
398 */
399 function getWidth() {
400 $this->load();
401 return $this->width;
402 }
403
404 /**
405 * Return the height of the image
406 *
407 * Returns -1 if the file specified is not a known image type
408 * @access public
409 */
410 function getHeight() {
411 $this->load();
412 return $this->height;
413 }
414
415 /**
416 * Return the size of the image file, in bytes
417 * @access public
418 */
419 function getSize() {
420 $this->load();
421 return $this->size;
422 }
423
424 /**
425 * Return the type of the image
426 *
427 * - 1 GIF
428 * - 2 JPG
429 * - 3 PNG
430 * - 15 WBMP
431 * - 16 XBM
432 */
433 function getType() {
434 $this->load();
435 return $this->type;
436 }
437
438 /**
439 * Return the escapeLocalURL of this image
440 * @access public
441 */
442 function getEscapeLocalURL() {
443 $this->getTitle();
444 return $this->title->escapeLocalURL();
445 }
446
447 /**
448 * Return the escapeFullURL of this image
449 * @access public
450 */
451 function getEscapeFullURL() {
452 $this->getTitle();
453 return $this->title->escapeFullURL();
454 }
455
456 /**
457 * Return the URL of an image, provided its name.
458 *
459 * @param string $name Name of the image, without the leading "Image:"
460 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
461 * @access public
462 * @static
463 */
464 function imageUrl( $name, $fromSharedDirectory = false ) {
465 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
466 if($fromSharedDirectory) {
467 $base = '';
468 $path = $wgSharedUploadPath;
469 } else {
470 $base = $wgUploadBaseUrl;
471 $path = $wgUploadPath;
472 }
473 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
474 return wfUrlencode( $url );
475 }
476
477 /**
478 * Returns true if the image file exists on disk.
479 *
480 * @access public
481 */
482 function exists() {
483 $this->load();
484 return $this->fileExists;
485 }
486
487 /**
488 *
489 * @access private
490 */
491 function thumbUrl( $width, $subdir='thumb') {
492 global $wgUploadPath, $wgUploadBaseUrl,
493 $wgSharedUploadPath,$wgSharedUploadDirectory,
494 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
495
496 // Generate thumb.php URL if possible
497 $script = false;
498 $url = false;
499
500 if ( $this->fromSharedDirectory ) {
501 if ( $wgSharedThumbnailScriptPath ) {
502 $script = $wgSharedThumbnailScriptPath;
503 }
504 } else {
505 if ( $wgThumbnailScriptPath ) {
506 $script = $wgThumbnailScriptPath;
507 }
508 }
509 if ( $script ) {
510 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
511 } else {
512 $name = $this->thumbName( $width );
513 if($this->fromSharedDirectory) {
514 $base = '';
515 $path = $wgSharedUploadPath;
516 } else {
517 $base = $wgUploadBaseUrl;
518 $path = $wgUploadPath;
519 }
520 $url = "{$base}{$path}/{$subdir}" .
521 wfGetHashPath($this->name, $this->fromSharedDirectory)
522 . $this->name.'/'.$name;
523 $url = wfUrlencode( $url );
524 }
525 return array( $script !== false, $url );
526 }
527
528 /**
529 * Return the file name of a thumbnail of the specified width
530 *
531 * @param integer $width Width of the thumbnail image
532 * @param boolean $shared Does the thumbnail come from the shared repository?
533 * @access private
534 */
535 function thumbName( $width ) {
536 $thumb = $width."px-".$this->name;
537 if( $this->extension == 'svg' ) {
538 # Rasterize SVG vector images to PNG
539 $thumb .= '.png';
540 }
541 return $thumb;
542 }
543
544 /**
545 * Create a thumbnail of the image having the specified width/height.
546 * The thumbnail will not be created if the width is larger than the
547 * image's width. Let the browser do the scaling in this case.
548 * The thumbnail is stored on disk and is only computed if the thumbnail
549 * file does not exist OR if it is older than the image.
550 * Returns the URL.
551 *
552 * Keeps aspect ratio of original image. If both width and height are
553 * specified, the generated image will be no bigger than width x height,
554 * and will also have correct aspect ratio.
555 *
556 * @param integer $width maximum width of the generated thumbnail
557 * @param integer $height maximum height of the image (optional)
558 * @access public
559 */
560 function createThumb( $width, $height=-1 ) {
561 $thumb = $this->getThumbnail( $width, $height );
562 if( is_null( $thumb ) ) return '';
563 return $thumb->getUrl();
564 }
565
566 /**
567 * As createThumb, but returns a ThumbnailImage object. This can
568 * provide access to the actual file, the real size of the thumb,
569 * and can produce a convenient <img> tag for you.
570 *
571 * @param integer $width maximum width of the generated thumbnail
572 * @param integer $height maximum height of the image (optional)
573 * @return ThumbnailImage
574 * @access public
575 */
576 function &getThumbnail( $width, $height=-1 ) {
577 if ( $height == -1 ) {
578 return $this->renderThumb( $width );
579 }
580 $this->load();
581 if ( $width < $this->width ) {
582 $thumbheight = $this->height * $width / $this->width;
583 $thumbwidth = $width;
584 } else {
585 $thumbheight = $this->height;
586 $thumbwidth = $this->width;
587 }
588 if ( $thumbheight > $height ) {
589 $thumbwidth = $thumbwidth * $height / $thumbheight;
590 $thumbheight = $height;
591 }
592 $thumb = $this->renderThumb( $thumbwidth );
593 if( is_null( $thumb ) ) {
594 $thumb = $this->iconThumb();
595 }
596 return $thumb;
597 }
598
599 /**
600 * @return ThumbnailImage
601 */
602 function iconThumb() {
603 global $wgStylePath, $wgStyleDirectory;
604
605 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
606 foreach( $try as $icon ) {
607 $path = '/common/images/' . $icon;
608 $filepath = $wgStyleDirectory . $path;
609 if( file_exists( $filepath ) ) {
610 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
611 }
612 }
613 return null;
614 }
615
616 /**
617 * Create a thumbnail of the image having the specified width.
618 * The thumbnail will not be created if the width is larger than the
619 * image's width. Let the browser do the scaling in this case.
620 * The thumbnail is stored on disk and is only computed if the thumbnail
621 * file does not exist OR if it is older than the image.
622 * Returns an object which can return the pathname, URL, and physical
623 * pixel size of the thumbnail -- or null on failure.
624 *
625 * @return ThumbnailImage
626 * @access private
627 */
628 function /* private */ renderThumb( $width, $useScript = true ) {
629 global $wgUseSquid, $wgInternalServer;
630 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
631
632 $width = IntVal( $width );
633
634 $this->load();
635 if ( ! $this->exists() )
636 {
637 # If there is no image, there will be no thumbnail
638 return null;
639 }
640
641 # Sanity check $width
642 if( $width <= 0 ) {
643 # BZZZT
644 return null;
645 }
646
647 if( $width > $this->width && !$this->mustRender() ) {
648 # Don't make an image bigger than the source
649 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
650 }
651
652 $height = floor( $this->height * ( $width/$this->width ) );
653
654 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
655 if ( $isScriptUrl && $useScript ) {
656 // Use thumb.php to render the image
657 return new ThumbnailImage( $url, $width, $height );
658 }
659
660 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
661 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
662
663 if ( !file_exists( $thumbPath ) ) {
664 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
665 '/'.$thumbName;
666 $done = false;
667 if ( file_exists( $oldThumbPath ) ) {
668 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
669 rename( $oldThumbPath, $thumbPath );
670 $done = true;
671 } else {
672 unlink( $oldThumbPath );
673 }
674 }
675 if ( !$done ) {
676 $this->reallyRenderThumb( $thumbPath, $width, $height );
677
678 # Purge squid
679 # This has to be done after the image is updated and present for all machines on NFS,
680 # or else the old version might be stored into the squid again
681 if ( $wgUseSquid ) {
682 if ( substr( $url, 0, 4 ) == 'http' ) {
683 $urlArr = array( $url );
684 } else {
685 $urlArr = array( $wgInternalServer.$url );
686 }
687 wfPurgeSquidServers($urlArr);
688 }
689 }
690 }
691 return new ThumbnailImage( $url, $width, $height, $thumbPath );
692 } // END OF function renderThumb
693
694 /**
695 * Really render a thumbnail
696 *
697 * @access private
698 */
699 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
700 global $wgSVGConverters, $wgSVGConverter,
701 $wgUseImageMagick, $wgImageMagickConvertCommand;
702
703 $this->load();
704
705 if( $this->extension == 'svg' ) {
706 global $wgSVGConverters, $wgSVGConverter;
707 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
708 global $wgSVGConverterPath;
709 $cmd = str_replace(
710 array( '$path/', '$width', '$input', '$output' ),
711 array( $wgSVGConverterPath,
712 $width,
713 escapeshellarg( $this->imagePath ),
714 escapeshellarg( $thumbPath ) ),
715 $wgSVGConverters[$wgSVGConverter] );
716 $conv = shell_exec( $cmd );
717 } else {
718 $conv = false;
719 }
720 } elseif ( $wgUseImageMagick ) {
721 # use ImageMagick
722 # Specify white background color, will be used for transparent images
723 # in Internet Explorer/Windows instead of default black.
724 $cmd = $wgImageMagickConvertCommand .
725 " -quality 85 -background white -geometry {$width} ".
726 escapeshellarg($this->imagePath) . " " .
727 escapeshellarg($thumbPath);
728 $conv = shell_exec( $cmd );
729 } else {
730 # Use PHP's builtin GD library functions.
731 #
732 # First find out what kind of file this is, and select the correct
733 # input routine for this.
734
735 $truecolor = false;
736
737 switch( $this->type ) {
738 case 1: # GIF
739 $src_image = imagecreatefromgif( $this->imagePath );
740 break;
741 case 2: # JPG
742 $src_image = imagecreatefromjpeg( $this->imagePath );
743 $truecolor = true;
744 break;
745 case 3: # PNG
746 $src_image = imagecreatefrompng( $this->imagePath );
747 $truecolor = ( $this->bits > 8 );
748 break;
749 case 15: # WBMP for WML
750 $src_image = imagecreatefromwbmp( $this->imagePath );
751 break;
752 case 16: # XBM
753 $src_image = imagecreatefromxbm( $this->imagePath );
754 break;
755 default:
756 return 'Image type not supported';
757 break;
758 }
759 if ( $truecolor ) {
760 $dst_image = imagecreatetruecolor( $width, $height );
761 } else {
762 $dst_image = imagecreate( $width, $height );
763 }
764 imagecopyresampled( $dst_image, $src_image,
765 0,0,0,0,
766 $width, $height, $this->width, $this->height );
767 switch( $this->type ) {
768 case 1: # GIF
769 case 3: # PNG
770 case 15: # WBMP
771 case 16: # XBM
772 imagepng( $dst_image, $thumbPath );
773 break;
774 case 2: # JPEG
775 imageinterlace( $dst_image );
776 imagejpeg( $dst_image, $thumbPath, 95 );
777 break;
778 default:
779 break;
780 }
781 imagedestroy( $dst_image );
782 imagedestroy( $src_image );
783 }
784 #
785 # Check for zero-sized thumbnails. Those can be generated when
786 # no disk space is available or some other error occurs
787 #
788 if( file_exists( $thumbPath ) ) {
789 $thumbstat = stat( $thumbPath );
790 if( $thumbstat['size'] == 0 ) {
791 unlink( $thumbPath );
792 }
793 }
794 }
795
796 /**
797 * Get all thumbnail names previously generated for this image
798 */
799 function getThumbnails( $shared = false ) {
800 $this->load();
801 $files = array();
802 $dir = wfImageThumbDir( $this->name, $shared );
803
804 // This generates an error on failure, hence the @
805 $handle = @opendir( $dir );
806
807 if ( $handle ) {
808 while ( false !== ( $file = readdir($handle) ) ) {
809 if ( $file{0} != '.' ) {
810 $files[] = $file;
811 }
812 }
813 closedir( $handle );
814 }
815
816 return $files;
817 }
818
819 /**
820 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
821 */
822 function purgeCache( $archiveFiles = array(), $shared = false ) {
823 global $wgInternalServer, $wgUseSquid;
824
825 // Refresh metadata cache
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;
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 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 = wfTimestampNow();
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' => $dbw->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
994 if ( $dbw->affectedRows() ) {
995 # Successfully inserted, this is a new image
996 $id = $descTitle->getArticleID();
997
998 if ( $id == 0 ) {
999 $article = new Article( $descTitle );
1000 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1001 }
1002 } else {
1003 # Collision, this is an update of an image
1004 # Insert previous contents into oldimage
1005 $dbw->insertSelect( 'oldimage', 'image',
1006 array(
1007 'oi_name' => 'img_name',
1008 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1009 'oi_size' => 'img_size',
1010 'oi_width' => 'img_width',
1011 'oi_height' => 'img_height',
1012 'oi_bits' => 'img_bits',
1013 'oi_type' => 'img_type',
1014 'oi_timestamp' => 'img_timestamp',
1015 'oi_description' => 'img_description',
1016 'oi_user' => 'img_user',
1017 'oi_user_text' => 'img_user_text',
1018 ), array( 'img_name' => $this->name ), $fname
1019 );
1020
1021 # Update the current image row
1022 $dbw->update( 'image',
1023 array( /* SET */
1024 'img_size' => $this->size,
1025 'img_width' => $this->width,
1026 'img_height' => $this->height,
1027 'img_bits' => $this->bits,
1028 'img_type' => $this->type,
1029 'img_timestamp' => $dbw->timestamp(),
1030 'img_user' => $wgUser->getID(),
1031 'img_user_text' => $wgUser->getName(),
1032 'img_description' => $desc,
1033 ), array( /* WHERE */
1034 'img_name' => $this->name
1035 ), $fname
1036 );
1037
1038 # Invalidate the cache for the description page
1039 $descTitle->invalidateCache();
1040 }
1041
1042 $log = new LogPage( 'upload' );
1043 $log->addEntry( 'upload', $descTitle, $desc );
1044
1045 return true;
1046 }
1047
1048 } //class
1049
1050
1051 /**
1052 * Returns the image directory of an image
1053 * If the directory does not exist, it is created.
1054 * The result is an absolute path.
1055 *
1056 * This function is called from thumb.php before Setup.php is included
1057 *
1058 * @param string $fname file name of the image file
1059 * @access public
1060 */
1061 function wfImageDir( $fname ) {
1062 global $wgUploadDirectory, $wgHashedUploadDirectory;
1063
1064 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1065
1066 $hash = md5( $fname );
1067 $oldumask = umask(0);
1068 $dest = $wgUploadDirectory . '/' . $hash{0};
1069 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1070 $dest .= '/' . substr( $hash, 0, 2 );
1071 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1072
1073 umask( $oldumask );
1074 return $dest;
1075 }
1076
1077 /**
1078 * Returns the image directory of an image's thubnail
1079 * If the directory does not exist, it is created.
1080 * The result is an absolute path.
1081 *
1082 * This function is called from thumb.php before Setup.php is included
1083 *
1084 * @param string $fname file name of the original image file
1085 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1086 * @param boolean $shared (optional) use the shared upload directory
1087 * @access public
1088 */
1089 function wfImageThumbDir( $fname, $shared = false ) {
1090 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1091 $dir = "$base/$fname";
1092
1093 if ( !is_dir( $base ) ) {
1094 $oldumask = umask(0);
1095 @mkdir( $base, 0777 );
1096 umask( $oldumask );
1097 }
1098
1099 if ( ! is_dir( $dir ) ) {
1100 $oldumask = umask(0);
1101 @mkdir( $dir, 0777 );
1102 umask( $oldumask );
1103 }
1104
1105 return $dir;
1106 }
1107
1108 /**
1109 * Old thumbnail directory, kept for conversion
1110 */
1111 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1112 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1113 }
1114
1115 /**
1116 * Returns the image directory of an image's old version
1117 * If the directory does not exist, it is created.
1118 * The result is an absolute path.
1119 *
1120 * This function is called from thumb.php before Setup.php is included
1121 *
1122 * @param string $fname file name of the thumbnail file, including file size prefix
1123 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1124 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1125 * @access public
1126 */
1127 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1128 global $wgUploadDirectory, $wgHashedUploadDirectory,
1129 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1130 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1131 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1132 if (!$hashdir) { return $dir.'/'.$subdir; }
1133 $hash = md5( $fname );
1134 $oldumask = umask(0);
1135
1136 # Suppress warning messages here; if the file itself can't
1137 # be written we'll worry about it then.
1138 wfSuppressWarnings();
1139
1140 $archive = $dir.'/'.$subdir;
1141 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1142 $archive .= '/' . $hash{0};
1143 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1144 $archive .= '/' . substr( $hash, 0, 2 );
1145 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1146
1147 wfRestoreWarnings();
1148 umask( $oldumask );
1149 return $archive;
1150 }
1151
1152
1153 /*
1154 * Return the hash path component of an image path (URL or filesystem),
1155 * e.g. "/3/3c/", or just "/" if hashing is not used.
1156 *
1157 * @param $dbkey The filesystem / database name of the file
1158 * @param $fromSharedDirectory Use the shared file repository? It may
1159 * use different hash settings from the local one.
1160 */
1161 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1162 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1163 global $wgHashedUploadDirectory;
1164
1165 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
1166 $wgHashedUploadDirectory;
1167 if($ishashed) {
1168 $hash = md5($dbkey);
1169 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1170 } else {
1171 return '/';
1172 }
1173 }
1174
1175 /**
1176 * Returns the image URL of an image's old version
1177 *
1178 * @param string $fname file name of the image file
1179 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1180 * @access public
1181 */
1182 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1183 global $wgUploadPath, $wgHashedUploadDirectory;
1184
1185 if ($wgHashedUploadDirectory) {
1186 $hash = md5( substr( $name, 15) );
1187 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1188 substr( $hash, 0, 2 ) . '/'.$name;
1189 } else {
1190 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1191 }
1192 return wfUrlencode($url);
1193 }
1194
1195 /**
1196 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1197 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1198 *
1199 * @param string $length
1200 * @return int Length in pixels
1201 */
1202 function wfScaleSVGUnit( $length ) {
1203 static $unitLength = array(
1204 'px' => 1.0,
1205 'pt' => 1.25,
1206 'pc' => 15.0,
1207 'mm' => 3.543307,
1208 'cm' => 35.43307,
1209 'in' => 90.0,
1210 '' => 1.0, // "User units" pixels by default
1211 '%' => 2.0, // Fake it!
1212 );
1213 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1214 $length = FloatVal( $matches[1] );
1215 $unit = $matches[2];
1216 return round( $length * $unitLength[$unit] );
1217 } else {
1218 // Assume pixels
1219 return round( FloatVal( $length ) );
1220 }
1221 }
1222
1223 /**
1224 * Compatible with PHP getimagesize()
1225 * @todo support gzipped SVGZ
1226 * @todo check XML more carefully
1227 * @todo sensible defaults
1228 *
1229 * @param string $filename
1230 * @return array
1231 */
1232 function wfGetSVGsize( $filename ) {
1233 $width = 256;
1234 $height = 256;
1235
1236 // Read a chunk of the file
1237 $f = fopen( $filename, "rt" );
1238 if( !$f ) return false;
1239 $chunk = fread( $f, 4096 );
1240 fclose( $f );
1241
1242 // Uber-crappy hack! Run through a real XML parser.
1243 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1244 return false;
1245 }
1246 $tag = $matches[1];
1247 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1248 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1249 }
1250 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1251 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1252 }
1253
1254 return array( $width, $height, 'SVG',
1255 "width=\"$width\" height=\"$height\"" );
1256 }
1257
1258 /**
1259 * Is an image on the bad image list?
1260 */
1261 function wfIsBadImage( $name ) {
1262 global $wgLang;
1263
1264 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1265 foreach ( $lines as $line ) {
1266 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1267 $t = Title::newFromText( $m[1] );
1268 if ( $t->getDBkey() == $name ) {
1269 return true;
1270 }
1271 }
1272 }
1273 return false;
1274 }
1275
1276
1277
1278 /**
1279 * Wrapper class for thumbnail images
1280 * @package MediaWiki
1281 */
1282 class ThumbnailImage {
1283 /**
1284 * @param string $path Filesystem path to the thumb
1285 * @param string $url URL path to the thumb
1286 * @access private
1287 */
1288 function ThumbnailImage( $url, $width, $height, $path = false ) {
1289 $this->url = $url;
1290 $this->width = $width;
1291 $this->height = $height;
1292 $this->path = $path;
1293 }
1294
1295 /**
1296 * @return string The thumbnail URL
1297 */
1298 function getUrl() {
1299 return $this->url;
1300 }
1301
1302 /**
1303 * Return HTML <img ... /> tag for the thumbnail, will include
1304 * width and height attributes and a blank alt text (as required).
1305 *
1306 * You can set or override additional attributes by passing an
1307 * associative array of name => data pairs. The data will be escaped
1308 * for HTML output, so should be in plaintext.
1309 *
1310 * @param array $attribs
1311 * @return string
1312 * @access public
1313 */
1314 function toHtml( $attribs = array() ) {
1315 $attribs['src'] = $this->url;
1316 $attribs['width'] = $this->width;
1317 $attribs['height'] = $this->height;
1318 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1319
1320 $html = '<img ';
1321 foreach( $attribs as $name => $data ) {
1322 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1323 }
1324 $html .= '/>';
1325 return $html;
1326 }
1327
1328 }
1329 ?>