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