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