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