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