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