Don't check if the thumbnail file exists if $wgGenerateThumbnailOnParse=false. Ineffi...
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 */
4
5 /**
6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
9 *
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
12 */
13
14 /**
15 * Bump this number when serialized cache records may be incompatible.
16 */
17 define( 'MW_IMAGE_VERSION', 2 );
18
19 /**
20 * Class to represent an image
21 *
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
24 *
25 * @addtogroup Media
26 */
27 class Image
28 {
29 const DELETED_FILE = 1;
30 const DELETED_COMMENT = 2;
31 const DELETED_USER = 4;
32 const DELETED_RESTRICTED = 8;
33 const RENDER_NOW = 1;
34
35 /**#@+
36 * @private
37 */
38 var $name, # name of the image (constructor)
39 $imagePath, # Path of the image (loadFromXxx)
40 $url, # Image URL (accessor)
41 $title, # Title object for this image (constructor)
42 $fileExists, # does the image file exist on disk? (loadFromXxx)
43 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
44 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
45 $historyRes, # result of the query for the image's history (nextHistoryLine)
46 $width, # \
47 $height, # |
48 $bits, # --- returned by getimagesize (loadFromXxx)
49 $attr, # /
50 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
51 $mime, # MIME type, determined by MimeMagic::guessMimeType
52 $extension, # The file extension (constructor)
53 $size, # Size in bytes (loadFromXxx)
54 $metadata, # Metadata
55 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
56 $page, # Page to render when creating thumbnails
57 $lastError; # Error string associated with a thumbnail display error
58
59
60 /**#@-*/
61
62 /**
63 * Create an Image object from an image name
64 *
65 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
66 * @public
67 */
68 public static function newFromName( $name ) {
69 $title = Title::makeTitleSafe( NS_IMAGE, $name );
70 if ( is_object( $title ) ) {
71 return new Image( $title );
72 } else {
73 return NULL;
74 }
75 }
76
77 /**
78 * Obsolete factory function, use constructor
79 * @deprecated
80 */
81 function newFromTitle( $title ) {
82 return new Image( $title );
83 }
84
85 function Image( $title ) {
86 if( !is_object( $title ) ) {
87 throw new MWException( 'Image constructor given bogus title.' );
88 }
89 $this->title =& $title;
90 $this->name = $title->getDBkey();
91 $this->metadata = '';
92
93 $n = strrpos( $this->name, '.' );
94 $this->extension = Image::normalizeExtension( $n ?
95 substr( $this->name, $n + 1 ) : '' );
96 $this->historyLine = 0;
97
98 $this->dataLoaded = false;
99 }
100
101 /**
102 * Normalize a file extension to the common form, and ensure it's clean.
103 * Extensions with non-alphanumeric characters will be discarded.
104 *
105 * @param $ext string (without the .)
106 * @return string
107 */
108 static function normalizeExtension( $ext ) {
109 $lower = strtolower( $ext );
110 $squish = array(
111 'htm' => 'html',
112 'jpeg' => 'jpg',
113 'mpeg' => 'mpg',
114 'tiff' => 'tif' );
115 if( isset( $squish[$lower] ) ) {
116 return $squish[$lower];
117 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
118 return $lower;
119 } else {
120 return '';
121 }
122 }
123
124 /**
125 * Get the memcached keys
126 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
127 */
128 function getCacheKeys( ) {
129 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
130
131 $hashedName = md5($this->name);
132 $keys = array( wfMemcKey( 'Image', $hashedName ) );
133 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
134 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
135 }
136 return $keys;
137 }
138
139 /**
140 * Try to load image metadata from memcached. Returns true on success.
141 */
142 function loadFromCache() {
143 global $wgUseSharedUploads, $wgMemc;
144 wfProfileIn( __METHOD__ );
145 $this->dataLoaded = false;
146 $keys = $this->getCacheKeys();
147 $cachedValues = $wgMemc->get( $keys[0] );
148
149 // Check if the key existed and belongs to this version of MediaWiki
150 if (!empty($cachedValues) && is_array($cachedValues)
151 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
152 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
153 {
154 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
155 # if this is shared file, we need to check if image
156 # in shared repository has not changed
157 if ( isset( $keys[1] ) ) {
158 $commonsCachedValues = $wgMemc->get( $keys[1] );
159 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
160 && isset($commonsCachedValues['version'])
161 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
162 && isset($commonsCachedValues['mime'])) {
163 wfDebug( "Pulling image metadata from shared repository cache\n" );
164 $this->name = $commonsCachedValues['name'];
165 $this->imagePath = $commonsCachedValues['imagePath'];
166 $this->fileExists = $commonsCachedValues['fileExists'];
167 $this->width = $commonsCachedValues['width'];
168 $this->height = $commonsCachedValues['height'];
169 $this->bits = $commonsCachedValues['bits'];
170 $this->type = $commonsCachedValues['type'];
171 $this->mime = $commonsCachedValues['mime'];
172 $this->metadata = $commonsCachedValues['metadata'];
173 $this->size = $commonsCachedValues['size'];
174 $this->fromSharedDirectory = true;
175 $this->dataLoaded = true;
176 $this->imagePath = $this->getFullPath(true);
177 }
178 }
179 } else {
180 wfDebug( "Pulling image metadata from local cache\n" );
181 $this->name = $cachedValues['name'];
182 $this->imagePath = $cachedValues['imagePath'];
183 $this->fileExists = $cachedValues['fileExists'];
184 $this->width = $cachedValues['width'];
185 $this->height = $cachedValues['height'];
186 $this->bits = $cachedValues['bits'];
187 $this->type = $cachedValues['type'];
188 $this->mime = $cachedValues['mime'];
189 $this->metadata = $cachedValues['metadata'];
190 $this->size = $cachedValues['size'];
191 $this->fromSharedDirectory = false;
192 $this->dataLoaded = true;
193 $this->imagePath = $this->getFullPath();
194 }
195 }
196 if ( $this->dataLoaded ) {
197 wfIncrStats( 'image_cache_hit' );
198 } else {
199 wfIncrStats( 'image_cache_miss' );
200 }
201
202 wfProfileOut( __METHOD__ );
203 return $this->dataLoaded;
204 }
205
206 /**
207 * Save the image metadata to memcached
208 */
209 function saveToCache() {
210 global $wgMemc, $wgUseSharedUploads;
211 $this->load();
212 $keys = $this->getCacheKeys();
213 // We can't cache negative metadata for non-existent files,
214 // because if the file later appears in commons, the local
215 // keys won't be purged.
216 if ( $this->fileExists || !$wgUseSharedUploads ) {
217 $cachedValues = array(
218 'version' => MW_IMAGE_VERSION,
219 'name' => $this->name,
220 'imagePath' => $this->imagePath,
221 'fileExists' => $this->fileExists,
222 'fromShared' => $this->fromSharedDirectory,
223 'width' => $this->width,
224 'height' => $this->height,
225 'bits' => $this->bits,
226 'type' => $this->type,
227 'mime' => $this->mime,
228 'metadata' => $this->metadata,
229 'size' => $this->size );
230
231 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
232 } else {
233 // However we should clear them, so they aren't leftover
234 // if we've deleted the file.
235 $wgMemc->delete( $keys[0] );
236 }
237 }
238
239 /**
240 * Load metadata from the file itself
241 */
242 function loadFromFile() {
243 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
244 wfProfileIn( __METHOD__ );
245 $this->imagePath = $this->getFullPath();
246 $this->fileExists = file_exists( $this->imagePath );
247 $this->fromSharedDirectory = false;
248 $gis = array();
249
250 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
251
252 # If the file is not found, and a shared upload directory is used, look for it there.
253 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
254 # In case we're on a wgCapitalLinks=false wiki, we
255 # capitalize the first letter of the filename before
256 # looking it up in the shared repository.
257 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
258 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
259 if ( $this->fileExists ) {
260 $this->name = $sharedImage->name;
261 $this->imagePath = $this->getFullPath(true);
262 $this->fromSharedDirectory = true;
263 }
264 }
265
266
267 if ( $this->fileExists ) {
268 $magic=& MimeMagic::singleton();
269
270 $this->mime = $magic->guessMimeType($this->imagePath,true);
271 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
272 $handler = MediaHandler::getHandler( $this->mime );
273
274 # Get size in bytes
275 $this->size = filesize( $this->imagePath );
276
277 # Height, width and metadata
278 if ( $handler ) {
279 $gis = $handler->getImageSize( $this, $this->imagePath );
280 $this->metadata = $handler->getMetadata( $this, $this->imagePath );
281 } else {
282 $gis = false;
283 $this->metadata = '';
284 }
285
286 wfDebug(__METHOD__.': '.$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
287 }
288 else {
289 $this->mime = NULL;
290 $this->type = MEDIATYPE_UNKNOWN;
291 $this->metadata = '';
292 wfDebug(__METHOD__.': '.$this->imagePath." NOT FOUND!\n");
293 }
294
295 if( $gis ) {
296 $this->width = $gis[0];
297 $this->height = $gis[1];
298 } else {
299 $this->width = 0;
300 $this->height = 0;
301 }
302
303 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
304
305 #NOTE: we have to set this flag early to avoid load() to be called
306 # be some of the functions below. This may lead to recursion or other bad things!
307 # as ther's only one thread of execution, this should be safe anyway.
308 $this->dataLoaded = true;
309
310 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
311 else $this->bits = 0;
312
313 wfProfileOut( __METHOD__ );
314 }
315
316 /**
317 * Load image metadata from the DB
318 */
319 function loadFromDB() {
320 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
321 wfProfileIn( __METHOD__ );
322
323 $dbr = wfGetDB( DB_SLAVE );
324
325 $row = $dbr->selectRow( 'image',
326 array( 'img_size', 'img_width', 'img_height', 'img_bits',
327 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
328 array( 'img_name' => $this->name ), __METHOD__ );
329 if ( $row ) {
330 $this->fromSharedDirectory = false;
331 $this->fileExists = true;
332 $this->loadFromRow( $row );
333 $this->imagePath = $this->getFullPath();
334 // Check for rows from a previous schema, quietly upgrade them
335 $this->maybeUpgradeRow();
336 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
337 # In case we're on a wgCapitalLinks=false wiki, we
338 # capitalize the first letter of the filename before
339 # looking it up in the shared repository.
340 $name = $wgContLang->ucfirst($this->name);
341 $dbc = Image::getCommonsDB();
342
343 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
344 array(
345 'img_size', 'img_width', 'img_height', 'img_bits',
346 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
347 array( 'img_name' => $name ), __METHOD__ );
348 if ( $row ) {
349 $this->fromSharedDirectory = true;
350 $this->fileExists = true;
351 $this->imagePath = $this->getFullPath(true);
352 $this->name = $name;
353 $this->loadFromRow( $row );
354
355 // Check for rows from a previous schema, quietly upgrade them
356 $this->maybeUpgradeRow();
357 }
358 }
359
360 if ( !$row ) {
361 $this->size = 0;
362 $this->width = 0;
363 $this->height = 0;
364 $this->bits = 0;
365 $this->type = 0;
366 $this->fileExists = false;
367 $this->fromSharedDirectory = false;
368 $this->metadata = '';
369 $this->mime = false;
370 }
371
372 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
373 $this->dataLoaded = true;
374 wfProfileOut( __METHOD__ );
375 }
376
377 /*
378 * Load image metadata from a DB result row
379 */
380 function loadFromRow( &$row ) {
381 $this->size = $row->img_size;
382 $this->width = $row->img_width;
383 $this->height = $row->img_height;
384 $this->bits = $row->img_bits;
385 $this->type = $row->img_media_type;
386
387 $major= $row->img_major_mime;
388 $minor= $row->img_minor_mime;
389
390 if (!$major) $this->mime = "unknown/unknown";
391 else {
392 if (!$minor) $minor= "unknown";
393 $this->mime = $major.'/'.$minor;
394 }
395 $this->metadata = $row->img_metadata;
396
397 $this->dataLoaded = true;
398 }
399
400 /**
401 * Load image metadata from cache or DB, unless already loaded
402 */
403 function load() {
404 global $wgSharedUploadDBname, $wgUseSharedUploads;
405 if ( !$this->dataLoaded ) {
406 if ( !$this->loadFromCache() ) {
407 $this->loadFromDB();
408 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
409 $this->loadFromFile();
410 } elseif ( $this->fileExists || !$wgUseSharedUploads ) {
411 // We can do negative caching for local images, because the cache
412 // will be purged on upload. But we can't do it when shared images
413 // are enabled, since updates to that won't purge foreign caches.
414 $this->saveToCache();
415 }
416 }
417 $this->dataLoaded = true;
418 }
419 }
420
421 /**
422 * Upgrade a row if it needs it
423 */
424 function maybeUpgradeRow() {
425 if ( is_null($this->type) || $this->mime == 'image/svg' ) {
426 $this->upgradeRow();
427 } else {
428 $handler = $this->getHandler();
429 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
430 $this->upgradeRow();
431 }
432 }
433 }
434
435 /**
436 * Fix assorted version-related problems with the image row by reloading it from the file
437 */
438 function upgradeRow() {
439 global $wgDBname, $wgSharedUploadDBname;
440 wfProfileIn( __METHOD__ );
441
442 $this->loadFromFile();
443
444 if ( $this->fromSharedDirectory ) {
445 if ( !$wgSharedUploadDBname ) {
446 wfProfileOut( __METHOD__ );
447 return;
448 }
449
450 // Write to the other DB using selectDB, not database selectors
451 // This avoids breaking replication in MySQL
452 $dbw = Image::getCommonsDB();
453 } else {
454 $dbw = wfGetDB( DB_MASTER );
455 }
456
457 list( $major, $minor ) = self::splitMime( $this->mime );
458
459 wfDebug(__METHOD__.': upgrading '.$this->name." to the current schema\n");
460
461 $dbw->update( 'image',
462 array(
463 'img_width' => $this->width,
464 'img_height' => $this->height,
465 'img_bits' => $this->bits,
466 'img_media_type' => $this->type,
467 'img_major_mime' => $major,
468 'img_minor_mime' => $minor,
469 'img_metadata' => $this->metadata,
470 ), array( 'img_name' => $this->name ), __METHOD__
471 );
472 if ( $this->fromSharedDirectory ) {
473 $dbw->selectDB( $wgDBname );
474 }
475 wfProfileOut( __METHOD__ );
476 }
477
478 /**
479 * Split an internet media type into its two components; if not
480 * a two-part name, set the minor type to 'unknown'.
481 *
482 * @param $mime "text/html" etc
483 * @return array ("text", "html") etc
484 */
485 static function splitMime( $mime ) {
486 if( strpos( $mime, '/' ) !== false ) {
487 return explode( '/', $mime, 2 );
488 } else {
489 return array( $mime, 'unknown' );
490 }
491 }
492
493 /**
494 * Return the name of this image
495 * @public
496 */
497 function getName() {
498 return $this->name;
499 }
500
501 /**
502 * Return the associated title object
503 * @public
504 */
505 function getTitle() {
506 return $this->title;
507 }
508
509 /**
510 * Return the URL of the image file
511 * @public
512 */
513 function getURL() {
514 if ( !$this->url ) {
515 $this->load();
516 if($this->fileExists) {
517 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
518 } else {
519 $this->url = '';
520 }
521 }
522 return $this->url;
523 }
524
525 function getViewURL() {
526 if( $this->mustRender()) {
527 if( $this->canRender() ) {
528 return $this->createThumb( $this->getWidth() );
529 }
530 else {
531 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
532 return $this->getURL(); #hm... return NULL?
533 }
534 } else {
535 return $this->getURL();
536 }
537 }
538
539 /**
540 * Return the image path of the image in the
541 * local file system as an absolute path
542 * @public
543 */
544 function getImagePath() {
545 $this->load();
546 return $this->imagePath;
547 }
548
549 /**
550 * Return the width of the image
551 *
552 * Returns false on error
553 * @public
554 */
555 function getWidth( $page = 1 ) {
556 $this->load();
557 if ( $this->isMultipage() ) {
558 $dim = $this->getHandler()->getPageDimensions( $this, $page );
559 if ( $dim ) {
560 return $dim['width'];
561 } else {
562 return false;
563 }
564 } else {
565 return $this->width;
566 }
567 }
568
569 /**
570 * Return the height of the image
571 *
572 * Returns false on error
573 * @public
574 */
575 function getHeight( $page = 1 ) {
576 $this->load();
577 if ( $this->isMultipage() ) {
578 $dim = $this->getHandler()->getPageDimensions( $this, $page );
579 if ( $dim ) {
580 return $dim['height'];
581 } else {
582 return false;
583 }
584 } else {
585 return $this->height;
586 }
587 }
588
589 /**
590 * Get handler-specific metadata
591 */
592 function getMetadata() {
593 $this->load();
594 return $this->metadata;
595 }
596
597 /**
598 * Return the size of the image file, in bytes
599 * @public
600 */
601 function getSize() {
602 $this->load();
603 return $this->size;
604 }
605
606 /**
607 * Returns the mime type of the file.
608 */
609 function getMimeType() {
610 $this->load();
611 return $this->mime;
612 }
613
614 /**
615 * Return the type of the media in the file.
616 * Use the value returned by this function with the MEDIATYPE_xxx constants.
617 */
618 function getMediaType() {
619 $this->load();
620 return $this->type;
621 }
622
623 /**
624 * Checks if the file can be presented to the browser as a bitmap.
625 *
626 * Currently, this checks if the file is an image format
627 * that can be converted to a format
628 * supported by all browsers (namely GIF, PNG and JPEG),
629 * or if it is an SVG image and SVG conversion is enabled.
630 *
631 * @todo remember the result of this check.
632 */
633 function canRender() {
634 $handler = $this->getHandler();
635 return $handler && $handler->canRender();
636 }
637
638 /**
639 * Return true if the file is of a type that can't be directly
640 * rendered by typical browsers and needs to be re-rasterized.
641 *
642 * This returns true for everything but the bitmap types
643 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
644 * also return true for any non-image formats.
645 *
646 * @return bool
647 */
648 function mustRender() {
649 $handler = $this->getHandler();
650 return $handler && $handler->mustRender();
651 }
652
653 /**
654 * Determines if this media file may be shown inline on a page.
655 *
656 * This is currently synonymous to canRender(), but this could be
657 * extended to also allow inline display of other media,
658 * like flash animations or videos. If you do so, please keep in mind that
659 * that could be a security risk.
660 */
661 function allowInlineDisplay() {
662 return $this->canRender();
663 }
664
665 /**
666 * Determines if this media file is in a format that is unlikely to
667 * contain viruses or malicious content. It uses the global
668 * $wgTrustedMediaFormats list to determine if the file is safe.
669 *
670 * This is used to show a warning on the description page of non-safe files.
671 * It may also be used to disallow direct [[media:...]] links to such files.
672 *
673 * Note that this function will always return true if allowInlineDisplay()
674 * or isTrustedFile() is true for this file.
675 */
676 function isSafeFile() {
677 if ($this->allowInlineDisplay()) return true;
678 if ($this->isTrustedFile()) return true;
679
680 global $wgTrustedMediaFormats;
681
682 $type= $this->getMediaType();
683 $mime= $this->getMimeType();
684 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
685
686 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
687 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
688
689 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
690 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
691
692 return false;
693 }
694
695 /** Returns true if the file is flagged as trusted. Files flagged that way
696 * can be linked to directly, even if that is not allowed for this type of
697 * file normally.
698 *
699 * This is a dummy function right now and always returns false. It could be
700 * implemented to extract a flag from the database. The trusted flag could be
701 * set on upload, if the user has sufficient privileges, to bypass script-
702 * and html-filters. It may even be coupled with cryptographics signatures
703 * or such.
704 */
705 function isTrustedFile() {
706 #this could be implemented to check a flag in the databas,
707 #look for signatures, etc
708 return false;
709 }
710
711 /**
712 * Return the escapeLocalURL of this image
713 * @public
714 */
715 function getEscapeLocalURL( $query=false) {
716 return $this->getTitle()->escapeLocalURL( $query );
717 }
718
719 /**
720 * Return the escapeFullURL of this image
721 * @public
722 */
723 function getEscapeFullURL() {
724 $this->getTitle();
725 return $this->title->escapeFullURL();
726 }
727
728 /**
729 * Return the URL of an image, provided its name.
730 *
731 * @param string $name Name of the image, without the leading "Image:"
732 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
733 * @return string URL of $name image
734 * @public
735 */
736 static function imageUrl( $name, $fromSharedDirectory = false ) {
737 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
738 if($fromSharedDirectory) {
739 $base = '';
740 $path = $wgSharedUploadPath;
741 } else {
742 $base = $wgUploadBaseUrl;
743 $path = $wgUploadPath;
744 }
745 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
746 return wfUrlencode( $url );
747 }
748
749 /**
750 * Returns true if the image file exists on disk.
751 * @return boolean Whether image file exist on disk.
752 * @public
753 */
754 function exists() {
755 $this->load();
756 return $this->fileExists;
757 }
758
759 /**
760 * @todo document
761 * @private
762 */
763 function thumbUrlFromName( $thumbName, $subdir = 'thumb' ) {
764 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
765 if($this->fromSharedDirectory) {
766 $base = '';
767 $path = $wgSharedUploadPath;
768 } else {
769 $base = $wgUploadBaseUrl;
770 $path = $wgUploadPath;
771 }
772 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
773 $hashdir = wfGetHashPath($this->name, $this->fromSharedDirectory) .
774 wfUrlencode( $this->name );
775 } else {
776 $hashdir = '';
777 }
778 $url = "{$base}{$path}/{$subdir}{$hashdir}/" . wfUrlencode( $thumbName );
779 return $url;
780 }
781
782 /**
783 * @deprecated Use $image->transform()->getUrl() or thumbUrlFromName()
784 */
785 function thumbUrl( $width, $subdir = 'thumb' ) {
786 $name = $this->thumbName( array( 'width' => $width ) );
787 if ( strval( $name ) !== '' ) {
788 return array( false, $this->thumbUrlFromName( $name, $subdir ) );
789 } else {
790 return array( false, false );
791 }
792 }
793
794 function getTransformScript() {
795 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
796 if ( $this->fromSharedDirectory ) {
797 $script = $wgSharedThumbnailScriptPath;
798 } else {
799 $script = $wgThumbnailScriptPath;
800 }
801 if ( $script ) {
802 return "$script?f=" . urlencode( $this->name );
803 } else {
804 return false;
805 }
806 }
807
808 /**
809 * Get a ThumbnailImage which is the same size as the source
810 */
811 function getUnscaledThumb( $page = false ) {
812 if ( $page ) {
813 $params = array(
814 'page' => $page,
815 'width' => $this->getWidth( $page )
816 );
817 } else {
818 $params = array( 'width' => $this->getWidth() );
819 }
820 return $this->transform( $params );
821 }
822
823 /**
824 * Return the file name of a thumbnail with the specified parameters
825 *
826 * @param array $params Handler-specific parameters
827 * @private
828 */
829 function thumbName( $params ) {
830 $handler = $this->getHandler();
831 if ( !$handler ) {
832 return null;
833 }
834 list( $thumbExt, /* $thumbMime */ ) = self::getThumbType( $this->extension, $this->mime );
835 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name;
836 if ( $thumbExt != $this->extension ) {
837 $thumbName .= ".$thumbExt";
838 }
839 return $thumbName;
840 }
841
842 /**
843 * Create a thumbnail of the image having the specified width/height.
844 * The thumbnail will not be created if the width is larger than the
845 * image's width. Let the browser do the scaling in this case.
846 * The thumbnail is stored on disk and is only computed if the thumbnail
847 * file does not exist OR if it is older than the image.
848 * Returns the URL.
849 *
850 * Keeps aspect ratio of original image. If both width and height are
851 * specified, the generated image will be no bigger than width x height,
852 * and will also have correct aspect ratio.
853 *
854 * @param integer $width maximum width of the generated thumbnail
855 * @param integer $height maximum height of the image (optional)
856 * @public
857 */
858 function createThumb( $width, $height = -1 ) {
859 $params = array( 'width' => $width );
860 if ( $height != -1 ) {
861 $params['height'] = $height;
862 }
863 $thumb = $this->transform( $params );
864 if( is_null( $thumb ) || $thumb->isError() ) return '';
865 return $thumb->getUrl();
866 }
867
868 /**
869 * As createThumb, but returns a ThumbnailImage object. This can
870 * provide access to the actual file, the real size of the thumb,
871 * and can produce a convenient <img> tag for you.
872 *
873 * For non-image formats, this may return a filetype-specific icon.
874 *
875 * @param integer $width maximum width of the generated thumbnail
876 * @param integer $height maximum height of the image (optional)
877 * @param boolean $render True to render the thumbnail if it doesn't exist,
878 * false to just return the URL
879 *
880 * @return ThumbnailImage or null on failure
881 * @public
882 *
883 * @deprecated use transform()
884 */
885 function getThumbnail( $width, $height=-1, $render = true ) {
886 $params = array( 'width' => $width );
887 if ( $height != -1 ) {
888 $params['height'] = $height;
889 }
890 $flags = $render ? self::RENDER_NOW : 0;
891 return $this->transform( $params, $flags );
892 }
893
894 /**
895 * Transform a media file
896 *
897 * @param array $params An associative array of handler-specific parameters. Typical
898 * keys are width, height and page.
899 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
900 * @return MediaTransformOutput
901 */
902 function transform( $params, $flags = 0 ) {
903 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
904
905 wfProfileIn( __METHOD__ );
906 do {
907 $handler = $this->getHandler();
908 if ( !$handler || !$handler->canRender() ) {
909 // not a bitmap or renderable image, don't try.
910 $thumb = $this->iconThumb();
911 break;
912 }
913
914 $script = $this->getTransformScript();
915 if ( $script && !($flags & self::RENDER_NOW) ) {
916 // Use a script to transform on client request
917 $thumb = $handler->getScriptedTransform( $this, $script, $params );
918 break;
919 }
920
921 $normalisedParams = $params;
922 $handler->normaliseParams( $this, $normalisedParams );
923 list( $thumbExt, $thumbMime ) = self::getThumbType( $this->extension, $this->mime );
924 $thumbName = $this->thumbName( $normalisedParams );
925 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ) . "/$thumbName";
926 $thumbUrl = $this->thumbUrlFromName( $thumbName );
927
928 $this->migrateThumbFile( $thumbName );
929
930 if ( !$wgGenerateThumbnailOnParse && !($flags & self::RENDER_NOW ) ) {
931 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
932 break;
933 }
934 if ( file_exists( $thumbPath ) ) {
935 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
936 break;
937 }
938
939 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
940
941 // Ignore errors if requested
942 if ( !$thumb ) {
943 $thumb = null;
944 } elseif ( $thumb->isError() ) {
945 $this->lastError = $thumb->toText();
946 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
947 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
948 }
949 }
950
951 if ( $wgUseSquid ) {
952 wfPurgeSquidServers( array( $thumbUrl ) );
953 }
954 } while (false);
955
956 wfProfileOut( __METHOD__ );
957 return $thumb;
958 }
959
960 /**
961 * Fix thumbnail files from 1.4 or before, with extreme prejudice
962 */
963 function migrateThumbFile( $thumbName ) {
964 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
965 $thumbPath = "$thumbDir/$thumbName";
966 if ( is_dir( $thumbPath ) ) {
967 // Directory where file should be
968 // This happened occasionally due to broken migration code in 1.5
969 // Rename to broken-*
970 global $wgUploadDirectory;
971 for ( $i = 0; $i < 100 ; $i++ ) {
972 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
973 if ( !file_exists( $broken ) ) {
974 rename( $thumbPath, $broken );
975 break;
976 }
977 }
978 // Doesn't exist anymore
979 clearstatcache();
980 }
981 if ( is_file( $thumbDir ) ) {
982 // File where directory should be
983 unlink( $thumbDir );
984 // Doesn't exist anymore
985 clearstatcache();
986 }
987 }
988
989 /**
990 * Get a MediaHandler instance for this image
991 */
992 function getHandler() {
993 return MediaHandler::getHandler( $this->getMimeType() );
994 }
995
996 /**
997 * Get a ThumbnailImage representing a file type icon
998 * @return ThumbnailImage
999 */
1000 function iconThumb() {
1001 global $wgStylePath, $wgStyleDirectory;
1002
1003 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
1004 foreach( $try as $icon ) {
1005 $path = '/common/images/icons/' . $icon;
1006 $filepath = $wgStyleDirectory . $path;
1007 if( file_exists( $filepath ) ) {
1008 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1009 }
1010 }
1011 return null;
1012 }
1013
1014 /**
1015 * Get last thumbnailing error.
1016 * Largely obsolete.
1017 */
1018 function getLastError() {
1019 return $this->lastError;
1020 }
1021
1022 /**
1023 * Get all thumbnail names previously generated for this image
1024 */
1025 function getThumbnails( $shared = false ) {
1026 if ( Image::isHashed( $shared ) ) {
1027 $this->load();
1028 $files = array();
1029 $dir = wfImageThumbDir( $this->name, $shared );
1030
1031 if ( is_dir( $dir ) ) {
1032 $handle = opendir( $dir );
1033
1034 if ( $handle ) {
1035 while ( false !== ( $file = readdir($handle) ) ) {
1036 if ( $file{0} != '.' ) {
1037 $files[] = $file;
1038 }
1039 }
1040 closedir( $handle );
1041 }
1042 }
1043 } else {
1044 $files = array();
1045 }
1046
1047 return $files;
1048 }
1049
1050 /**
1051 * Refresh metadata in memcached, but don't touch thumbnails or squid
1052 */
1053 function purgeMetadataCache() {
1054 clearstatcache();
1055 $this->loadFromFile();
1056 $this->saveToCache();
1057 }
1058
1059 /**
1060 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1061 */
1062 function purgeCache( $archiveFiles = array(), $shared = false ) {
1063 global $wgUseSquid;
1064
1065 // Refresh metadata cache
1066 $this->purgeMetadataCache();
1067
1068 // Delete thumbnails
1069 $files = $this->getThumbnails( $shared );
1070 $dir = wfImageThumbDir( $this->name, $shared );
1071 $urls = array();
1072 foreach ( $files as $file ) {
1073 # Check that the base image name is part of the thumb name
1074 # This is a basic sanity check to avoid erasing unrelated directories
1075 if ( strpos( $file, $this->name ) !== false ) {
1076 $url = $this->thumbUrlFromName( $file );
1077 $urls[] = $url;
1078 @unlink( "$dir/$file" );
1079 }
1080 }
1081
1082 // Purge the squid
1083 if ( $wgUseSquid ) {
1084 $urls[] = $this->getURL();
1085 foreach ( $archiveFiles as $file ) {
1086 $urls[] = wfImageArchiveUrl( $file );
1087 }
1088 wfPurgeSquidServers( $urls );
1089 }
1090 }
1091
1092 /**
1093 * Purge the image description page, but don't go after
1094 * pages using the image. Use when modifying file history
1095 * but not the current data.
1096 */
1097 function purgeDescription() {
1098 $page = Title::makeTitle( NS_IMAGE, $this->name );
1099 $page->invalidateCache();
1100 $page->purgeSquid();
1101 }
1102
1103 /**
1104 * Purge metadata and all affected pages when the image is created,
1105 * deleted, or majorly updated. A set of additional URLs may be
1106 * passed to purge, such as specific image files which have changed.
1107 * @param $urlArray array
1108 */
1109 function purgeEverything( $urlArr=array() ) {
1110 // Delete thumbnails and refresh image metadata cache
1111 $this->purgeCache();
1112 $this->purgeDescription();
1113
1114 // Purge cache of all pages using this image
1115 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1116 $update->doUpdate();
1117 }
1118
1119 /**
1120 * Return the image history of this image, line by line.
1121 * starts with current version, then old versions.
1122 * uses $this->historyLine to check which line to return:
1123 * 0 return line for current version
1124 * 1 query for old versions, return first one
1125 * 2, ... return next old version from above query
1126 *
1127 * @public
1128 */
1129 function nextHistoryLine() {
1130 $dbr = wfGetDB( DB_SLAVE );
1131
1132 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1133 $this->historyRes = $dbr->select( 'image',
1134 array(
1135 'img_size',
1136 'img_description',
1137 'img_user','img_user_text',
1138 'img_timestamp',
1139 'img_width',
1140 'img_height',
1141 "'' AS oi_archive_name"
1142 ),
1143 array( 'img_name' => $this->title->getDBkey() ),
1144 __METHOD__
1145 );
1146 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1147 return FALSE;
1148 }
1149 } else if ( $this->historyLine == 1 ) {
1150 $this->historyRes = $dbr->select( 'oldimage',
1151 array(
1152 'oi_size AS img_size',
1153 'oi_description AS img_description',
1154 'oi_user AS img_user',
1155 'oi_user_text AS img_user_text',
1156 'oi_timestamp AS img_timestamp',
1157 'oi_width as img_width',
1158 'oi_height as img_height',
1159 'oi_archive_name'
1160 ),
1161 array( 'oi_name' => $this->title->getDBkey() ),
1162 __METHOD__,
1163 array( 'ORDER BY' => 'oi_timestamp DESC' )
1164 );
1165 }
1166 $this->historyLine ++;
1167
1168 return $dbr->fetchObject( $this->historyRes );
1169 }
1170
1171 /**
1172 * Reset the history pointer to the first element of the history
1173 * @public
1174 */
1175 function resetHistory() {
1176 $this->historyLine = 0;
1177 }
1178
1179 /**
1180 * Return the full filesystem path to the file. Note that this does
1181 * not mean that a file actually exists under that location.
1182 *
1183 * This path depends on whether directory hashing is active or not,
1184 * i.e. whether the images are all found in the same directory,
1185 * or in hashed paths like /images/3/3c.
1186 *
1187 * @public
1188 * @param boolean $fromSharedDirectory Return the path to the file
1189 * in a shared repository (see $wgUseSharedRepository and related
1190 * options in DefaultSettings.php) instead of a local one.
1191 *
1192 */
1193 function getFullPath( $fromSharedRepository = false ) {
1194 global $wgUploadDirectory, $wgSharedUploadDirectory;
1195
1196 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1197 $wgUploadDirectory;
1198
1199 // $wgSharedUploadDirectory may be false, if thumb.php is used
1200 if ( $dir ) {
1201 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1202 } else {
1203 $fullpath = false;
1204 }
1205
1206 return $fullpath;
1207 }
1208
1209 /**
1210 * @return bool
1211 */
1212 public static function isHashed( $shared ) {
1213 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1214 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1215 }
1216
1217 /**
1218 * Record an image upload in the upload log and the image table
1219 */
1220 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1221 global $wgUser, $wgUseCopyrightUpload;
1222
1223 $dbw = wfGetDB( DB_MASTER );
1224
1225 // Delete thumbnails and refresh the metadata cache
1226 $this->purgeCache();
1227
1228 // Fail now if the image isn't there
1229 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1230 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1231 return false;
1232 }
1233
1234 if ( $wgUseCopyrightUpload ) {
1235 if ( $license != '' ) {
1236 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1237 }
1238 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1239 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1240 "$licensetxt" .
1241 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1242 } else {
1243 if ( $license != '' ) {
1244 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1245 $textdesc = $filedesc .
1246 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1247 } else {
1248 $textdesc = $desc;
1249 }
1250 }
1251
1252 $now = $dbw->timestamp();
1253
1254 #split mime type
1255 if (strpos($this->mime,'/')!==false) {
1256 list($major,$minor)= explode('/',$this->mime,2);
1257 }
1258 else {
1259 $major= $this->mime;
1260 $minor= "unknown";
1261 }
1262
1263 # Test to see if the row exists using INSERT IGNORE
1264 # This avoids race conditions by locking the row until the commit, and also
1265 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1266 $dbw->insert( 'image',
1267 array(
1268 'img_name' => $this->name,
1269 'img_size'=> $this->size,
1270 'img_width' => intval( $this->width ),
1271 'img_height' => intval( $this->height ),
1272 'img_bits' => $this->bits,
1273 'img_media_type' => $this->type,
1274 'img_major_mime' => $major,
1275 'img_minor_mime' => $minor,
1276 'img_timestamp' => $now,
1277 'img_description' => $desc,
1278 'img_user' => $wgUser->getID(),
1279 'img_user_text' => $wgUser->getName(),
1280 'img_metadata' => $this->metadata,
1281 ),
1282 __METHOD__,
1283 'IGNORE'
1284 );
1285
1286 if( $dbw->affectedRows() == 0 ) {
1287 # Collision, this is an update of an image
1288 # Insert previous contents into oldimage
1289 $dbw->insertSelect( 'oldimage', 'image',
1290 array(
1291 'oi_name' => 'img_name',
1292 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1293 'oi_size' => 'img_size',
1294 'oi_width' => 'img_width',
1295 'oi_height' => 'img_height',
1296 'oi_bits' => 'img_bits',
1297 'oi_timestamp' => 'img_timestamp',
1298 'oi_description' => 'img_description',
1299 'oi_user' => 'img_user',
1300 'oi_user_text' => 'img_user_text',
1301 ), array( 'img_name' => $this->name ), __METHOD__
1302 );
1303
1304 # Update the current image row
1305 $dbw->update( 'image',
1306 array( /* SET */
1307 'img_size' => $this->size,
1308 'img_width' => intval( $this->width ),
1309 'img_height' => intval( $this->height ),
1310 'img_bits' => $this->bits,
1311 'img_media_type' => $this->type,
1312 'img_major_mime' => $major,
1313 'img_minor_mime' => $minor,
1314 'img_timestamp' => $now,
1315 'img_description' => $desc,
1316 'img_user' => $wgUser->getID(),
1317 'img_user_text' => $wgUser->getName(),
1318 'img_metadata' => $this->metadata,
1319 ), array( /* WHERE */
1320 'img_name' => $this->name
1321 ), __METHOD__
1322 );
1323 } else {
1324 # This is a new image
1325 # Update the image count
1326 $site_stats = $dbw->tableName( 'site_stats' );
1327 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1328 }
1329
1330 $descTitle = $this->getTitle();
1331 $article = new Article( $descTitle );
1332 $minor = false;
1333 $watch = $watch || $wgUser->isWatched( $descTitle );
1334 $suppressRC = true; // There's already a log entry, so don't double the RC load
1335
1336 if( $descTitle->exists() ) {
1337 // TODO: insert a null revision into the page history for this update.
1338 if( $watch ) {
1339 $wgUser->addWatch( $descTitle );
1340 }
1341
1342 # Invalidate the cache for the description page
1343 $descTitle->invalidateCache();
1344 $descTitle->purgeSquid();
1345 } else {
1346 // New image; create the description page.
1347 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1348 }
1349
1350 # Hooks, hooks, the magic of hooks...
1351 wfRunHooks( 'FileUpload', array( $this ) );
1352
1353 # Add the log entry
1354 $log = new LogPage( 'upload' );
1355 $log->addEntry( 'upload', $descTitle, $desc );
1356
1357 # Commit the transaction now, in case something goes wrong later
1358 # The most important thing is that images don't get lost, especially archives
1359 $dbw->immediateCommit();
1360
1361 # Invalidate cache for all pages using this image
1362 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1363 $update->doUpdate();
1364
1365 return true;
1366 }
1367
1368 /**
1369 * Get an array of Title objects which are articles which use this image
1370 * Also adds their IDs to the link cache
1371 *
1372 * This is mostly copied from Title::getLinksTo()
1373 *
1374 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1375 */
1376 function getLinksTo( $options = '' ) {
1377 wfProfileIn( __METHOD__ );
1378
1379 if ( $options ) {
1380 $db = wfGetDB( DB_MASTER );
1381 } else {
1382 $db = wfGetDB( DB_SLAVE );
1383 }
1384 $linkCache =& LinkCache::singleton();
1385
1386 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1387 $encName = $db->addQuotes( $this->name );
1388 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1389 $res = $db->query( $sql, __METHOD__ );
1390
1391 $retVal = array();
1392 if ( $db->numRows( $res ) ) {
1393 while ( $row = $db->fetchObject( $res ) ) {
1394 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1395 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1396 $retVal[] = $titleObj;
1397 }
1398 }
1399 }
1400 $db->freeResult( $res );
1401 wfProfileOut( __METHOD__ );
1402 return $retVal;
1403 }
1404
1405 function getExifData() {
1406 $handler = $this->getHandler();
1407 if ( !$handler || $handler->getMetadataType( $this ) != 'exif' ) {
1408 return array();
1409 }
1410 if ( !$this->metadata ) {
1411 return array();
1412 }
1413 $exif = unserialize( $this->metadata );
1414 if ( !$exif ) {
1415 return array();
1416 }
1417 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
1418 $format = new FormatExif( $exif );
1419
1420 return $format->getFormattedData();
1421 }
1422
1423 /**
1424 * Returns true if the image does not come from the shared
1425 * image repository.
1426 *
1427 * @return bool
1428 */
1429 function isLocal() {
1430 return !$this->fromSharedDirectory;
1431 }
1432
1433 /**
1434 * Was this image ever deleted from the wiki?
1435 *
1436 * @return bool
1437 */
1438 function wasDeleted() {
1439 $title = Title::makeTitle( NS_IMAGE, $this->name );
1440 return ( $title->isDeleted() > 0 );
1441 }
1442
1443 /**
1444 * Delete all versions of the image.
1445 *
1446 * Moves the files into an archive directory (or deletes them)
1447 * and removes the database rows.
1448 *
1449 * Cache purging is done; logging is caller's responsibility.
1450 *
1451 * @param $reason
1452 * @return true on success, false on some kind of failure
1453 */
1454 function delete( $reason, $suppress=false ) {
1455 $transaction = new FSTransaction();
1456 $urlArr = array( $this->getURL() );
1457
1458 if( !FileStore::lock() ) {
1459 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1460 return false;
1461 }
1462
1463 try {
1464 $dbw = wfGetDB( DB_MASTER );
1465 $dbw->begin();
1466
1467 // Delete old versions
1468 $result = $dbw->select( 'oldimage',
1469 array( 'oi_archive_name' ),
1470 array( 'oi_name' => $this->name ) );
1471
1472 while( $row = $dbw->fetchObject( $result ) ) {
1473 $oldName = $row->oi_archive_name;
1474
1475 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1476
1477 // We'll need to purge this URL from caches...
1478 $urlArr[] = wfImageArchiveUrl( $oldName );
1479 }
1480 $dbw->freeResult( $result );
1481
1482 // And the current version...
1483 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1484
1485 $dbw->immediateCommit();
1486 } catch( MWException $e ) {
1487 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1488 $transaction->rollback();
1489 FileStore::unlock();
1490 throw $e;
1491 }
1492
1493 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1494 $transaction->commit();
1495 FileStore::unlock();
1496
1497
1498 // Update site_stats
1499 $site_stats = $dbw->tableName( 'site_stats' );
1500 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1501
1502 $this->purgeEverything( $urlArr );
1503
1504 return true;
1505 }
1506
1507
1508 /**
1509 * Delete an old version of the image.
1510 *
1511 * Moves the file into an archive directory (or deletes it)
1512 * and removes the database row.
1513 *
1514 * Cache purging is done; logging is caller's responsibility.
1515 *
1516 * @param $reason
1517 * @throws MWException or FSException on database or filestore failure
1518 * @return true on success, false on some kind of failure
1519 */
1520 function deleteOld( $archiveName, $reason, $suppress=false ) {
1521 $transaction = new FSTransaction();
1522 $urlArr = array();
1523
1524 if( !FileStore::lock() ) {
1525 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1526 return false;
1527 }
1528
1529 $transaction = new FSTransaction();
1530 try {
1531 $dbw = wfGetDB( DB_MASTER );
1532 $dbw->begin();
1533 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1534 $dbw->immediateCommit();
1535 } catch( MWException $e ) {
1536 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1537 $transaction->rollback();
1538 FileStore::unlock();
1539 throw $e;
1540 }
1541
1542 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1543 $transaction->commit();
1544 FileStore::unlock();
1545
1546 $this->purgeDescription();
1547
1548 // Squid purging
1549 global $wgUseSquid;
1550 if ( $wgUseSquid ) {
1551 $urlArr = array(
1552 wfImageArchiveUrl( $archiveName ),
1553 );
1554 wfPurgeSquidServers( $urlArr );
1555 }
1556 return true;
1557 }
1558
1559 /**
1560 * Delete the current version of a file.
1561 * May throw a database error.
1562 * @return true on success, false on failure
1563 */
1564 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1565 return $this->prepareDeleteVersion(
1566 $this->getFullPath(),
1567 $reason,
1568 'image',
1569 array(
1570 'fa_name' => 'img_name',
1571 'fa_archive_name' => 'NULL',
1572 'fa_size' => 'img_size',
1573 'fa_width' => 'img_width',
1574 'fa_height' => 'img_height',
1575 'fa_metadata' => 'img_metadata',
1576 'fa_bits' => 'img_bits',
1577 'fa_media_type' => 'img_media_type',
1578 'fa_major_mime' => 'img_major_mime',
1579 'fa_minor_mime' => 'img_minor_mime',
1580 'fa_description' => 'img_description',
1581 'fa_user' => 'img_user',
1582 'fa_user_text' => 'img_user_text',
1583 'fa_timestamp' => 'img_timestamp' ),
1584 array( 'img_name' => $this->name ),
1585 $suppress,
1586 __METHOD__ );
1587 }
1588
1589 /**
1590 * Delete a given older version of a file.
1591 * May throw a database error.
1592 * @return true on success, false on failure
1593 */
1594 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1595 $oldpath = wfImageArchiveDir( $this->name ) .
1596 DIRECTORY_SEPARATOR . $archiveName;
1597 return $this->prepareDeleteVersion(
1598 $oldpath,
1599 $reason,
1600 'oldimage',
1601 array(
1602 'fa_name' => 'oi_name',
1603 'fa_archive_name' => 'oi_archive_name',
1604 'fa_size' => 'oi_size',
1605 'fa_width' => 'oi_width',
1606 'fa_height' => 'oi_height',
1607 'fa_metadata' => 'NULL',
1608 'fa_bits' => 'oi_bits',
1609 'fa_media_type' => 'NULL',
1610 'fa_major_mime' => 'NULL',
1611 'fa_minor_mime' => 'NULL',
1612 'fa_description' => 'oi_description',
1613 'fa_user' => 'oi_user',
1614 'fa_user_text' => 'oi_user_text',
1615 'fa_timestamp' => 'oi_timestamp' ),
1616 array(
1617 'oi_name' => $this->name,
1618 'oi_archive_name' => $archiveName ),
1619 $suppress,
1620 __METHOD__ );
1621 }
1622
1623 /**
1624 * Do the dirty work of backing up an image row and its file
1625 * (if $wgSaveDeletedFiles is on) and removing the originals.
1626 *
1627 * Must be run while the file store is locked and a database
1628 * transaction is open to avoid race conditions.
1629 *
1630 * @return FSTransaction
1631 */
1632 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1633 global $wgUser, $wgSaveDeletedFiles;
1634
1635 // Dupe the file into the file store
1636 if( file_exists( $path ) ) {
1637 if( $wgSaveDeletedFiles ) {
1638 $group = 'deleted';
1639
1640 $store = FileStore::get( $group );
1641 $key = FileStore::calculateKey( $path, $this->extension );
1642 $transaction = $store->insert( $key, $path,
1643 FileStore::DELETE_ORIGINAL );
1644 } else {
1645 $group = null;
1646 $key = null;
1647 $transaction = FileStore::deleteFile( $path );
1648 }
1649 } else {
1650 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
1651 $group = null;
1652 $key = null;
1653 $transaction = new FSTransaction(); // empty
1654 }
1655
1656 if( $transaction === false ) {
1657 // Fail to restore?
1658 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
1659 throw new MWException( "Could not archive and delete file $path" );
1660 return false;
1661 }
1662
1663 // Bitfields to further supress the image content
1664 // Note that currently, live images are stored elsewhere
1665 // and cannot be partially deleted
1666 $bitfield = 0;
1667 if ( $suppress ) {
1668 $bitfield |= self::DELETED_FILE;
1669 $bitfield |= self::DELETED_COMMENT;
1670 $bitfield |= self::DELETED_USER;
1671 $bitfield |= self::DELETED_RESTRICTED;
1672 }
1673
1674 $dbw = wfGetDB( DB_MASTER );
1675 $storageMap = array(
1676 'fa_storage_group' => $dbw->addQuotes( $group ),
1677 'fa_storage_key' => $dbw->addQuotes( $key ),
1678
1679 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1680 'fa_deleted_timestamp' => $dbw->timestamp(),
1681 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1682 'fa_deleted' => $bitfield);
1683 $allFields = array_merge( $storageMap, $fieldMap );
1684
1685 try {
1686 if( $wgSaveDeletedFiles ) {
1687 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1688 }
1689 $dbw->delete( $table, $where, $fname );
1690 } catch( DBQueryError $e ) {
1691 // Something went horribly wrong!
1692 // Leave the file as it was...
1693 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
1694 $transaction->rollback();
1695 throw $e;
1696 }
1697
1698 return $transaction;
1699 }
1700
1701 /**
1702 * Restore all or specified deleted revisions to the given file.
1703 * Permissions and logging are left to the caller.
1704 *
1705 * May throw database exceptions on error.
1706 *
1707 * @param $versions set of record ids of deleted items to restore,
1708 * or empty to restore all revisions.
1709 * @return the number of file revisions restored if successful,
1710 * or false on failure
1711 */
1712 function restore( $versions=array(), $Unsuppress=false ) {
1713 global $wgUser;
1714
1715 if( !FileStore::lock() ) {
1716 wfDebug( __METHOD__." could not acquire filestore lock\n" );
1717 return false;
1718 }
1719
1720 $transaction = new FSTransaction();
1721 try {
1722 $dbw = wfGetDB( DB_MASTER );
1723 $dbw->begin();
1724
1725 // Re-confirm whether this image presently exists;
1726 // if no we'll need to create an image record for the
1727 // first item we restore.
1728 $exists = $dbw->selectField( 'image', '1',
1729 array( 'img_name' => $this->name ),
1730 __METHOD__ );
1731
1732 // Fetch all or selected archived revisions for the file,
1733 // sorted from the most recent to the oldest.
1734 $conditions = array( 'fa_name' => $this->name );
1735 if( $versions ) {
1736 $conditions['fa_id'] = $versions;
1737 }
1738
1739 $result = $dbw->select( 'filearchive', '*',
1740 $conditions,
1741 __METHOD__,
1742 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1743
1744 if( $dbw->numRows( $result ) < count( $versions ) ) {
1745 // There's some kind of conflict or confusion;
1746 // we can't restore everything we were asked to.
1747 wfDebug( __METHOD__.": couldn't find requested items\n" );
1748 $dbw->rollback();
1749 FileStore::unlock();
1750 return false;
1751 }
1752
1753 if( $dbw->numRows( $result ) == 0 ) {
1754 // Nothing to do.
1755 wfDebug( __METHOD__.": nothing to do\n" );
1756 $dbw->rollback();
1757 FileStore::unlock();
1758 return true;
1759 }
1760
1761 $revisions = 0;
1762 while( $row = $dbw->fetchObject( $result ) ) {
1763 if ( $Unsuppress ) {
1764 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1765 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
1766 // Skip restoring file revisions that the user cannot restore
1767 continue;
1768 }
1769 $revisions++;
1770 $store = FileStore::get( $row->fa_storage_group );
1771 if( !$store ) {
1772 wfDebug( __METHOD__.": skipping row with no file.\n" );
1773 continue;
1774 }
1775
1776 if( $revisions == 1 && !$exists ) {
1777 $destDir = wfImageDir( $row->fa_name );
1778 if ( !is_dir( $destDir ) ) {
1779 wfMkdirParents( $destDir );
1780 }
1781 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
1782
1783 // We may have to fill in data if this was originally
1784 // an archived file revision.
1785 if( is_null( $row->fa_metadata ) ) {
1786 $tempFile = $store->filePath( $row->fa_storage_key );
1787
1788 $magic = MimeMagic::singleton();
1789 $mime = $magic->guessMimeType( $tempFile, true );
1790 $media_type = $magic->getMediaType( $tempFile, $mime );
1791 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
1792 $handler = MediaHandler::getHandler( $mime );
1793 if ( $handler ) {
1794 $metadata = $handler->getMetadata( $image, $tempFile );
1795 } else {
1796 $metadata = '';
1797 }
1798 } else {
1799 $metadata = $row->fa_metadata;
1800 $major_mime = $row->fa_major_mime;
1801 $minor_mime = $row->fa_minor_mime;
1802 $media_type = $row->fa_media_type;
1803 }
1804
1805 $table = 'image';
1806 $fields = array(
1807 'img_name' => $row->fa_name,
1808 'img_size' => $row->fa_size,
1809 'img_width' => $row->fa_width,
1810 'img_height' => $row->fa_height,
1811 'img_metadata' => $metadata,
1812 'img_bits' => $row->fa_bits,
1813 'img_media_type' => $media_type,
1814 'img_major_mime' => $major_mime,
1815 'img_minor_mime' => $minor_mime,
1816 'img_description' => $row->fa_description,
1817 'img_user' => $row->fa_user,
1818 'img_user_text' => $row->fa_user_text,
1819 'img_timestamp' => $row->fa_timestamp );
1820 } else {
1821 $archiveName = $row->fa_archive_name;
1822 if( $archiveName == '' ) {
1823 // This was originally a current version; we
1824 // have to devise a new archive name for it.
1825 // Format is <timestamp of archiving>!<name>
1826 $archiveName =
1827 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
1828 '!' . $row->fa_name;
1829 }
1830 $destDir = wfImageArchiveDir( $row->fa_name );
1831 if ( !is_dir( $destDir ) ) {
1832 wfMkdirParents( $destDir );
1833 }
1834 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
1835
1836 $table = 'oldimage';
1837 $fields = array(
1838 'oi_name' => $row->fa_name,
1839 'oi_archive_name' => $archiveName,
1840 'oi_size' => $row->fa_size,
1841 'oi_width' => $row->fa_width,
1842 'oi_height' => $row->fa_height,
1843 'oi_bits' => $row->fa_bits,
1844 'oi_description' => $row->fa_description,
1845 'oi_user' => $row->fa_user,
1846 'oi_user_text' => $row->fa_user_text,
1847 'oi_timestamp' => $row->fa_timestamp );
1848 }
1849
1850 $dbw->insert( $table, $fields, __METHOD__ );
1851 // @todo this delete is not totally safe, potentially
1852 $dbw->delete( 'filearchive',
1853 array( 'fa_id' => $row->fa_id ),
1854 __METHOD__ );
1855
1856 // Check if any other stored revisions use this file;
1857 // if so, we shouldn't remove the file from the deletion
1858 // archives so they will still work.
1859 $useCount = $dbw->selectField( 'filearchive',
1860 'COUNT(*)',
1861 array(
1862 'fa_storage_group' => $row->fa_storage_group,
1863 'fa_storage_key' => $row->fa_storage_key ),
1864 __METHOD__ );
1865 if( $useCount == 0 ) {
1866 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1867 $flags = FileStore::DELETE_ORIGINAL;
1868 } else {
1869 $flags = 0;
1870 }
1871
1872 $transaction->add( $store->export( $row->fa_storage_key,
1873 $destPath, $flags ) );
1874 }
1875
1876 $dbw->immediateCommit();
1877 } catch( MWException $e ) {
1878 wfDebug( __METHOD__." caught error, aborting\n" );
1879 $transaction->rollback();
1880 throw $e;
1881 }
1882
1883 $transaction->commit();
1884 FileStore::unlock();
1885
1886 if( $revisions > 0 ) {
1887 if( !$exists ) {
1888 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
1889
1890 // Update site_stats
1891 $site_stats = $dbw->tableName( 'site_stats' );
1892 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1893
1894 $this->purgeEverything();
1895 } else {
1896 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
1897 $this->purgeDescription();
1898 }
1899 }
1900
1901 return $revisions;
1902 }
1903
1904 /**
1905 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1906 * document.
1907 *
1908 * @return Bool
1909 */
1910 function isMultipage() {
1911 $handler = $this->getHandler();
1912 return $handler && $handler->isMultiPage();
1913 }
1914
1915 /**
1916 * Returns the number of pages of a multipage document, or NULL for
1917 * documents which aren't multipage documents
1918 */
1919 function pageCount() {
1920 $handler = $this->getHandler();
1921 if ( $handler && $handler->isMultiPage() ) {
1922 return $handler->pageCount( $this );
1923 } else {
1924 return null;
1925 }
1926 }
1927
1928 static function getCommonsDB() {
1929 static $dbc;
1930 global $wgLoadBalancer, $wgSharedUploadDBname;
1931 if ( !isset( $dbc ) ) {
1932 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1933 $dbinfo = $wgLoadBalancer->mServers[$i];
1934 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1935 $dbinfo['password'], $wgSharedUploadDBname );
1936 }
1937 return $dbc;
1938 }
1939
1940 /**
1941 * Calculate the height of a thumbnail using the source and destination width
1942 */
1943 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1944 // Exact integer multiply followed by division
1945 if ( $srcWidth == 0 ) {
1946 return 0;
1947 } else {
1948 return round( $srcHeight * $dstWidth / $srcWidth );
1949 }
1950 }
1951
1952 /**
1953 * Get an image size array like that returned by getimagesize(), or false if it
1954 * can't be determined.
1955 *
1956 * @param string $fileName The filename
1957 * @return array
1958 */
1959 function getImageSize( $fileName ) {
1960 $handler = $this->getHandler();
1961 return $handler->getImageSize( $this, $fileName );
1962 }
1963
1964 /**
1965 * Get the thumbnail extension and MIME type for a given source MIME type
1966 * @return array thumbnail extension and MIME type
1967 */
1968 static function getThumbType( $ext, $mime ) {
1969 $handler = MediaHandler::getHandler( $mime );
1970 if ( $handler ) {
1971 return $handler->getThumbType( $ext, $mime );
1972 } else {
1973 return array( $ext, $mime );
1974 }
1975 }
1976
1977 } //class
1978
1979
1980 /**
1981 * @addtogroup Media
1982 */
1983 class ArchivedFile
1984 {
1985 /**
1986 * Returns a file object from the filearchive table
1987 * In the future, all current and old image storage
1988 * may use FileStore. There will be a "old" storage
1989 * for current and previous file revisions as well as
1990 * the "deleted" group for archived revisions
1991 * @param $title, the corresponding image page title
1992 * @param $id, the image id, a unique key
1993 * @param $key, optional storage key
1994 * @return ResultWrapper
1995 */
1996 function ArchivedFile( $title, $id=0, $key='' ) {
1997 if( !is_object( $title ) ) {
1998 throw new MWException( 'Image constructor given bogus title.' );
1999 }
2000 $conds = ($id) ? "fa_id = $id" : "fa_storage_key = '$key'";
2001 if( $title->getNamespace() == NS_IMAGE ) {
2002 $dbr = wfGetDB( DB_SLAVE );
2003 $res = $dbr->select( 'filearchive',
2004 array(
2005 'fa_id',
2006 'fa_name',
2007 'fa_storage_key',
2008 'fa_storage_group',
2009 'fa_size',
2010 'fa_bits',
2011 'fa_width',
2012 'fa_height',
2013 'fa_metadata',
2014 'fa_media_type',
2015 'fa_major_mime',
2016 'fa_minor_mime',
2017 'fa_description',
2018 'fa_user',
2019 'fa_user_text',
2020 'fa_timestamp',
2021 'fa_deleted' ),
2022 array(
2023 'fa_name' => $title->getDbKey(),
2024 $conds ),
2025 __METHOD__,
2026 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2027
2028 if ( $dbr->numRows( $res ) == 0 ) {
2029 // this revision does not exist?
2030 return;
2031 }
2032 $ret = $dbr->resultObject( $res );
2033 $row = $ret->fetchObject();
2034
2035 // initialize fields for filestore image object
2036 $this->mId = intval($row->fa_id);
2037 $this->mName = $row->fa_name;
2038 $this->mGroup = $row->fa_storage_group;
2039 $this->mKey = $row->fa_storage_key;
2040 $this->mSize = $row->fa_size;
2041 $this->mBits = $row->fa_bits;
2042 $this->mWidth = $row->fa_width;
2043 $this->mHeight = $row->fa_height;
2044 $this->mMetaData = $row->fa_metadata;
2045 $this->mMime = "$row->fa_major_mime/$row->fa_minor_mime";
2046 $this->mType = $row->fa_media_type;
2047 $this->mDescription = $row->fa_description;
2048 $this->mUser = $row->fa_user;
2049 $this->mUserText = $row->fa_user_text;
2050 $this->mTimestamp = $row->fa_timestamp;
2051 $this->mDeleted = $row->fa_deleted;
2052 } else {
2053 throw new MWException( 'This title does not correspond to an image page.' );
2054 return;
2055 }
2056 return true;
2057 }
2058
2059 /**
2060 * int $field one of DELETED_* bitfield constants
2061 * for file or revision rows
2062 * @return bool
2063 */
2064 function isDeleted( $field ) {
2065 return ($this->mDeleted & $field) == $field;
2066 }
2067
2068 /**
2069 * Determine if the current user is allowed to view a particular
2070 * field of this FileStore image file, if it's marked as deleted.
2071 * @param int $field
2072 * @return bool
2073 */
2074 function userCan( $field ) {
2075 if( isset($this->mDeleted) && ($this->mDeleted & $field) == $field ) {
2076 // images
2077 global $wgUser;
2078 $permission = ( $this->mDeleted & Revision::DELETED_RESTRICTED ) == Revision::DELETED_RESTRICTED
2079 ? 'hiderevision'
2080 : 'deleterevision';
2081 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2082 return $wgUser->isAllowed( $permission );
2083 } else {
2084 return true;
2085 }
2086 }
2087 }
2088
2089 /**
2090 * Aliases for backwards compatibility with 1.6
2091 */
2092 define( 'MW_IMG_DELETED_FILE', Image::DELETED_FILE );
2093 define( 'MW_IMG_DELETED_COMMENT', Image::DELETED_COMMENT );
2094 define( 'MW_IMG_DELETED_USER', Image::DELETED_USER );
2095 define( 'MW_IMG_DELETED_RESTRICTED', Image::DELETED_RESTRICTED );
2096
2097 ?>