debugging
[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 thumbUrl( $thumbName ) {
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 $subdir = wfGetHashPath($this->name, $this->fromSharedDirectory) .
778 wfUrlencode( $this->name );
779 } else {
780 $subdir = '';
781 }
782 $url = "{$base}{$path}/thumb{$subdir}/" . wfUrlencode( $thumbName );
783 return $url;
784 }
785
786 function getTransformScript() {
787 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
788 if ( $this->fromSharedDirectory ) {
789 $script = $wgSharedThumbnailScriptPath;
790 } else {
791 $script = $wgThumbnailScriptPath;
792 }
793 if ( $script ) {
794 return "$script?f=" . urlencode( $this->name );
795 } else {
796 return false;
797 }
798 }
799
800 /**
801 * Get a ThumbnailImage which is the same size as the source
802 */
803 function getUnscaledThumb( $page = false ) {
804 if ( $page ) {
805 $params = array(
806 'page' => $page,
807 'width' => $this->getWidth( $page )
808 );
809 } else {
810 $params = array( 'width' => $this->getWidth() );
811 }
812 return $this->transform( $params );
813 }
814
815 /**
816 * Return the file name of a thumbnail with the specified parameters
817 *
818 * @param array $params Handler-specific parameters
819 * @private
820 */
821 function thumbName( $params ) {
822 $handler = $this->getHandler();
823 if ( !$handler ) {
824 return null;
825 }
826 list( $thumbExt, $thumbMime ) = self::getThumbType( $this->extension, $this->mime );
827 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name;
828 if ( $thumbExt != $this->extension ) {
829 $thumbName .= ".$thumbExt";
830 }
831 return $thumbName;
832 }
833
834 /**
835 * Create a thumbnail of the image having the specified width/height.
836 * The thumbnail will not be created if the width is larger than the
837 * image's width. Let the browser do the scaling in this case.
838 * The thumbnail is stored on disk and is only computed if the thumbnail
839 * file does not exist OR if it is older than the image.
840 * Returns the URL.
841 *
842 * Keeps aspect ratio of original image. If both width and height are
843 * specified, the generated image will be no bigger than width x height,
844 * and will also have correct aspect ratio.
845 *
846 * @param integer $width maximum width of the generated thumbnail
847 * @param integer $height maximum height of the image (optional)
848 * @public
849 */
850 function createThumb( $width, $height = -1 ) {
851 $params = array( 'width' => $width );
852 if ( $height != -1 ) {
853 $params['height'] = $height;
854 }
855 $thumb = $this->transform( $params );
856 if( is_null( $thumb ) || $thumb->isError() ) return '';
857 return $thumb->getUrl();
858 }
859
860 /**
861 * As createThumb, but returns a ThumbnailImage object. This can
862 * provide access to the actual file, the real size of the thumb,
863 * and can produce a convenient <img> tag for you.
864 *
865 * For non-image formats, this may return a filetype-specific icon.
866 *
867 * @param integer $width maximum width of the generated thumbnail
868 * @param integer $height maximum height of the image (optional)
869 * @param boolean $render True to render the thumbnail if it doesn't exist,
870 * false to just return the URL
871 *
872 * @return ThumbnailImage or null on failure
873 * @public
874 *
875 * @deprecated use transform()
876 */
877 function getThumbnail( $width, $height=-1, $render = true ) {
878 $params = array( 'width' => $width );
879 if ( $height != -1 ) {
880 $params['height'] = $height;
881 }
882 $flags = $render ? self::RENDER_NOW : 0;
883 return $this->transform( $params, $flags );
884 }
885
886 /**
887 * Transform a media file
888 *
889 * @param array $params An associative array of handler-specific parameters. Typical
890 * keys are width, height and page.
891 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
892 * @return MediaTransformOutput
893 */
894 function transform( $params, $flags = 0 ) {
895 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
896
897 wfProfileIn( __METHOD__ );
898 do {
899 $handler = $this->getHandler();
900 if ( !$handler || !$handler->canRender() ) {
901 // not a bitmap or renderable image, don't try.
902 $thumb = $this->iconThumb();
903 break;
904 }
905
906 $script = $this->getTransformScript();
907 if ( $script && !($flags & self::RENDER_NOW) ) {
908 // Use a script to transform on client request
909 $thumb = $handler->getScriptedTransform( $this, $script, $params );
910 break;
911 }
912
913 $normalisedParams = $params;
914 $handler->normaliseParams( $this, $normalisedParams );
915 list( $thumbExt, $thumbMime ) = self::getThumbType( $this->extension, $this->mime );
916 $thumbName = $this->thumbName( $normalisedParams );
917 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ) . "/$thumbName";
918 $thumbUrl = $this->thumbUrl( $thumbName );
919
920 $this->migrateThumbFile( $thumbName );
921
922 if ( file_exists( $thumbPath ) ) {
923 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
924 break;
925 }
926
927 if ( !$wgGenerateThumbnailOnParse && !($flags & self::RENDER_NOW ) ) {
928 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
929 break;
930 }
931 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
932
933 // Ignore errors if requested
934 if ( !$thumb ) {
935 $thumb = null;
936 } elseif ( $thumb->isError() ) {
937 $this->lastError = $thumb->toText();
938 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
939 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
940 }
941 }
942
943 if ( $wgUseSquid ) {
944 wfPurgeSquidServers( array( $thumbUrl ) );
945 }
946 } while (false);
947
948 wfProfileOut( __METHOD__ );
949 return $thumb;
950 }
951
952 /**
953 * Fix thumbnail files from 1.4 or before, with extreme prejudice
954 */
955 function migrateThumbFile( $thumbName ) {
956 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
957 $thumbPath = "$thumbDir/$thumbName";
958 if ( is_dir( $thumbPath ) ) {
959 // Directory where file should be
960 // This happened occasionally due to broken migration code in 1.5
961 // Rename to broken-*
962 global $wgUploadDirectory;
963 for ( $i = 0; $i < 100 ; $i++ ) {
964 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
965 if ( !file_exists( $broken ) ) {
966 rename( $thumbPath, $broken );
967 break;
968 }
969 }
970 // Doesn't exist anymore
971 clearstatcache();
972 }
973 if ( is_file( $thumbDir ) ) {
974 // File where directory should be
975 unlink( $thumbDir );
976 // Doesn't exist anymore
977 clearstatcache();
978 }
979 }
980
981 /**
982 * Get a MediaHandler instance for this image
983 */
984 function getHandler() {
985 return MediaHandler::getHandler( $this->getMimeType() );
986 }
987
988 /**
989 * Get a ThumbnailImage representing a file type icon
990 * @return ThumbnailImage
991 */
992 function iconThumb() {
993 global $wgStylePath, $wgStyleDirectory;
994
995 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
996 foreach( $try as $icon ) {
997 $path = '/common/images/icons/' . $icon;
998 $filepath = $wgStyleDirectory . $path;
999 if( file_exists( $filepath ) ) {
1000 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1001 }
1002 }
1003 return null;
1004 }
1005
1006 /**
1007 * Get last thumbnailing error.
1008 * Largely obsolete.
1009 */
1010 function getLastError() {
1011 return $this->lastError;
1012 }
1013
1014 /**
1015 * Get all thumbnail names previously generated for this image
1016 */
1017 function getThumbnails( $shared = false ) {
1018 if ( Image::isHashed( $shared ) ) {
1019 $this->load();
1020 $files = array();
1021 $dir = wfImageThumbDir( $this->name, $shared );
1022
1023 if ( is_dir( $dir ) ) {
1024 $handle = opendir( $dir );
1025
1026 if ( $handle ) {
1027 while ( false !== ( $file = readdir($handle) ) ) {
1028 if ( $file{0} != '.' ) {
1029 $files[] = $file;
1030 }
1031 }
1032 closedir( $handle );
1033 }
1034 }
1035 } else {
1036 $files = array();
1037 }
1038
1039 return $files;
1040 }
1041
1042 /**
1043 * Refresh metadata in memcached, but don't touch thumbnails or squid
1044 */
1045 function purgeMetadataCache() {
1046 clearstatcache();
1047 $this->upgradeRow();
1048 $this->saveToCache();
1049 }
1050
1051 /**
1052 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1053 */
1054 function purgeCache( $archiveFiles = array(), $shared = false ) {
1055 global $wgUseSquid;
1056
1057 // Refresh metadata cache
1058 $this->purgeMetadataCache();
1059
1060 // Delete thumbnails
1061 $files = $this->getThumbnails( $shared );
1062 $dir = wfImageThumbDir( $this->name, $shared );
1063 $urls = array();
1064 foreach ( $files as $file ) {
1065 $m = array();
1066 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1067 $url = $this->thumbUrl( $m[1] );
1068 $urls[] = $url;
1069 @unlink( "$dir/$file" );
1070 }
1071 }
1072
1073 // Purge the squid
1074 if ( $wgUseSquid ) {
1075 $urls[] = $this->getURL();
1076 foreach ( $archiveFiles as $file ) {
1077 $urls[] = wfImageArchiveUrl( $file );
1078 }
1079 wfPurgeSquidServers( $urls );
1080 }
1081 }
1082
1083 /**
1084 * Purge the image description page, but don't go after
1085 * pages using the image. Use when modifying file history
1086 * but not the current data.
1087 */
1088 function purgeDescription() {
1089 $page = Title::makeTitle( NS_IMAGE, $this->name );
1090 $page->invalidateCache();
1091 $page->purgeSquid();
1092 }
1093
1094 /**
1095 * Purge metadata and all affected pages when the image is created,
1096 * deleted, or majorly updated. A set of additional URLs may be
1097 * passed to purge, such as specific image files which have changed.
1098 * @param $urlArray array
1099 */
1100 function purgeEverything( $urlArr=array() ) {
1101 // Delete thumbnails and refresh image metadata cache
1102 $this->purgeCache();
1103 $this->purgeDescription();
1104
1105 // Purge cache of all pages using this image
1106 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1107 $update->doUpdate();
1108 }
1109
1110 /**
1111 * Check the image table schema on the given connection for subtle problems
1112 */
1113 function checkDBSchema(&$db) {
1114 static $checkDone = false;
1115 global $wgCheckDBSchema;
1116 if (!$wgCheckDBSchema || $checkDone) {
1117 return;
1118 }
1119 # img_name must be unique
1120 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1121 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1122 }
1123 $checkDone = true;
1124
1125 # new fields must exist
1126 #
1127 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1128 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1129 # something. The only reason I put the above schema check in was because the absence of that particular
1130 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1131 # uploads. -- TS
1132 /*
1133 if ( !$db->fieldExists( 'image', 'img_media_type' )
1134 || !$db->fieldExists( 'image', 'img_metadata' )
1135 || !$db->fieldExists( 'image', 'img_width' ) ) {
1136
1137 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1138 }
1139 */
1140 }
1141
1142 /**
1143 * Return the image history of this image, line by line.
1144 * starts with current version, then old versions.
1145 * uses $this->historyLine to check which line to return:
1146 * 0 return line for current version
1147 * 1 query for old versions, return first one
1148 * 2, ... return next old version from above query
1149 *
1150 * @public
1151 */
1152 function nextHistoryLine() {
1153 $dbr = wfGetDB( DB_SLAVE );
1154
1155 $this->checkDBSchema($dbr);
1156
1157 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1158 $this->historyRes = $dbr->select( 'image',
1159 array(
1160 'img_size',
1161 'img_description',
1162 'img_user','img_user_text',
1163 'img_timestamp',
1164 'img_width',
1165 'img_height',
1166 "'' AS oi_archive_name"
1167 ),
1168 array( 'img_name' => $this->title->getDBkey() ),
1169 __METHOD__
1170 );
1171 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1172 return FALSE;
1173 }
1174 } else if ( $this->historyLine == 1 ) {
1175 $this->historyRes = $dbr->select( 'oldimage',
1176 array(
1177 'oi_size AS img_size',
1178 'oi_description AS img_description',
1179 'oi_user AS img_user',
1180 'oi_user_text AS img_user_text',
1181 'oi_timestamp AS img_timestamp',
1182 'oi_width as img_width',
1183 'oi_height as img_height',
1184 'oi_archive_name'
1185 ),
1186 array( 'oi_name' => $this->title->getDBkey() ),
1187 __METHOD__,
1188 array( 'ORDER BY' => 'oi_timestamp DESC' )
1189 );
1190 }
1191 $this->historyLine ++;
1192
1193 return $dbr->fetchObject( $this->historyRes );
1194 }
1195
1196 /**
1197 * Reset the history pointer to the first element of the history
1198 * @public
1199 */
1200 function resetHistory() {
1201 $this->historyLine = 0;
1202 }
1203
1204 /**
1205 * Return the full filesystem path to the file. Note that this does
1206 * not mean that a file actually exists under that location.
1207 *
1208 * This path depends on whether directory hashing is active or not,
1209 * i.e. whether the images are all found in the same directory,
1210 * or in hashed paths like /images/3/3c.
1211 *
1212 * @public
1213 * @param boolean $fromSharedDirectory Return the path to the file
1214 * in a shared repository (see $wgUseSharedRepository and related
1215 * options in DefaultSettings.php) instead of a local one.
1216 *
1217 */
1218 function getFullPath( $fromSharedRepository = false ) {
1219 global $wgUploadDirectory, $wgSharedUploadDirectory;
1220
1221 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1222 $wgUploadDirectory;
1223
1224 // $wgSharedUploadDirectory may be false, if thumb.php is used
1225 if ( $dir ) {
1226 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1227 } else {
1228 $fullpath = false;
1229 }
1230
1231 return $fullpath;
1232 }
1233
1234 /**
1235 * @return bool
1236 * @static
1237 */
1238 public static function isHashed( $shared ) {
1239 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1240 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1241 }
1242
1243 /**
1244 * Record an image upload in the upload log and the image table
1245 */
1246 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1247 global $wgUser, $wgUseCopyrightUpload;
1248
1249 $dbw = wfGetDB( DB_MASTER );
1250
1251 $this->checkDBSchema($dbw);
1252
1253 // Delete thumbnails and refresh the metadata cache
1254 $this->purgeCache();
1255
1256 // Fail now if the image isn't there
1257 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1258 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1259 return false;
1260 }
1261
1262 if ( $wgUseCopyrightUpload ) {
1263 if ( $license != '' ) {
1264 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1265 }
1266 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1267 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1268 "$licensetxt" .
1269 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1270 } else {
1271 if ( $license != '' ) {
1272 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1273 $textdesc = $filedesc .
1274 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1275 } else {
1276 $textdesc = $desc;
1277 }
1278 }
1279
1280 $now = $dbw->timestamp();
1281
1282 #split mime type
1283 if (strpos($this->mime,'/')!==false) {
1284 list($major,$minor)= explode('/',$this->mime,2);
1285 }
1286 else {
1287 $major= $this->mime;
1288 $minor= "unknown";
1289 }
1290
1291 # Test to see if the row exists using INSERT IGNORE
1292 # This avoids race conditions by locking the row until the commit, and also
1293 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1294 $dbw->insert( 'image',
1295 array(
1296 'img_name' => $this->name,
1297 'img_size'=> $this->size,
1298 'img_width' => intval( $this->width ),
1299 'img_height' => intval( $this->height ),
1300 'img_bits' => $this->bits,
1301 'img_media_type' => $this->type,
1302 'img_major_mime' => $major,
1303 'img_minor_mime' => $minor,
1304 'img_timestamp' => $now,
1305 'img_description' => $desc,
1306 'img_user' => $wgUser->getID(),
1307 'img_user_text' => $wgUser->getName(),
1308 'img_metadata' => $this->metadata,
1309 ),
1310 __METHOD__,
1311 'IGNORE'
1312 );
1313
1314 if( $dbw->affectedRows() == 0 ) {
1315 # Collision, this is an update of an image
1316 # Insert previous contents into oldimage
1317 $dbw->insertSelect( 'oldimage', 'image',
1318 array(
1319 'oi_name' => 'img_name',
1320 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1321 'oi_size' => 'img_size',
1322 'oi_width' => 'img_width',
1323 'oi_height' => 'img_height',
1324 'oi_bits' => 'img_bits',
1325 'oi_timestamp' => 'img_timestamp',
1326 'oi_description' => 'img_description',
1327 'oi_user' => 'img_user',
1328 'oi_user_text' => 'img_user_text',
1329 ), array( 'img_name' => $this->name ), __METHOD__
1330 );
1331
1332 # Update the current image row
1333 $dbw->update( 'image',
1334 array( /* SET */
1335 'img_size' => $this->size,
1336 'img_width' => intval( $this->width ),
1337 'img_height' => intval( $this->height ),
1338 'img_bits' => $this->bits,
1339 'img_media_type' => $this->type,
1340 'img_major_mime' => $major,
1341 'img_minor_mime' => $minor,
1342 'img_timestamp' => $now,
1343 'img_description' => $desc,
1344 'img_user' => $wgUser->getID(),
1345 'img_user_text' => $wgUser->getName(),
1346 'img_metadata' => $this->metadata,
1347 ), array( /* WHERE */
1348 'img_name' => $this->name
1349 ), __METHOD__
1350 );
1351 } else {
1352 # This is a new image
1353 # Update the image count
1354 $site_stats = $dbw->tableName( 'site_stats' );
1355 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1356 }
1357
1358 $descTitle = $this->getTitle();
1359 $article = new Article( $descTitle );
1360 $minor = false;
1361 $watch = $watch || $wgUser->isWatched( $descTitle );
1362 $suppressRC = true; // There's already a log entry, so don't double the RC load
1363
1364 if( $descTitle->exists() ) {
1365 // TODO: insert a null revision into the page history for this update.
1366 if( $watch ) {
1367 $wgUser->addWatch( $descTitle );
1368 }
1369
1370 # Invalidate the cache for the description page
1371 $descTitle->invalidateCache();
1372 $descTitle->purgeSquid();
1373 } else {
1374 // New image; create the description page.
1375 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1376 }
1377
1378 # Hooks, hooks, the magic of hooks...
1379 wfRunHooks( 'FileUpload', array( $this ) );
1380
1381 # Add the log entry
1382 $log = new LogPage( 'upload' );
1383 $log->addEntry( 'upload', $descTitle, $desc );
1384
1385 # Commit the transaction now, in case something goes wrong later
1386 # The most important thing is that images don't get lost, especially archives
1387 $dbw->immediateCommit();
1388
1389 # Invalidate cache for all pages using this image
1390 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1391 $update->doUpdate();
1392
1393 return true;
1394 }
1395
1396 /**
1397 * Get an array of Title objects which are articles which use this image
1398 * Also adds their IDs to the link cache
1399 *
1400 * This is mostly copied from Title::getLinksTo()
1401 *
1402 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1403 */
1404 function getLinksTo( $options = '' ) {
1405 wfProfileIn( __METHOD__ );
1406
1407 if ( $options ) {
1408 $db = wfGetDB( DB_MASTER );
1409 } else {
1410 $db = wfGetDB( DB_SLAVE );
1411 }
1412 $linkCache =& LinkCache::singleton();
1413
1414 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1415 $encName = $db->addQuotes( $this->name );
1416 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1417 $res = $db->query( $sql, __METHOD__ );
1418
1419 $retVal = array();
1420 if ( $db->numRows( $res ) ) {
1421 while ( $row = $db->fetchObject( $res ) ) {
1422 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1423 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1424 $retVal[] = $titleObj;
1425 }
1426 }
1427 }
1428 $db->freeResult( $res );
1429 wfProfileOut( __METHOD__ );
1430 return $retVal;
1431 }
1432
1433 function getExifData() {
1434 global $wgRequest;
1435 $handler = $this->getHandler();
1436 if ( !$handler || $handler->getMetadataType( $this ) != 'exif' ) {
1437 return array();
1438 }
1439 if ( !$this->metadata ) {
1440 return array();
1441 }
1442 $exif = unserialize( $this->metadata );
1443 if ( !$exif ) {
1444 return array();
1445 }
1446 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
1447 $format = new FormatExif( $exif );
1448
1449 return $format->getFormattedData();
1450 }
1451
1452 /**
1453 * Returns true if the image does not come from the shared
1454 * image repository.
1455 *
1456 * @return bool
1457 */
1458 function isLocal() {
1459 return !$this->fromSharedDirectory;
1460 }
1461
1462 /**
1463 * Was this image ever deleted from the wiki?
1464 *
1465 * @return bool
1466 */
1467 function wasDeleted() {
1468 $title = Title::makeTitle( NS_IMAGE, $this->name );
1469 return ( $title->isDeleted() > 0 );
1470 }
1471
1472 /**
1473 * Delete all versions of the image.
1474 *
1475 * Moves the files into an archive directory (or deletes them)
1476 * and removes the database rows.
1477 *
1478 * Cache purging is done; logging is caller's responsibility.
1479 *
1480 * @param $reason
1481 * @return true on success, false on some kind of failure
1482 */
1483 function delete( $reason, $suppress=false ) {
1484 $transaction = new FSTransaction();
1485 $urlArr = array( $this->getURL() );
1486
1487 if( !FileStore::lock() ) {
1488 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1489 return false;
1490 }
1491
1492 try {
1493 $dbw = wfGetDB( DB_MASTER );
1494 $dbw->begin();
1495
1496 // Delete old versions
1497 $result = $dbw->select( 'oldimage',
1498 array( 'oi_archive_name' ),
1499 array( 'oi_name' => $this->name ) );
1500
1501 while( $row = $dbw->fetchObject( $result ) ) {
1502 $oldName = $row->oi_archive_name;
1503
1504 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1505
1506 // We'll need to purge this URL from caches...
1507 $urlArr[] = wfImageArchiveUrl( $oldName );
1508 }
1509 $dbw->freeResult( $result );
1510
1511 // And the current version...
1512 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1513
1514 $dbw->immediateCommit();
1515 } catch( MWException $e ) {
1516 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1517 $transaction->rollback();
1518 FileStore::unlock();
1519 throw $e;
1520 }
1521
1522 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1523 $transaction->commit();
1524 FileStore::unlock();
1525
1526
1527 // Update site_stats
1528 $site_stats = $dbw->tableName( 'site_stats' );
1529 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1530
1531 $this->purgeEverything( $urlArr );
1532
1533 return true;
1534 }
1535
1536
1537 /**
1538 * Delete an old version of the image.
1539 *
1540 * Moves the file into an archive directory (or deletes it)
1541 * and removes the database row.
1542 *
1543 * Cache purging is done; logging is caller's responsibility.
1544 *
1545 * @param $reason
1546 * @throws MWException or FSException on database or filestore failure
1547 * @return true on success, false on some kind of failure
1548 */
1549 function deleteOld( $archiveName, $reason, $suppress=false ) {
1550 $transaction = new FSTransaction();
1551 $urlArr = array();
1552
1553 if( !FileStore::lock() ) {
1554 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1555 return false;
1556 }
1557
1558 $transaction = new FSTransaction();
1559 try {
1560 $dbw = wfGetDB( DB_MASTER );
1561 $dbw->begin();
1562 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1563 $dbw->immediateCommit();
1564 } catch( MWException $e ) {
1565 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1566 $transaction->rollback();
1567 FileStore::unlock();
1568 throw $e;
1569 }
1570
1571 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1572 $transaction->commit();
1573 FileStore::unlock();
1574
1575 $this->purgeDescription();
1576
1577 // Squid purging
1578 global $wgUseSquid;
1579 if ( $wgUseSquid ) {
1580 $urlArr = array(
1581 wfImageArchiveUrl( $archiveName ),
1582 );
1583 wfPurgeSquidServers( $urlArr );
1584 }
1585 return true;
1586 }
1587
1588 /**
1589 * Delete the current version of a file.
1590 * May throw a database error.
1591 * @return true on success, false on failure
1592 */
1593 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1594 return $this->prepareDeleteVersion(
1595 $this->getFullPath(),
1596 $reason,
1597 'image',
1598 array(
1599 'fa_name' => 'img_name',
1600 'fa_archive_name' => 'NULL',
1601 'fa_size' => 'img_size',
1602 'fa_width' => 'img_width',
1603 'fa_height' => 'img_height',
1604 'fa_metadata' => 'img_metadata',
1605 'fa_bits' => 'img_bits',
1606 'fa_media_type' => 'img_media_type',
1607 'fa_major_mime' => 'img_major_mime',
1608 'fa_minor_mime' => 'img_minor_mime',
1609 'fa_description' => 'img_description',
1610 'fa_user' => 'img_user',
1611 'fa_user_text' => 'img_user_text',
1612 'fa_timestamp' => 'img_timestamp' ),
1613 array( 'img_name' => $this->name ),
1614 $suppress,
1615 __METHOD__ );
1616 }
1617
1618 /**
1619 * Delete a given older version of a file.
1620 * May throw a database error.
1621 * @return true on success, false on failure
1622 */
1623 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1624 $oldpath = wfImageArchiveDir( $this->name ) .
1625 DIRECTORY_SEPARATOR . $archiveName;
1626 return $this->prepareDeleteVersion(
1627 $oldpath,
1628 $reason,
1629 'oldimage',
1630 array(
1631 'fa_name' => 'oi_name',
1632 'fa_archive_name' => 'oi_archive_name',
1633 'fa_size' => 'oi_size',
1634 'fa_width' => 'oi_width',
1635 'fa_height' => 'oi_height',
1636 'fa_metadata' => 'NULL',
1637 'fa_bits' => 'oi_bits',
1638 'fa_media_type' => 'NULL',
1639 'fa_major_mime' => 'NULL',
1640 'fa_minor_mime' => 'NULL',
1641 'fa_description' => 'oi_description',
1642 'fa_user' => 'oi_user',
1643 'fa_user_text' => 'oi_user_text',
1644 'fa_timestamp' => 'oi_timestamp' ),
1645 array(
1646 'oi_name' => $this->name,
1647 'oi_archive_name' => $archiveName ),
1648 $suppress,
1649 __METHOD__ );
1650 }
1651
1652 /**
1653 * Do the dirty work of backing up an image row and its file
1654 * (if $wgSaveDeletedFiles is on) and removing the originals.
1655 *
1656 * Must be run while the file store is locked and a database
1657 * transaction is open to avoid race conditions.
1658 *
1659 * @return FSTransaction
1660 */
1661 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1662 global $wgUser, $wgSaveDeletedFiles;
1663
1664 // Dupe the file into the file store
1665 if( file_exists( $path ) ) {
1666 if( $wgSaveDeletedFiles ) {
1667 $group = 'deleted';
1668
1669 $store = FileStore::get( $group );
1670 $key = FileStore::calculateKey( $path, $this->extension );
1671 $transaction = $store->insert( $key, $path,
1672 FileStore::DELETE_ORIGINAL );
1673 } else {
1674 $group = null;
1675 $key = null;
1676 $transaction = FileStore::deleteFile( $path );
1677 }
1678 } else {
1679 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
1680 $group = null;
1681 $key = null;
1682 $transaction = new FSTransaction(); // empty
1683 }
1684
1685 if( $transaction === false ) {
1686 // Fail to restore?
1687 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
1688 throw new MWException( "Could not archive and delete file $path" );
1689 return false;
1690 }
1691
1692 // Bitfields to further supress the image content
1693 // Note that currently, live images are stored elsewhere
1694 // and cannot be partially deleted
1695 $bitfield = 0;
1696 if ( $suppress ) {
1697 $bitfield |= self::DELETED_FILE;
1698 $bitfield |= self::DELETED_COMMENT;
1699 $bitfield |= self::DELETED_USER;
1700 $bitfield |= self::DELETED_RESTRICTED;
1701 }
1702
1703 $dbw = wfGetDB( DB_MASTER );
1704 $storageMap = array(
1705 'fa_storage_group' => $dbw->addQuotes( $group ),
1706 'fa_storage_key' => $dbw->addQuotes( $key ),
1707
1708 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1709 'fa_deleted_timestamp' => $dbw->timestamp(),
1710 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1711 'fa_deleted' => $bitfield);
1712 $allFields = array_merge( $storageMap, $fieldMap );
1713
1714 try {
1715 if( $wgSaveDeletedFiles ) {
1716 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1717 }
1718 $dbw->delete( $table, $where, $fname );
1719 } catch( DBQueryError $e ) {
1720 // Something went horribly wrong!
1721 // Leave the file as it was...
1722 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
1723 $transaction->rollback();
1724 throw $e;
1725 }
1726
1727 return $transaction;
1728 }
1729
1730 /**
1731 * Restore all or specified deleted revisions to the given file.
1732 * Permissions and logging are left to the caller.
1733 *
1734 * May throw database exceptions on error.
1735 *
1736 * @param $versions set of record ids of deleted items to restore,
1737 * or empty to restore all revisions.
1738 * @return the number of file revisions restored if successful,
1739 * or false on failure
1740 */
1741 function restore( $versions=array(), $Unsuppress=false ) {
1742 global $wgUser;
1743
1744 if( !FileStore::lock() ) {
1745 wfDebug( __METHOD__." could not acquire filestore lock\n" );
1746 return false;
1747 }
1748
1749 $transaction = new FSTransaction();
1750 try {
1751 $dbw = wfGetDB( DB_MASTER );
1752 $dbw->begin();
1753
1754 // Re-confirm whether this image presently exists;
1755 // if no we'll need to create an image record for the
1756 // first item we restore.
1757 $exists = $dbw->selectField( 'image', '1',
1758 array( 'img_name' => $this->name ),
1759 __METHOD__ );
1760
1761 // Fetch all or selected archived revisions for the file,
1762 // sorted from the most recent to the oldest.
1763 $conditions = array( 'fa_name' => $this->name );
1764 if( $versions ) {
1765 $conditions['fa_id'] = $versions;
1766 }
1767
1768 $result = $dbw->select( 'filearchive', '*',
1769 $conditions,
1770 __METHOD__,
1771 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1772
1773 if( $dbw->numRows( $result ) < count( $versions ) ) {
1774 // There's some kind of conflict or confusion;
1775 // we can't restore everything we were asked to.
1776 wfDebug( __METHOD__.": couldn't find requested items\n" );
1777 $dbw->rollback();
1778 FileStore::unlock();
1779 return false;
1780 }
1781
1782 if( $dbw->numRows( $result ) == 0 ) {
1783 // Nothing to do.
1784 wfDebug( __METHOD__.": nothing to do\n" );
1785 $dbw->rollback();
1786 FileStore::unlock();
1787 return true;
1788 }
1789
1790 $revisions = 0;
1791 while( $row = $dbw->fetchObject( $result ) ) {
1792 if ( $Unsuppress ) {
1793 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1794 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
1795 // Skip restoring file revisions that the user cannot restore
1796 continue;
1797 }
1798 $revisions++;
1799 $store = FileStore::get( $row->fa_storage_group );
1800 if( !$store ) {
1801 wfDebug( __METHOD__.": skipping row with no file.\n" );
1802 continue;
1803 }
1804
1805 if( $revisions == 1 && !$exists ) {
1806 $destDir = wfImageDir( $row->fa_name );
1807 if ( !is_dir( $destDir ) ) {
1808 wfMkdirParents( $destDir );
1809 }
1810 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
1811
1812 // We may have to fill in data if this was originally
1813 // an archived file revision.
1814 if( is_null( $row->fa_metadata ) ) {
1815 $tempFile = $store->filePath( $row->fa_storage_key );
1816
1817 $magic = MimeMagic::singleton();
1818 $mime = $magic->guessMimeType( $tempFile, true );
1819 $media_type = $magic->getMediaType( $tempFile, $mime );
1820 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
1821 $handler = MediaHandler::getHandler( $mime );
1822 if ( $handler ) {
1823 $metadata = $handler->getMetadata( $image, $tempFile );
1824 } else {
1825 $metadata = '';
1826 }
1827 } else {
1828 $metadata = $row->fa_metadata;
1829 $major_mime = $row->fa_major_mime;
1830 $minor_mime = $row->fa_minor_mime;
1831 $media_type = $row->fa_media_type;
1832 }
1833
1834 $table = 'image';
1835 $fields = array(
1836 'img_name' => $row->fa_name,
1837 'img_size' => $row->fa_size,
1838 'img_width' => $row->fa_width,
1839 'img_height' => $row->fa_height,
1840 'img_metadata' => $metadata,
1841 'img_bits' => $row->fa_bits,
1842 'img_media_type' => $media_type,
1843 'img_major_mime' => $major_mime,
1844 'img_minor_mime' => $minor_mime,
1845 'img_description' => $row->fa_description,
1846 'img_user' => $row->fa_user,
1847 'img_user_text' => $row->fa_user_text,
1848 'img_timestamp' => $row->fa_timestamp );
1849 } else {
1850 $archiveName = $row->fa_archive_name;
1851 if( $archiveName == '' ) {
1852 // This was originally a current version; we
1853 // have to devise a new archive name for it.
1854 // Format is <timestamp of archiving>!<name>
1855 $archiveName =
1856 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
1857 '!' . $row->fa_name;
1858 }
1859 $destDir = wfImageArchiveDir( $row->fa_name );
1860 if ( !is_dir( $destDir ) ) {
1861 wfMkdirParents( $destDir );
1862 }
1863 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
1864
1865 $table = 'oldimage';
1866 $fields = array(
1867 'oi_name' => $row->fa_name,
1868 'oi_archive_name' => $archiveName,
1869 'oi_size' => $row->fa_size,
1870 'oi_width' => $row->fa_width,
1871 'oi_height' => $row->fa_height,
1872 'oi_bits' => $row->fa_bits,
1873 'oi_description' => $row->fa_description,
1874 'oi_user' => $row->fa_user,
1875 'oi_user_text' => $row->fa_user_text,
1876 'oi_timestamp' => $row->fa_timestamp );
1877 }
1878
1879 $dbw->insert( $table, $fields, __METHOD__ );
1880 // @todo this delete is not totally safe, potentially
1881 $dbw->delete( 'filearchive',
1882 array( 'fa_id' => $row->fa_id ),
1883 __METHOD__ );
1884
1885 // Check if any other stored revisions use this file;
1886 // if so, we shouldn't remove the file from the deletion
1887 // archives so they will still work.
1888 $useCount = $dbw->selectField( 'filearchive',
1889 'COUNT(*)',
1890 array(
1891 'fa_storage_group' => $row->fa_storage_group,
1892 'fa_storage_key' => $row->fa_storage_key ),
1893 __METHOD__ );
1894 if( $useCount == 0 ) {
1895 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1896 $flags = FileStore::DELETE_ORIGINAL;
1897 } else {
1898 $flags = 0;
1899 }
1900
1901 $transaction->add( $store->export( $row->fa_storage_key,
1902 $destPath, $flags ) );
1903 }
1904
1905 $dbw->immediateCommit();
1906 } catch( MWException $e ) {
1907 wfDebug( __METHOD__." caught error, aborting\n" );
1908 $transaction->rollback();
1909 throw $e;
1910 }
1911
1912 $transaction->commit();
1913 FileStore::unlock();
1914
1915 if( $revisions > 0 ) {
1916 if( !$exists ) {
1917 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
1918
1919 // Update site_stats
1920 $site_stats = $dbw->tableName( 'site_stats' );
1921 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1922
1923 $this->purgeEverything();
1924 } else {
1925 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
1926 $this->purgeDescription();
1927 }
1928 }
1929
1930 return $revisions;
1931 }
1932
1933 /**
1934 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1935 * document.
1936 *
1937 * @return Bool
1938 */
1939 function isMultipage() {
1940 $handler = $this->getHandler();
1941 return $handler && $handler->isMultiPage();
1942 }
1943
1944 /**
1945 * Returns the number of pages of a multipage document, or NULL for
1946 * documents which aren't multipage documents
1947 */
1948 function pageCount() {
1949 $handler = $this->getHandler();
1950 if ( $handler && $handler->isMultiPage() ) {
1951 return $handler->pageCount( $this );
1952 } else {
1953 return null;
1954 }
1955 }
1956
1957 static function getCommonsDB() {
1958 static $dbc;
1959 global $wgLoadBalancer, $wgSharedUploadDBname;
1960 if ( !isset( $dbc ) ) {
1961 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1962 $dbinfo = $wgLoadBalancer->mServers[$i];
1963 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1964 $dbinfo['password'], $wgSharedUploadDBname );
1965 }
1966 return $dbc;
1967 }
1968
1969 /**
1970 * Calculate the height of a thumbnail using the source and destination width
1971 */
1972 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1973 // Exact integer multiply followed by division
1974 if ( $srcWidth == 0 ) {
1975 return 0;
1976 } else {
1977 return round( $srcHeight * $dstWidth / $srcWidth );
1978 }
1979 }
1980
1981 /**
1982 * Get an image size array like that returned by getimagesize(), or false if it
1983 * can't be determined.
1984 *
1985 * @param string $fileName The filename
1986 * @return array
1987 */
1988 function getImageSize( $fileName ) {
1989 $handler = $this->getHandler();
1990 return $handler->getImageSize( $this, $fileName );
1991 }
1992
1993 /**
1994 * Get the thumbnail extension and MIME type for a given source MIME type
1995 * @return array thumbnail extension and MIME type
1996 */
1997 static function getThumbType( $ext, $mime ) {
1998 $handler = MediaHandler::getHandler( $mime );
1999 if ( $handler ) {
2000 return $handler->getThumbType( $ext, $mime );
2001 } else {
2002 return array( $ext, $mime );
2003 }
2004 }
2005
2006 } //class
2007
2008
2009 /**
2010 * @addtogroup Media
2011 */
2012 class ArchivedFile
2013 {
2014 /**
2015 * Returns a file object from the filearchive table
2016 * In the future, all current and old image storage
2017 * may use FileStore. There will be a "old" storage
2018 * for current and previous file revisions as well as
2019 * the "deleted" group for archived revisions
2020 * @param $title, the corresponding image page title
2021 * @param $id, the image id, a unique key
2022 * @param $key, optional storage key
2023 * @return ResultWrapper
2024 */
2025 function ArchivedFile( $title, $id=0, $key='' ) {
2026 if( !is_object( $title ) ) {
2027 throw new MWException( 'Image constructor given bogus title.' );
2028 }
2029 $conds = ($id) ? "fa_id = $id" : "fa_storage_key = '$key'";
2030 if( $title->getNamespace() == NS_IMAGE ) {
2031 $dbr = wfGetDB( DB_SLAVE );
2032 $res = $dbr->select( 'filearchive',
2033 array(
2034 'fa_id',
2035 'fa_name',
2036 'fa_storage_key',
2037 'fa_storage_group',
2038 'fa_size',
2039 'fa_bits',
2040 'fa_width',
2041 'fa_height',
2042 'fa_metadata',
2043 'fa_media_type',
2044 'fa_major_mime',
2045 'fa_minor_mime',
2046 'fa_description',
2047 'fa_user',
2048 'fa_user_text',
2049 'fa_timestamp',
2050 'fa_deleted' ),
2051 array(
2052 'fa_name' => $title->getDbKey(),
2053 $conds ),
2054 __METHOD__,
2055 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2056
2057 if ( $dbr->numRows( $res ) == 0 ) {
2058 // this revision does not exist?
2059 return;
2060 }
2061 $ret = $dbr->resultObject( $res );
2062 $row = $ret->fetchObject();
2063
2064 // initialize fields for filestore image object
2065 $this->mId = intval($row->fa_id);
2066 $this->mName = $row->fa_name;
2067 $this->mGroup = $row->fa_storage_group;
2068 $this->mKey = $row->fa_storage_key;
2069 $this->mSize = $row->fa_size;
2070 $this->mBits = $row->fa_bits;
2071 $this->mWidth = $row->fa_width;
2072 $this->mHeight = $row->fa_height;
2073 $this->mMetaData = $row->fa_metadata;
2074 $this->mMime = "$row->fa_major_mime/$row->fa_minor_mime";
2075 $this->mType = $row->fa_media_type;
2076 $this->mDescription = $row->fa_description;
2077 $this->mUser = $row->fa_user;
2078 $this->mUserText = $row->fa_user_text;
2079 $this->mTimestamp = $row->fa_timestamp;
2080 $this->mDeleted = $row->fa_deleted;
2081 } else {
2082 throw new MWException( 'This title does not correspond to an image page.' );
2083 return;
2084 }
2085 return true;
2086 }
2087
2088 /**
2089 * int $field one of DELETED_* bitfield constants
2090 * for file or revision rows
2091 * @return bool
2092 */
2093 function isDeleted( $field ) {
2094 return ($this->mDeleted & $field) == $field;
2095 }
2096
2097 /**
2098 * Determine if the current user is allowed to view a particular
2099 * field of this FileStore image file, if it's marked as deleted.
2100 * @param int $field
2101 * @return bool
2102 */
2103 function userCan( $field ) {
2104 if( isset($this->mDeleted) && ($this->mDeleted & $field) == $field ) {
2105 // images
2106 global $wgUser;
2107 $permission = ( $this->mDeleted & Revision::DELETED_RESTRICTED ) == Revision::DELETED_RESTRICTED
2108 ? 'hiderevision'
2109 : 'deleterevision';
2110 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2111 return $wgUser->isAllowed( $permission );
2112 } else {
2113 return true;
2114 }
2115 }
2116 }
2117
2118 /**
2119 * Aliases for backwards compatibility with 1.6
2120 */
2121 define( 'MW_IMG_DELETED_FILE', Image::DELETED_FILE );
2122 define( 'MW_IMG_DELETED_COMMENT', Image::DELETED_COMMENT );
2123 define( 'MW_IMG_DELETED_USER', Image::DELETED_USER );
2124 define( 'MW_IMG_DELETED_RESTRICTED', Image::DELETED_RESTRICTED );
2125
2126 ?>