Merge "mediawiki.api: Use Promise.then instead of manual Deferred wrap"
[lhc/web/wiklou.git] / includes / filerepo / file / LocalFile.php
1 <?php
2 /**
3 * Local file in the wiki's own database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileAbstraction
22 */
23
24 /**
25 * Bump this number when serialized cache records may be incompatible.
26 */
27 define( 'MW_FILE_VERSION', 9 );
28
29 /**
30 * Class to represent a local file in the wiki's own database
31 *
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
34 *
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
38 *
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
40 *
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
42 * in most cases.
43 *
44 * @ingroup FileAbstraction
45 */
46 class LocalFile extends File {
47 const CACHE_FIELD_MAX_LEN = 1000;
48
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
51
52 /** @var int image width */
53 protected $width;
54
55 /** @var int image height */
56 protected $height;
57
58 /** @var int Returned by getimagesize (loadFromXxx) */
59 protected $bits;
60
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
63
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
65 protected $mime;
66
67 /** @var int Size in bytes (loadFromXxx) */
68 protected $size;
69
70 /** @var string Handler-specific metadata */
71 protected $metadata;
72
73 /** @var string SHA-1 base 36 content hash */
74 protected $sha1;
75
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
78
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
81
82 /** @var int Bitfield akin to rev_deleted */
83 protected $deleted;
84
85 /** @var string */
86 protected $repoClass = 'LocalRepo';
87
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
89 private $historyLine;
90
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
92 private $historyRes;
93
94 /** @var string Major mime type */
95 private $major_mime;
96
97 /** @var string Minor mime type */
98 private $minor_mime;
99
100 /** @var string Upload timestamp */
101 private $timestamp;
102
103 /** @var int User ID of uploader */
104 private $user;
105
106 /** @var string User name of uploader */
107 private $user_text;
108
109 /** @var string Description of current revision of the file */
110 private $description;
111
112 /** @var bool Whether the row was upgraded on load */
113 private $upgraded;
114
115 /** @var bool True if the image row is locked */
116 private $locked;
117
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
120
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
122 private $missing;
123
124 const LOAD_ALL = 1; // integer; load all the lazy fields too (like metadata)
125
126 /**
127 * Create a LocalFile from a title
128 * Do not call this except from inside a repo class.
129 *
130 * Note: $unused param is only here to avoid an E_STRICT
131 *
132 * @param Title $title
133 * @param FileRepo $repo
134 * @param $unused
135 *
136 * @return LocalFile
137 */
138 static function newFromTitle( $title, $repo, $unused = null ) {
139 return new self( $title, $repo );
140 }
141
142 /**
143 * Create a LocalFile from a title
144 * Do not call this except from inside a repo class.
145 *
146 * @param stdClass $row
147 * @param FileRepo $repo
148 *
149 * @return LocalFile
150 */
151 static function newFromRow( $row, $repo ) {
152 $title = Title::makeTitle( NS_FILE, $row->img_name );
153 $file = new self( $title, $repo );
154 $file->loadFromRow( $row );
155
156 return $file;
157 }
158
159 /**
160 * Create a LocalFile from a SHA-1 key
161 * Do not call this except from inside a repo class.
162 *
163 * @param string $sha1 base-36 SHA-1
164 * @param LocalRepo $repo
165 * @param string|bool $timestamp MW_timestamp (optional)
166 * @return bool|LocalFile
167 */
168 static function newFromKey( $sha1, $repo, $timestamp = false ) {
169 $dbr = $repo->getSlaveDB();
170
171 $conds = array( 'img_sha1' => $sha1 );
172 if ( $timestamp ) {
173 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
174 }
175
176 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
177 if ( $row ) {
178 return self::newFromRow( $row, $repo );
179 } else {
180 return false;
181 }
182 }
183
184 /**
185 * Fields in the image table
186 * @return array
187 */
188 static function selectFields() {
189 return array(
190 'img_name',
191 'img_size',
192 'img_width',
193 'img_height',
194 'img_metadata',
195 'img_bits',
196 'img_media_type',
197 'img_major_mime',
198 'img_minor_mime',
199 'img_description',
200 'img_user',
201 'img_user_text',
202 'img_timestamp',
203 'img_sha1',
204 );
205 }
206
207 /**
208 * Constructor.
209 * Do not call this except from inside a repo class.
210 */
211 function __construct( $title, $repo ) {
212 parent::__construct( $title, $repo );
213
214 $this->metadata = '';
215 $this->historyLine = 0;
216 $this->historyRes = null;
217 $this->dataLoaded = false;
218 $this->extraDataLoaded = false;
219
220 $this->assertRepoDefined();
221 $this->assertTitleDefined();
222 }
223
224 /**
225 * Get the memcached key for the main data for this file, or false if
226 * there is no access to the shared cache.
227 * @return bool
228 */
229 function getCacheKey() {
230 $hashedName = md5( $this->getName() );
231
232 return $this->repo->getSharedCacheKey( 'file', $hashedName );
233 }
234
235 /**
236 * Try to load file metadata from memcached. Returns true on success.
237 * @return bool
238 */
239 function loadFromCache() {
240 global $wgMemc;
241
242 wfProfileIn( __METHOD__ );
243 $this->dataLoaded = false;
244 $this->extraDataLoaded = false;
245 $key = $this->getCacheKey();
246
247 if ( !$key ) {
248 wfProfileOut( __METHOD__ );
249
250 return false;
251 }
252
253 $cachedValues = $wgMemc->get( $key );
254
255 // Check if the key existed and belongs to this version of MediaWiki
256 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION ) {
257 wfDebug( "Pulling file metadata from cache key $key\n" );
258 $this->fileExists = $cachedValues['fileExists'];
259 if ( $this->fileExists ) {
260 $this->setProps( $cachedValues );
261 }
262 $this->dataLoaded = true;
263 $this->extraDataLoaded = true;
264 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
265 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
266 }
267 }
268
269 if ( $this->dataLoaded ) {
270 wfIncrStats( 'image_cache_hit' );
271 } else {
272 wfIncrStats( 'image_cache_miss' );
273 }
274
275 wfProfileOut( __METHOD__ );
276
277 return $this->dataLoaded;
278 }
279
280 /**
281 * Save the file metadata to memcached
282 */
283 function saveToCache() {
284 global $wgMemc;
285
286 $this->load();
287 $key = $this->getCacheKey();
288
289 if ( !$key ) {
290 return;
291 }
292
293 $fields = $this->getCacheFields( '' );
294 $cache = array( 'version' => MW_FILE_VERSION );
295 $cache['fileExists'] = $this->fileExists;
296
297 if ( $this->fileExists ) {
298 foreach ( $fields as $field ) {
299 $cache[$field] = $this->$field;
300 }
301 }
302
303 // Strip off excessive entries from the subset of fields that can become large.
304 // If the cache value gets to large it will not fit in memcached and nothing will
305 // get cached at all, causing master queries for any file access.
306 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
307 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
308 unset( $cache[$field] ); // don't let the value get too big
309 }
310 }
311
312 // Cache presence for 1 week and negatives for 1 day
313 $wgMemc->set( $key, $cache, $this->fileExists ? 86400 * 7 : 86400 );
314 }
315
316 /**
317 * Load metadata from the file itself
318 */
319 function loadFromFile() {
320 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
321 $this->setProps( $props );
322 }
323
324 /**
325 * @param $prefix string
326 * @return array
327 */
328 function getCacheFields( $prefix = 'img_' ) {
329 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
330 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
331 'user_text', 'description' );
332 static $results = array();
333
334 if ( $prefix == '' ) {
335 return $fields;
336 }
337
338 if ( !isset( $results[$prefix] ) ) {
339 $prefixedFields = array();
340 foreach ( $fields as $field ) {
341 $prefixedFields[] = $prefix . $field;
342 }
343 $results[$prefix] = $prefixedFields;
344 }
345
346 return $results[$prefix];
347 }
348
349 /**
350 * @param string $prefix
351 * @return array
352 */
353 function getLazyCacheFields( $prefix = 'img_' ) {
354 static $fields = array( 'metadata' );
355 static $results = array();
356
357 if ( $prefix == '' ) {
358 return $fields;
359 }
360
361 if ( !isset( $results[$prefix] ) ) {
362 $prefixedFields = array();
363 foreach ( $fields as $field ) {
364 $prefixedFields[] = $prefix . $field;
365 }
366 $results[$prefix] = $prefixedFields;
367 }
368
369 return $results[$prefix];
370 }
371
372 /**
373 * Load file metadata from the DB
374 */
375 function loadFromDB() {
376 # Polymorphic function name to distinguish foreign and local fetches
377 $fname = get_class( $this ) . '::' . __FUNCTION__;
378 wfProfileIn( $fname );
379
380 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
381 $this->dataLoaded = true;
382 $this->extraDataLoaded = true;
383
384 $dbr = $this->repo->getMasterDB();
385 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
386 array( 'img_name' => $this->getName() ), $fname );
387
388 if ( $row ) {
389 $this->loadFromRow( $row );
390 } else {
391 $this->fileExists = false;
392 }
393
394 wfProfileOut( $fname );
395 }
396
397 /**
398 * Load lazy file metadata from the DB.
399 * This covers fields that are sometimes not cached.
400 */
401 protected function loadExtraFromDB() {
402 # Polymorphic function name to distinguish foreign and local fetches
403 $fname = get_class( $this ) . '::' . __FUNCTION__;
404 wfProfileIn( $fname );
405
406 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
407 $this->extraDataLoaded = true;
408
409 $dbr = $this->repo->getSlaveDB();
410 // In theory the file could have just been renamed/deleted...oh well
411 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
412 array( 'img_name' => $this->getName() ), $fname );
413
414 if ( !$row ) { // fallback to master
415 $dbr = $this->repo->getMasterDB();
416 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
417 array( 'img_name' => $this->getName() ), $fname );
418 }
419
420 if ( $row ) {
421 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
422 $this->$name = $value;
423 }
424 } else {
425 wfProfileOut( $fname );
426 throw new MWException( "Could not find data for image '{$this->getName()}'." );
427 }
428
429 wfProfileOut( $fname );
430 }
431
432 /**
433 * @param array $row Row
434 * @param string $prefix
435 * @throws MWException
436 * @return array
437 */
438 protected function unprefixRow( $row, $prefix = 'img_' ) {
439 $array = (array)$row;
440 $prefixLength = strlen( $prefix );
441
442 // Sanity check prefix once
443 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
444 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
445 }
446
447 $decoded = array();
448 foreach ( $array as $name => $value ) {
449 $decoded[substr( $name, $prefixLength )] = $value;
450 }
451
452 return $decoded;
453 }
454
455 /**
456 * Decode a row from the database (either object or array) to an array
457 * with timestamps and MIME types decoded, and the field prefix removed.
458 * @param $row
459 * @param $prefix string
460 * @throws MWException
461 * @return array
462 */
463 function decodeRow( $row, $prefix = 'img_' ) {
464 $decoded = $this->unprefixRow( $row, $prefix );
465
466 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
467
468 if ( empty( $decoded['major_mime'] ) ) {
469 $decoded['mime'] = 'unknown/unknown';
470 } else {
471 if ( !$decoded['minor_mime'] ) {
472 $decoded['minor_mime'] = 'unknown';
473 }
474 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
475 }
476
477 # Trim zero padding from char/binary field
478 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
479
480 return $decoded;
481 }
482
483 /**
484 * Load file metadata from a DB result row
485 */
486 function loadFromRow( $row, $prefix = 'img_' ) {
487 $this->dataLoaded = true;
488 $this->extraDataLoaded = true;
489
490 $array = $this->decodeRow( $row, $prefix );
491
492 foreach ( $array as $name => $value ) {
493 $this->$name = $value;
494 }
495
496 $this->fileExists = true;
497 $this->maybeUpgradeRow();
498 }
499
500 /**
501 * Load file metadata from cache or DB, unless already loaded
502 * @param integer $flags
503 */
504 function load( $flags = 0 ) {
505 if ( !$this->dataLoaded ) {
506 if ( !$this->loadFromCache() ) {
507 $this->loadFromDB();
508 $this->saveToCache();
509 }
510 $this->dataLoaded = true;
511 }
512 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
513 $this->loadExtraFromDB();
514 }
515 }
516
517 /**
518 * Upgrade a row if it needs it
519 */
520 function maybeUpgradeRow() {
521 global $wgUpdateCompatibleMetadata;
522 if ( wfReadOnly() ) {
523 return;
524 }
525
526 if ( is_null( $this->media_type ) ||
527 $this->mime == 'image/svg'
528 ) {
529 $this->upgradeRow();
530 $this->upgraded = true;
531 } else {
532 $handler = $this->getHandler();
533 if ( $handler ) {
534 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
535 if ( $validity === MediaHandler::METADATA_BAD
536 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
537 ) {
538 $this->upgradeRow();
539 $this->upgraded = true;
540 }
541 }
542 }
543 }
544
545 function getUpgraded() {
546 return $this->upgraded;
547 }
548
549 /**
550 * Fix assorted version-related problems with the image row by reloading it from the file
551 */
552 function upgradeRow() {
553 wfProfileIn( __METHOD__ );
554
555 $this->lock(); // begin
556
557 $this->loadFromFile();
558
559 # Don't destroy file info of missing files
560 if ( !$this->fileExists ) {
561 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
562 wfProfileOut( __METHOD__ );
563
564 return;
565 }
566
567 $dbw = $this->repo->getMasterDB();
568 list( $major, $minor ) = self::splitMime( $this->mime );
569
570 if ( wfReadOnly() ) {
571 wfProfileOut( __METHOD__ );
572
573 return;
574 }
575 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
576
577 $dbw->update( 'image',
578 array(
579 'img_size' => $this->size, // sanity
580 'img_width' => $this->width,
581 'img_height' => $this->height,
582 'img_bits' => $this->bits,
583 'img_media_type' => $this->media_type,
584 'img_major_mime' => $major,
585 'img_minor_mime' => $minor,
586 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
587 'img_sha1' => $this->sha1,
588 ),
589 array( 'img_name' => $this->getName() ),
590 __METHOD__
591 );
592
593 $this->saveToCache();
594
595 $this->unlock(); // done
596
597 wfProfileOut( __METHOD__ );
598 }
599
600 /**
601 * Set properties in this object to be equal to those given in the
602 * associative array $info. Only cacheable fields can be set.
603 * All fields *must* be set in $info except for getLazyCacheFields().
604 *
605 * If 'mime' is given, it will be split into major_mime/minor_mime.
606 * If major_mime/minor_mime are given, $this->mime will also be set.
607 */
608 function setProps( $info ) {
609 $this->dataLoaded = true;
610 $fields = $this->getCacheFields( '' );
611 $fields[] = 'fileExists';
612
613 foreach ( $fields as $field ) {
614 if ( isset( $info[$field] ) ) {
615 $this->$field = $info[$field];
616 }
617 }
618
619 // Fix up mime fields
620 if ( isset( $info['major_mime'] ) ) {
621 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
622 } elseif ( isset( $info['mime'] ) ) {
623 $this->mime = $info['mime'];
624 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
625 }
626 }
627
628 /** splitMime inherited */
629 /** getName inherited */
630 /** getTitle inherited */
631 /** getURL inherited */
632 /** getViewURL inherited */
633 /** getPath inherited */
634 /** isVisible inhereted */
635
636 /**
637 * @return bool
638 */
639 function isMissing() {
640 if ( $this->missing === null ) {
641 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
642 $this->missing = !$fileExists;
643 }
644
645 return $this->missing;
646 }
647
648 /**
649 * Return the width of the image
650 *
651 * @param int $page
652 * @return int
653 */
654 public function getWidth( $page = 1 ) {
655 $this->load();
656
657 if ( $this->isMultipage() ) {
658 $handler = $this->getHandler();
659 if ( !$handler ) {
660 return 0;
661 }
662 $dim = $handler->getPageDimensions( $this, $page );
663 if ( $dim ) {
664 return $dim['width'];
665 } else {
666 // For non-paged media, the false goes through an
667 // intval, turning failure into 0, so do same here.
668 return 0;
669 }
670 } else {
671 return $this->width;
672 }
673 }
674
675 /**
676 * Return the height of the image
677 *
678 * @param int $page
679 * @return int
680 */
681 public function getHeight( $page = 1 ) {
682 $this->load();
683
684 if ( $this->isMultipage() ) {
685 $handler = $this->getHandler();
686 if ( !$handler ) {
687 return 0;
688 }
689 $dim = $handler->getPageDimensions( $this, $page );
690 if ( $dim ) {
691 return $dim['height'];
692 } else {
693 // For non-paged media, the false goes through an
694 // intval, turning failure into 0, so do same here.
695 return 0;
696 }
697 } else {
698 return $this->height;
699 }
700 }
701
702 /**
703 * Returns ID or name of user who uploaded the file
704 *
705 * @param string $type 'text' or 'id'
706 * @return int|string
707 */
708 function getUser( $type = 'text' ) {
709 $this->load();
710
711 if ( $type == 'text' ) {
712 return $this->user_text;
713 } elseif ( $type == 'id' ) {
714 return $this->user;
715 }
716 }
717
718 /**
719 * Get handler-specific metadata
720 * @return string
721 */
722 function getMetadata() {
723 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
724 return $this->metadata;
725 }
726
727 /**
728 * @return int
729 */
730 function getBitDepth() {
731 $this->load();
732
733 return $this->bits;
734 }
735
736 /**
737 * Returns the size of the image file, in bytes
738 * @return int
739 */
740 public function getSize() {
741 $this->load();
742
743 return $this->size;
744 }
745
746 /**
747 * Returns the mime type of the file.
748 * @return string
749 */
750 function getMimeType() {
751 $this->load();
752
753 return $this->mime;
754 }
755
756 /**
757 * Returns the type of the media in the file.
758 * Use the value returned by this function with the MEDIATYPE_xxx constants.
759 * @return string
760 */
761 function getMediaType() {
762 $this->load();
763
764 return $this->media_type;
765 }
766
767 /** canRender inherited */
768 /** mustRender inherited */
769 /** allowInlineDisplay inherited */
770 /** isSafeFile inherited */
771 /** isTrustedFile inherited */
772
773 /**
774 * Returns true if the file exists on disk.
775 * @return bool Whether file exist on disk.
776 */
777 public function exists() {
778 $this->load();
779
780 return $this->fileExists;
781 }
782
783 /** getTransformScript inherited */
784 /** getUnscaledThumb inherited */
785 /** thumbName inherited */
786 /** createThumb inherited */
787 /** transform inherited */
788
789 /**
790 * Fix thumbnail files from 1.4 or before, with extreme prejudice
791 * @todo Do we still care about this? Perhaps a maintenance script
792 * can be made instead. Enabling this code results in a serious
793 * RTT regression for wikis without 404 handling.
794 */
795 function migrateThumbFile( $thumbName ) {
796 /* Old code for bug 2532
797 $thumbDir = $this->getThumbPath();
798 $thumbPath = "$thumbDir/$thumbName";
799 if ( is_dir( $thumbPath ) ) {
800 // Directory where file should be
801 // This happened occasionally due to broken migration code in 1.5
802 // Rename to broken-*
803 for ( $i = 0; $i < 100; $i++ ) {
804 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
805 if ( !file_exists( $broken ) ) {
806 rename( $thumbPath, $broken );
807 break;
808 }
809 }
810 // Doesn't exist anymore
811 clearstatcache();
812 }
813 */
814 /*
815 if ( $this->repo->fileExists( $thumbDir ) ) {
816 // Delete file where directory should be
817 $this->repo->cleanupBatch( array( $thumbDir ) );
818 }
819 */
820 }
821
822 /** getHandler inherited */
823 /** iconThumb inherited */
824 /** getLastError inherited */
825
826 /**
827 * Get all thumbnail names previously generated for this file
828 * @param string|bool $archiveName Name of an archive file, default false
829 * @return array first element is the base dir, then files in that base dir.
830 */
831 function getThumbnails( $archiveName = false ) {
832 if ( $archiveName ) {
833 $dir = $this->getArchiveThumbPath( $archiveName );
834 } else {
835 $dir = $this->getThumbPath();
836 }
837
838 $backend = $this->repo->getBackend();
839 $files = array( $dir );
840 try {
841 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
842 foreach ( $iterator as $file ) {
843 $files[] = $file;
844 }
845 } catch ( FileBackendError $e ) {
846 } // suppress (bug 54674)
847
848 return $files;
849 }
850
851 /**
852 * Refresh metadata in memcached, but don't touch thumbnails or squid
853 */
854 function purgeMetadataCache() {
855 $this->loadFromDB();
856 $this->saveToCache();
857 $this->purgeHistory();
858 }
859
860 /**
861 * Purge the shared history (OldLocalFile) cache.
862 *
863 * @note This used to purge old thumbnails as well.
864 */
865 function purgeHistory() {
866 global $wgMemc;
867
868 $hashedName = md5( $this->getName() );
869 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
870
871 if ( $oldKey ) {
872 $wgMemc->delete( $oldKey );
873 }
874 }
875
876 /**
877 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
878 *
879 * @param array $options An array potentially with the key forThumbRefresh.
880 *
881 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
882 */
883 function purgeCache( $options = array() ) {
884 wfProfileIn( __METHOD__ );
885 // Refresh metadata cache
886 $this->purgeMetadataCache();
887
888 // Delete thumbnails
889 $this->purgeThumbnails( $options );
890
891 // Purge squid cache for this file
892 SquidUpdate::purge( array( $this->getURL() ) );
893 wfProfileOut( __METHOD__ );
894 }
895
896 /**
897 * Delete cached transformed files for an archived version only.
898 * @param string $archiveName Name of the archived file
899 */
900 function purgeOldThumbnails( $archiveName ) {
901 global $wgUseSquid;
902 wfProfileIn( __METHOD__ );
903
904 // Get a list of old thumbnails and URLs
905 $files = $this->getThumbnails( $archiveName );
906
907 // Purge any custom thumbnail caches
908 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
909
910 $dir = array_shift( $files );
911 $this->purgeThumbList( $dir, $files );
912
913 // Purge the squid
914 if ( $wgUseSquid ) {
915 $urls = array();
916 foreach ( $files as $file ) {
917 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
918 }
919 SquidUpdate::purge( $urls );
920 }
921
922 wfProfileOut( __METHOD__ );
923 }
924
925 /**
926 * Delete cached transformed files for the current version only.
927 */
928 function purgeThumbnails( $options = array() ) {
929 global $wgUseSquid;
930 wfProfileIn( __METHOD__ );
931
932 // Delete thumbnails
933 $files = $this->getThumbnails();
934 // Always purge all files from squid regardless of handler filters
935 $urls = array();
936 if ( $wgUseSquid ) {
937 foreach ( $files as $file ) {
938 $urls[] = $this->getThumbUrl( $file );
939 }
940 array_shift( $urls ); // don't purge directory
941 }
942
943 // Give media handler a chance to filter the file purge list
944 if ( !empty( $options['forThumbRefresh'] ) ) {
945 $handler = $this->getHandler();
946 if ( $handler ) {
947 $handler->filterThumbnailPurgeList( $files, $options );
948 }
949 }
950
951 // Purge any custom thumbnail caches
952 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
953
954 $dir = array_shift( $files );
955 $this->purgeThumbList( $dir, $files );
956
957 // Purge the squid
958 if ( $wgUseSquid ) {
959 SquidUpdate::purge( $urls );
960 }
961
962 wfProfileOut( __METHOD__ );
963 }
964
965 /**
966 * Delete a list of thumbnails visible at urls
967 * @param string $dir Base dir of the files.
968 * @param array $files Array of strings: relative filenames (to $dir)
969 */
970 protected function purgeThumbList( $dir, $files ) {
971 $fileListDebug = strtr(
972 var_export( $files, true ),
973 array( "\n" => '' )
974 );
975 wfDebug( __METHOD__ . ": $fileListDebug\n" );
976
977 $purgeList = array();
978 foreach ( $files as $file ) {
979 # Check that the base file name is part of the thumb name
980 # This is a basic sanity check to avoid erasing unrelated directories
981 if ( strpos( $file, $this->getName() ) !== false
982 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
983 ) {
984 $purgeList[] = "{$dir}/{$file}";
985 }
986 }
987
988 # Delete the thumbnails
989 $this->repo->quickPurgeBatch( $purgeList );
990 # Clear out the thumbnail directory if empty
991 $this->repo->quickCleanDir( $dir );
992 }
993
994 /** purgeDescription inherited */
995 /** purgeEverything inherited */
996
997 /**
998 * @param int $limit Optional: Limit to number of results
999 * @param int $start Optional: Timestamp, start from
1000 * @param int $end Optional: Timestamp, end at
1001 * @param bool $inc
1002 * @return array
1003 */
1004 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1005 $dbr = $this->repo->getSlaveDB();
1006 $tables = array( 'oldimage' );
1007 $fields = OldLocalFile::selectFields();
1008 $conds = $opts = $join_conds = array();
1009 $eq = $inc ? '=' : '';
1010 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1011
1012 if ( $start ) {
1013 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1014 }
1015
1016 if ( $end ) {
1017 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1018 }
1019
1020 if ( $limit ) {
1021 $opts['LIMIT'] = $limit;
1022 }
1023
1024 // Search backwards for time > x queries
1025 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1026 $opts['ORDER BY'] = "oi_timestamp $order";
1027 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1028
1029 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1030 &$conds, &$opts, &$join_conds ) );
1031
1032 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1033 $r = array();
1034
1035 foreach ( $res as $row ) {
1036 $r[] = $this->repo->newFileFromRow( $row );
1037 }
1038
1039 if ( $order == 'ASC' ) {
1040 $r = array_reverse( $r ); // make sure it ends up descending
1041 }
1042
1043 return $r;
1044 }
1045
1046 /**
1047 * Returns the history of this file, line by line.
1048 * starts with current version, then old versions.
1049 * uses $this->historyLine to check which line to return:
1050 * 0 return line for current version
1051 * 1 query for old versions, return first one
1052 * 2, ... return next old version from above query
1053 * @return bool
1054 */
1055 public function nextHistoryLine() {
1056 # Polymorphic function name to distinguish foreign and local fetches
1057 $fname = get_class( $this ) . '::' . __FUNCTION__;
1058
1059 $dbr = $this->repo->getSlaveDB();
1060
1061 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1062 $this->historyRes = $dbr->select( 'image',
1063 array(
1064 '*',
1065 "'' AS oi_archive_name",
1066 '0 as oi_deleted',
1067 'img_sha1'
1068 ),
1069 array( 'img_name' => $this->title->getDBkey() ),
1070 $fname
1071 );
1072
1073 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1074 $this->historyRes = null;
1075
1076 return false;
1077 }
1078 } elseif ( $this->historyLine == 1 ) {
1079 $this->historyRes = $dbr->select( 'oldimage', '*',
1080 array( 'oi_name' => $this->title->getDBkey() ),
1081 $fname,
1082 array( 'ORDER BY' => 'oi_timestamp DESC' )
1083 );
1084 }
1085 $this->historyLine++;
1086
1087 return $dbr->fetchObject( $this->historyRes );
1088 }
1089
1090 /**
1091 * Reset the history pointer to the first element of the history
1092 */
1093 public function resetHistory() {
1094 $this->historyLine = 0;
1095
1096 if ( !is_null( $this->historyRes ) ) {
1097 $this->historyRes = null;
1098 }
1099 }
1100
1101 /** getHashPath inherited */
1102 /** getRel inherited */
1103 /** getUrlRel inherited */
1104 /** getArchiveRel inherited */
1105 /** getArchivePath inherited */
1106 /** getThumbPath inherited */
1107 /** getArchiveUrl inherited */
1108 /** getThumbUrl inherited */
1109 /** getArchiveVirtualUrl inherited */
1110 /** getThumbVirtualUrl inherited */
1111 /** isHashed inherited */
1112
1113 /**
1114 * Upload a file and record it in the DB
1115 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1116 * @param string $comment Upload description
1117 * @param string $pageText Text to use for the new description page,
1118 * if a new description page is created
1119 * @param int|bool $flags Flags for publish()
1120 * @param array|bool $props File properties, if known. This can be used to
1121 * reduce the upload time when uploading virtual URLs for which the file
1122 * info is already known
1123 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1124 * current time
1125 * @param User|null $user User object or null to use $wgUser
1126 *
1127 * @return FileRepoStatus object. On success, the value member contains the
1128 * archive name, or an empty string if it was a new file.
1129 */
1130 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1131 $timestamp = false, $user = null
1132 ) {
1133 global $wgContLang;
1134
1135 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1136 return $this->readOnlyFatalStatus();
1137 }
1138
1139 if ( !$props ) {
1140 wfProfileIn( __METHOD__ . '-getProps' );
1141 if ( $this->repo->isVirtualUrl( $srcPath )
1142 || FileBackend::isStoragePath( $srcPath )
1143 ) {
1144 $props = $this->repo->getFileProps( $srcPath );
1145 } else {
1146 $props = FSFile::getPropsFromPath( $srcPath );
1147 }
1148 wfProfileOut( __METHOD__ . '-getProps' );
1149 }
1150
1151 $options = array();
1152 $handler = MediaHandler::getHandler( $props['mime'] );
1153 if ( $handler ) {
1154 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1155 } else {
1156 $options['headers'] = array();
1157 }
1158
1159 // Trim spaces on user supplied text
1160 $comment = trim( $comment );
1161
1162 // truncate nicely or the DB will do it for us
1163 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1164 $comment = $wgContLang->truncate( $comment, 255 );
1165 $this->lock(); // begin
1166 $status = $this->publish( $srcPath, $flags, $options );
1167
1168 if ( $status->successCount > 0 ) {
1169 # Essentially we are displacing any existing current file and saving
1170 # a new current file at the old location. If just the first succeeded,
1171 # we still need to displace the current DB entry and put in a new one.
1172 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
1173 $status->fatal( 'filenotfound', $srcPath );
1174 }
1175 }
1176
1177 $this->unlock(); // done
1178
1179 return $status;
1180 }
1181
1182 /**
1183 * Record a file upload in the upload log and the image table
1184 * @param string $oldver
1185 * @param string $desc
1186 * @param string $license
1187 * @param string $copyStatus
1188 * @param string $source
1189 * @param bool $watch
1190 * @param string|bool $timestamp
1191 * @param User|null $user User object or null to use $wgUser
1192 * @return bool
1193 */
1194 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1195 $watch = false, $timestamp = false, User $user = null ) {
1196 if ( !$user ) {
1197 global $wgUser;
1198 $user = $wgUser;
1199 }
1200
1201 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1202
1203 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1204 return false;
1205 }
1206
1207 if ( $watch ) {
1208 $user->addWatch( $this->getTitle() );
1209 }
1210
1211 return true;
1212 }
1213
1214 /**
1215 * Record a file upload in the upload log and the image table
1216 * @param string $oldver
1217 * @param string $comment
1218 * @param string $pageText
1219 * @param bool|array $props
1220 * @param string|bool $timestamp
1221 * @param null|User $user
1222 * @return bool
1223 */
1224 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1225 $user = null
1226 ) {
1227 wfProfileIn( __METHOD__ );
1228
1229 if ( is_null( $user ) ) {
1230 global $wgUser;
1231 $user = $wgUser;
1232 }
1233
1234 $dbw = $this->repo->getMasterDB();
1235 $dbw->begin( __METHOD__ );
1236
1237 if ( !$props ) {
1238 wfProfileIn( __METHOD__ . '-getProps' );
1239 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
1240 wfProfileOut( __METHOD__ . '-getProps' );
1241 }
1242
1243 if ( $timestamp === false ) {
1244 $timestamp = $dbw->timestamp();
1245 }
1246
1247 $props['description'] = $comment;
1248 $props['user'] = $user->getId();
1249 $props['user_text'] = $user->getName();
1250 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1251 $this->setProps( $props );
1252
1253 # Fail now if the file isn't there
1254 if ( !$this->fileExists ) {
1255 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1256 wfProfileOut( __METHOD__ );
1257
1258 return false;
1259 }
1260
1261 $reupload = false;
1262
1263 # Test to see if the row exists using INSERT IGNORE
1264 # This avoids race conditions by locking the row until the commit, and also
1265 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1266 $dbw->insert( 'image',
1267 array(
1268 'img_name' => $this->getName(),
1269 'img_size' => $this->size,
1270 'img_width' => intval( $this->width ),
1271 'img_height' => intval( $this->height ),
1272 'img_bits' => $this->bits,
1273 'img_media_type' => $this->media_type,
1274 'img_major_mime' => $this->major_mime,
1275 'img_minor_mime' => $this->minor_mime,
1276 'img_timestamp' => $timestamp,
1277 'img_description' => $comment,
1278 'img_user' => $user->getId(),
1279 'img_user_text' => $user->getName(),
1280 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1281 'img_sha1' => $this->sha1
1282 ),
1283 __METHOD__,
1284 'IGNORE'
1285 );
1286 if ( $dbw->affectedRows() == 0 ) {
1287 # (bug 34993) Note: $oldver can be empty here, if the previous
1288 # version of the file was broken. Allow registration of the new
1289 # version to continue anyway, because that's better than having
1290 # an image that's not fixable by user operations.
1291
1292 $reupload = true;
1293 # Collision, this is an update of a file
1294 # Insert previous contents into oldimage
1295 $dbw->insertSelect( 'oldimage', 'image',
1296 array(
1297 'oi_name' => 'img_name',
1298 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1299 'oi_size' => 'img_size',
1300 'oi_width' => 'img_width',
1301 'oi_height' => 'img_height',
1302 'oi_bits' => 'img_bits',
1303 'oi_timestamp' => 'img_timestamp',
1304 'oi_description' => 'img_description',
1305 'oi_user' => 'img_user',
1306 'oi_user_text' => 'img_user_text',
1307 'oi_metadata' => 'img_metadata',
1308 'oi_media_type' => 'img_media_type',
1309 'oi_major_mime' => 'img_major_mime',
1310 'oi_minor_mime' => 'img_minor_mime',
1311 'oi_sha1' => 'img_sha1'
1312 ),
1313 array( 'img_name' => $this->getName() ),
1314 __METHOD__
1315 );
1316
1317 # Update the current image row
1318 $dbw->update( 'image',
1319 array( /* SET */
1320 'img_size' => $this->size,
1321 'img_width' => intval( $this->width ),
1322 'img_height' => intval( $this->height ),
1323 'img_bits' => $this->bits,
1324 'img_media_type' => $this->media_type,
1325 'img_major_mime' => $this->major_mime,
1326 'img_minor_mime' => $this->minor_mime,
1327 'img_timestamp' => $timestamp,
1328 'img_description' => $comment,
1329 'img_user' => $user->getId(),
1330 'img_user_text' => $user->getName(),
1331 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1332 'img_sha1' => $this->sha1
1333 ),
1334 array( 'img_name' => $this->getName() ),
1335 __METHOD__
1336 );
1337 } else {
1338 # This is a new file, so update the image count
1339 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
1340 }
1341
1342 $descTitle = $this->getTitle();
1343 $wikiPage = new WikiFilePage( $descTitle );
1344 $wikiPage->setFile( $this );
1345
1346 # Add the log entry
1347 $action = $reupload ? 'overwrite' : 'upload';
1348
1349 $logEntry = new ManualLogEntry( 'upload', $action );
1350 $logEntry->setPerformer( $user );
1351 $logEntry->setComment( $comment );
1352 $logEntry->setTarget( $descTitle );
1353
1354 // Allow people using the api to associate log entries with the upload.
1355 // Log has a timestamp, but sometimes different from upload timestamp.
1356 $logEntry->setParameters(
1357 array(
1358 'img_sha1' => $this->sha1,
1359 'img_timestamp' => $timestamp,
1360 )
1361 );
1362 // Note we keep $logId around since during new image
1363 // creation, page doesn't exist yet, so log_page = 0
1364 // but we want it to point to the page we're making,
1365 // so we later modify the log entry.
1366 // For a similar reason, we avoid making an RC entry
1367 // now and wait until the page exists.
1368 $logId = $logEntry->insert();
1369
1370 $exists = $descTitle->exists();
1371 if ( $exists ) {
1372 // Page exists, do RC entry now (otherwise we wait for later).
1373 $logEntry->publish( $logId );
1374 }
1375 wfProfileIn( __METHOD__ . '-edit' );
1376
1377 if ( $exists ) {
1378 # Create a null revision
1379 $latest = $descTitle->getLatestRevID();
1380 $editSummary = LogFormatter::newFromEntry( $logEntry )->getPlainActionText();
1381
1382 $nullRevision = Revision::newNullRevision(
1383 $dbw,
1384 $descTitle->getArticleID(),
1385 $editSummary,
1386 false
1387 );
1388 if ( !is_null( $nullRevision ) ) {
1389 $nullRevision->insertOn( $dbw );
1390
1391 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1392 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1393 }
1394 }
1395
1396 # Commit the transaction now, in case something goes wrong later
1397 # The most important thing is that files don't get lost, especially archives
1398 # NOTE: once we have support for nested transactions, the commit may be moved
1399 # to after $wikiPage->doEdit has been called.
1400 $dbw->commit( __METHOD__ );
1401
1402 if ( $exists ) {
1403 # Invalidate the cache for the description page
1404 $descTitle->invalidateCache();
1405 $descTitle->purgeSquid();
1406 } else {
1407 # New file; create the description page.
1408 # There's already a log entry, so don't make a second RC entry
1409 # Squid and file cache for the description page are purged by doEditContent.
1410 $content = ContentHandler::makeContent( $pageText, $descTitle );
1411 $status = $wikiPage->doEditContent(
1412 $content,
1413 $comment,
1414 EDIT_NEW | EDIT_SUPPRESS_RC,
1415 false,
1416 $user
1417 );
1418
1419 $dbw->begin( __METHOD__ ); // XXX; doEdit() uses a transaction
1420 // Now that the page exists, make an RC entry.
1421 $logEntry->publish( $logId );
1422 if ( isset( $status->value['revision'] ) ) {
1423 $dbw->update( 'logging',
1424 array( 'log_page' => $status->value['revision']->getPage() ),
1425 array( 'log_id' => $logId ),
1426 __METHOD__
1427 );
1428 }
1429 $dbw->commit( __METHOD__ ); // commit before anything bad can happen
1430 }
1431
1432 wfProfileOut( __METHOD__ . '-edit' );
1433
1434 # Save to cache and purge the squid
1435 # We shall not saveToCache before the commit since otherwise
1436 # in case of a rollback there is an usable file from memcached
1437 # which in fact doesn't really exist (bug 24978)
1438 $this->saveToCache();
1439
1440 if ( $reupload ) {
1441 # Delete old thumbnails
1442 wfProfileIn( __METHOD__ . '-purge' );
1443 $this->purgeThumbnails();
1444 wfProfileOut( __METHOD__ . '-purge' );
1445
1446 # Remove the old file from the squid cache
1447 SquidUpdate::purge( array( $this->getURL() ) );
1448 }
1449
1450 # Hooks, hooks, the magic of hooks...
1451 wfProfileIn( __METHOD__ . '-hooks' );
1452 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1453 wfProfileOut( __METHOD__ . '-hooks' );
1454
1455 # Invalidate cache for all pages using this file
1456 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1457 $update->doUpdate();
1458 if ( !$reupload ) {
1459 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1460 }
1461
1462 wfProfileOut( __METHOD__ );
1463
1464 return true;
1465 }
1466
1467 /**
1468 * Move or copy a file to its public location. If a file exists at the
1469 * destination, move it to an archive. Returns a FileRepoStatus object with
1470 * the archive name in the "value" member on success.
1471 *
1472 * The archive name should be passed through to recordUpload for database
1473 * registration.
1474 *
1475 * @param string $srcPath Local filesystem path to the source image
1476 * @param int $flags A bitwise combination of:
1477 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1478 * @param array $options Optional additional parameters
1479 * @return FileRepoStatus On success, the value member contains the
1480 * archive name, or an empty string if it was a new file.
1481 */
1482 function publish( $srcPath, $flags = 0, array $options = array() ) {
1483 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1484 }
1485
1486 /**
1487 * Move or copy a file to a specified location. Returns a FileRepoStatus
1488 * object with the archive name in the "value" member on success.
1489 *
1490 * The archive name should be passed through to recordUpload for database
1491 * registration.
1492 *
1493 * @param string $srcPath Local filesystem path to the source image
1494 * @param string $dstRel Target relative path
1495 * @param int $flags A bitwise combination of:
1496 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1497 * @param array $options Optional additional parameters
1498 * @return FileRepoStatus On success, the value member contains the
1499 * archive name, or an empty string if it was a new file.
1500 */
1501 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1502 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1503 return $this->readOnlyFatalStatus();
1504 }
1505
1506 $this->lock(); // begin
1507
1508 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1509 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1510 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1511 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1512
1513 if ( $status->value == 'new' ) {
1514 $status->value = '';
1515 } else {
1516 $status->value = $archiveName;
1517 }
1518
1519 $this->unlock(); // done
1520
1521 return $status;
1522 }
1523
1524 /** getLinksTo inherited */
1525 /** getExifData inherited */
1526 /** isLocal inherited */
1527 /** wasDeleted inherited */
1528
1529 /**
1530 * Move file to the new title
1531 *
1532 * Move current, old version and all thumbnails
1533 * to the new filename. Old file is deleted.
1534 *
1535 * Cache purging is done; checks for validity
1536 * and logging are caller's responsibility
1537 *
1538 * @param Title $target New file name
1539 * @return FileRepoStatus
1540 */
1541 function move( $target ) {
1542 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1543 return $this->readOnlyFatalStatus();
1544 }
1545
1546 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1547 $batch = new LocalFileMoveBatch( $this, $target );
1548
1549 $this->lock(); // begin
1550 $batch->addCurrent();
1551 $archiveNames = $batch->addOlds();
1552 $status = $batch->execute();
1553 $this->unlock(); // done
1554
1555 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1556
1557 // Purge the source and target files...
1558 $oldTitleFile = wfLocalFile( $this->title );
1559 $newTitleFile = wfLocalFile( $target );
1560 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1561 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1562 $this->getRepo()->getMasterDB()->onTransactionIdle(
1563 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1564 $oldTitleFile->purgeEverything();
1565 foreach ( $archiveNames as $archiveName ) {
1566 $oldTitleFile->purgeOldThumbnails( $archiveName );
1567 }
1568 $newTitleFile->purgeEverything();
1569 }
1570 );
1571
1572 if ( $status->isOK() ) {
1573 // Now switch the object
1574 $this->title = $target;
1575 // Force regeneration of the name and hashpath
1576 unset( $this->name );
1577 unset( $this->hashPath );
1578 }
1579
1580 return $status;
1581 }
1582
1583 /**
1584 * Delete all versions of the file.
1585 *
1586 * Moves the files into an archive directory (or deletes them)
1587 * and removes the database rows.
1588 *
1589 * Cache purging is done; logging is caller's responsibility.
1590 *
1591 * @param string $reason
1592 * @param bool $suppress
1593 * @return FileRepoStatus
1594 */
1595 function delete( $reason, $suppress = false ) {
1596 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1597 return $this->readOnlyFatalStatus();
1598 }
1599
1600 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1601
1602 $this->lock(); // begin
1603 $batch->addCurrent();
1604 # Get old version relative paths
1605 $archiveNames = $batch->addOlds();
1606 $status = $batch->execute();
1607 $this->unlock(); // done
1608
1609 if ( $status->isOK() ) {
1610 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1611 }
1612
1613 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1614 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1615 $file = $this;
1616 $this->getRepo()->getMasterDB()->onTransactionIdle(
1617 function () use ( $file, $archiveNames ) {
1618 global $wgUseSquid;
1619
1620 $file->purgeEverything();
1621 foreach ( $archiveNames as $archiveName ) {
1622 $file->purgeOldThumbnails( $archiveName );
1623 }
1624
1625 if ( $wgUseSquid ) {
1626 // Purge the squid
1627 $purgeUrls = array();
1628 foreach ( $archiveNames as $archiveName ) {
1629 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1630 }
1631 SquidUpdate::purge( $purgeUrls );
1632 }
1633 }
1634 );
1635
1636 return $status;
1637 }
1638
1639 /**
1640 * Delete an old version of the file.
1641 *
1642 * Moves the file into an archive directory (or deletes it)
1643 * and removes the database row.
1644 *
1645 * Cache purging is done; logging is caller's responsibility.
1646 *
1647 * @param string $archiveName
1648 * @param string $reason
1649 * @param bool $suppress
1650 * @throws MWException Exception on database or file store failure
1651 * @return FileRepoStatus
1652 */
1653 function deleteOld( $archiveName, $reason, $suppress = false ) {
1654 global $wgUseSquid;
1655 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1656 return $this->readOnlyFatalStatus();
1657 }
1658
1659 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1660
1661 $this->lock(); // begin
1662 $batch->addOld( $archiveName );
1663 $status = $batch->execute();
1664 $this->unlock(); // done
1665
1666 $this->purgeOldThumbnails( $archiveName );
1667 if ( $status->isOK() ) {
1668 $this->purgeDescription();
1669 $this->purgeHistory();
1670 }
1671
1672 if ( $wgUseSquid ) {
1673 // Purge the squid
1674 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1675 }
1676
1677 return $status;
1678 }
1679
1680 /**
1681 * Restore all or specified deleted revisions to the given file.
1682 * Permissions and logging are left to the caller.
1683 *
1684 * May throw database exceptions on error.
1685 *
1686 * @param array $versions set of record ids of deleted items to restore,
1687 * or empty to restore all revisions.
1688 * @param bool $unsuppress
1689 * @return FileRepoStatus
1690 */
1691 function restore( $versions = array(), $unsuppress = false ) {
1692 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1693 return $this->readOnlyFatalStatus();
1694 }
1695
1696 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1697
1698 $this->lock(); // begin
1699 if ( !$versions ) {
1700 $batch->addAll();
1701 } else {
1702 $batch->addIds( $versions );
1703 }
1704 $status = $batch->execute();
1705 if ( $status->isGood() ) {
1706 $cleanupStatus = $batch->cleanup();
1707 $cleanupStatus->successCount = 0;
1708 $cleanupStatus->failCount = 0;
1709 $status->merge( $cleanupStatus );
1710 }
1711 $this->unlock(); // done
1712
1713 return $status;
1714 }
1715
1716 /** isMultipage inherited */
1717 /** pageCount inherited */
1718 /** scaleHeight inherited */
1719 /** getImageSize inherited */
1720
1721 /**
1722 * Get the URL of the file description page.
1723 * @return string
1724 */
1725 function getDescriptionUrl() {
1726 return $this->title->getLocalURL();
1727 }
1728
1729 /**
1730 * Get the HTML text of the description page
1731 * This is not used by ImagePage for local files, since (among other things)
1732 * it skips the parser cache.
1733 *
1734 * @param Language $lang What language to get description in (Optional)
1735 * @return bool|mixed
1736 */
1737 function getDescriptionText( $lang = null ) {
1738 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1739 if ( !$revision ) {
1740 return false;
1741 }
1742 $content = $revision->getContent();
1743 if ( !$content ) {
1744 return false;
1745 }
1746 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1747
1748 return $pout->getText();
1749 }
1750
1751 /**
1752 * @param int $audience
1753 * @param User $user
1754 * @return string
1755 */
1756 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1757 $this->load();
1758 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1759 return '';
1760 } elseif ( $audience == self::FOR_THIS_USER
1761 && !$this->userCan( self::DELETED_COMMENT, $user )
1762 ) {
1763 return '';
1764 } else {
1765 return $this->description;
1766 }
1767 }
1768
1769 /**
1770 * @return bool|string
1771 */
1772 function getTimestamp() {
1773 $this->load();
1774
1775 return $this->timestamp;
1776 }
1777
1778 /**
1779 * @return string
1780 */
1781 function getSha1() {
1782 $this->load();
1783 // Initialise now if necessary
1784 if ( $this->sha1 == '' && $this->fileExists ) {
1785 $this->lock(); // begin
1786
1787 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1788 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1789 $dbw = $this->repo->getMasterDB();
1790 $dbw->update( 'image',
1791 array( 'img_sha1' => $this->sha1 ),
1792 array( 'img_name' => $this->getName() ),
1793 __METHOD__ );
1794 $this->saveToCache();
1795 }
1796
1797 $this->unlock(); // done
1798 }
1799
1800 return $this->sha1;
1801 }
1802
1803 /**
1804 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1805 */
1806 function isCacheable() {
1807 $this->load();
1808
1809 // If extra data (metadata) was not loaded then it must have been large
1810 return $this->extraDataLoaded
1811 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1812 }
1813
1814 /**
1815 * Start a transaction and lock the image for update
1816 * Increments a reference counter if the lock is already held
1817 * @throws MWException
1818 * @return bool True if the image exists, false otherwise
1819 */
1820 function lock() {
1821 $dbw = $this->repo->getMasterDB();
1822
1823 if ( !$this->locked ) {
1824 if ( !$dbw->trxLevel() ) {
1825 $dbw->begin( __METHOD__ );
1826 $this->lockedOwnTrx = true;
1827 }
1828 $this->locked++;
1829 // Bug 54736: use simple lock to handle when the file does not exist.
1830 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1831 $cache = wfGetMainCache();
1832 $key = $this->getCacheKey();
1833 if ( !$cache->lock( $key, 60 ) ) {
1834 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1835 }
1836 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1837 $cache->unlock( $key ); // release on commit
1838 } );
1839 }
1840
1841 return $dbw->selectField( 'image', '1',
1842 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1843 }
1844
1845 /**
1846 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1847 * the transaction and thereby releases the image lock.
1848 */
1849 function unlock() {
1850 if ( $this->locked ) {
1851 --$this->locked;
1852 if ( !$this->locked && $this->lockedOwnTrx ) {
1853 $dbw = $this->repo->getMasterDB();
1854 $dbw->commit( __METHOD__ );
1855 $this->lockedOwnTrx = false;
1856 }
1857 }
1858 }
1859
1860 /**
1861 * Roll back the DB transaction and mark the image unlocked
1862 */
1863 function unlockAndRollback() {
1864 $this->locked = false;
1865 $dbw = $this->repo->getMasterDB();
1866 $dbw->rollback( __METHOD__ );
1867 $this->lockedOwnTrx = false;
1868 }
1869
1870 /**
1871 * @return Status
1872 */
1873 protected function readOnlyFatalStatus() {
1874 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1875 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1876 }
1877 } // LocalFile class
1878
1879 # ------------------------------------------------------------------------------
1880
1881 /**
1882 * Helper class for file deletion
1883 * @ingroup FileAbstraction
1884 */
1885 class LocalFileDeleteBatch {
1886 /** @var LocalFile */
1887 private $file;
1888
1889 /** @var string */
1890 private $reason;
1891
1892 /** @var array */
1893 private $srcRels = array();
1894
1895 /** @var array */
1896 private $archiveUrls = array();
1897
1898 /** @var array Items to be processed in the deletion batch */
1899 private $deletionBatch;
1900
1901 /** @var bool Wether to suppress all suppressable fields when deleting */
1902 private $suppress;
1903
1904 /** @var FileRepoStatus */
1905 private $status;
1906
1907 /**
1908 * @param File $file
1909 * @param string $reason
1910 * @param bool $suppress
1911 */
1912 function __construct( File $file, $reason = '', $suppress = false ) {
1913 $this->file = $file;
1914 $this->reason = $reason;
1915 $this->suppress = $suppress;
1916 $this->status = $file->repo->newGood();
1917 }
1918
1919 function addCurrent() {
1920 $this->srcRels['.'] = $this->file->getRel();
1921 }
1922
1923 /**
1924 * @param string $oldName
1925 */
1926 function addOld( $oldName ) {
1927 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1928 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1929 }
1930
1931 /**
1932 * Add the old versions of the image to the batch
1933 * @return array List of archive names from old versions
1934 */
1935 function addOlds() {
1936 $archiveNames = array();
1937
1938 $dbw = $this->file->repo->getMasterDB();
1939 $result = $dbw->select( 'oldimage',
1940 array( 'oi_archive_name' ),
1941 array( 'oi_name' => $this->file->getName() ),
1942 __METHOD__
1943 );
1944
1945 foreach ( $result as $row ) {
1946 $this->addOld( $row->oi_archive_name );
1947 $archiveNames[] = $row->oi_archive_name;
1948 }
1949
1950 return $archiveNames;
1951 }
1952
1953 /**
1954 * @return array
1955 */
1956 function getOldRels() {
1957 if ( !isset( $this->srcRels['.'] ) ) {
1958 $oldRels =& $this->srcRels;
1959 $deleteCurrent = false;
1960 } else {
1961 $oldRels = $this->srcRels;
1962 unset( $oldRels['.'] );
1963 $deleteCurrent = true;
1964 }
1965
1966 return array( $oldRels, $deleteCurrent );
1967 }
1968
1969 /**
1970 * @return array
1971 */
1972 protected function getHashes() {
1973 $hashes = array();
1974 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1975
1976 if ( $deleteCurrent ) {
1977 $hashes['.'] = $this->file->getSha1();
1978 }
1979
1980 if ( count( $oldRels ) ) {
1981 $dbw = $this->file->repo->getMasterDB();
1982 $res = $dbw->select(
1983 'oldimage',
1984 array( 'oi_archive_name', 'oi_sha1' ),
1985 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1986 __METHOD__
1987 );
1988
1989 foreach ( $res as $row ) {
1990 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1991 // Get the hash from the file
1992 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1993 $props = $this->file->repo->getFileProps( $oldUrl );
1994
1995 if ( $props['fileExists'] ) {
1996 // Upgrade the oldimage row
1997 $dbw->update( 'oldimage',
1998 array( 'oi_sha1' => $props['sha1'] ),
1999 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
2000 __METHOD__ );
2001 $hashes[$row->oi_archive_name] = $props['sha1'];
2002 } else {
2003 $hashes[$row->oi_archive_name] = false;
2004 }
2005 } else {
2006 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2007 }
2008 }
2009 }
2010
2011 $missing = array_diff_key( $this->srcRels, $hashes );
2012
2013 foreach ( $missing as $name => $rel ) {
2014 $this->status->error( 'filedelete-old-unregistered', $name );
2015 }
2016
2017 foreach ( $hashes as $name => $hash ) {
2018 if ( !$hash ) {
2019 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2020 unset( $hashes[$name] );
2021 }
2022 }
2023
2024 return $hashes;
2025 }
2026
2027 function doDBInserts() {
2028 global $wgUser;
2029
2030 $dbw = $this->file->repo->getMasterDB();
2031 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2032 $encUserId = $dbw->addQuotes( $wgUser->getId() );
2033 $encReason = $dbw->addQuotes( $this->reason );
2034 $encGroup = $dbw->addQuotes( 'deleted' );
2035 $ext = $this->file->getExtension();
2036 $dotExt = $ext === '' ? '' : ".$ext";
2037 $encExt = $dbw->addQuotes( $dotExt );
2038 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2039
2040 // Bitfields to further suppress the content
2041 if ( $this->suppress ) {
2042 $bitfield = 0;
2043 // This should be 15...
2044 $bitfield |= Revision::DELETED_TEXT;
2045 $bitfield |= Revision::DELETED_COMMENT;
2046 $bitfield |= Revision::DELETED_USER;
2047 $bitfield |= Revision::DELETED_RESTRICTED;
2048 } else {
2049 $bitfield = 'oi_deleted';
2050 }
2051
2052 if ( $deleteCurrent ) {
2053 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2054 $where = array( 'img_name' => $this->file->getName() );
2055 $dbw->insertSelect( 'filearchive', 'image',
2056 array(
2057 'fa_storage_group' => $encGroup,
2058 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2059 'fa_deleted_user' => $encUserId,
2060 'fa_deleted_timestamp' => $encTimestamp,
2061 'fa_deleted_reason' => $encReason,
2062 'fa_deleted' => $this->suppress ? $bitfield : 0,
2063
2064 'fa_name' => 'img_name',
2065 'fa_archive_name' => 'NULL',
2066 'fa_size' => 'img_size',
2067 'fa_width' => 'img_width',
2068 'fa_height' => 'img_height',
2069 'fa_metadata' => 'img_metadata',
2070 'fa_bits' => 'img_bits',
2071 'fa_media_type' => 'img_media_type',
2072 'fa_major_mime' => 'img_major_mime',
2073 'fa_minor_mime' => 'img_minor_mime',
2074 'fa_description' => 'img_description',
2075 'fa_user' => 'img_user',
2076 'fa_user_text' => 'img_user_text',
2077 'fa_timestamp' => 'img_timestamp',
2078 'fa_sha1' => 'img_sha1',
2079 ), $where, __METHOD__ );
2080 }
2081
2082 if ( count( $oldRels ) ) {
2083 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2084 $where = array(
2085 'oi_name' => $this->file->getName(),
2086 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
2087 $dbw->insertSelect( 'filearchive', 'oldimage',
2088 array(
2089 'fa_storage_group' => $encGroup,
2090 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2091 'fa_deleted_user' => $encUserId,
2092 'fa_deleted_timestamp' => $encTimestamp,
2093 'fa_deleted_reason' => $encReason,
2094 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2095
2096 'fa_name' => 'oi_name',
2097 'fa_archive_name' => 'oi_archive_name',
2098 'fa_size' => 'oi_size',
2099 'fa_width' => 'oi_width',
2100 'fa_height' => 'oi_height',
2101 'fa_metadata' => 'oi_metadata',
2102 'fa_bits' => 'oi_bits',
2103 'fa_media_type' => 'oi_media_type',
2104 'fa_major_mime' => 'oi_major_mime',
2105 'fa_minor_mime' => 'oi_minor_mime',
2106 'fa_description' => 'oi_description',
2107 'fa_user' => 'oi_user',
2108 'fa_user_text' => 'oi_user_text',
2109 'fa_timestamp' => 'oi_timestamp',
2110 'fa_sha1' => 'oi_sha1',
2111 ), $where, __METHOD__ );
2112 }
2113 }
2114
2115 function doDBDeletes() {
2116 $dbw = $this->file->repo->getMasterDB();
2117 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2118
2119 if ( count( $oldRels ) ) {
2120 $dbw->delete( 'oldimage',
2121 array(
2122 'oi_name' => $this->file->getName(),
2123 'oi_archive_name' => array_keys( $oldRels )
2124 ), __METHOD__ );
2125 }
2126
2127 if ( $deleteCurrent ) {
2128 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
2129 }
2130 }
2131
2132 /**
2133 * Run the transaction
2134 * @return FileRepoStatus
2135 */
2136 function execute() {
2137 wfProfileIn( __METHOD__ );
2138
2139 $this->file->lock();
2140 // Leave private files alone
2141 $privateFiles = array();
2142 list( $oldRels, ) = $this->getOldRels();
2143 $dbw = $this->file->repo->getMasterDB();
2144
2145 if ( !empty( $oldRels ) ) {
2146 $res = $dbw->select( 'oldimage',
2147 array( 'oi_archive_name' ),
2148 array( 'oi_name' => $this->file->getName(),
2149 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2150 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
2151 __METHOD__ );
2152
2153 foreach ( $res as $row ) {
2154 $privateFiles[$row->oi_archive_name] = 1;
2155 }
2156 }
2157 // Prepare deletion batch
2158 $hashes = $this->getHashes();
2159 $this->deletionBatch = array();
2160 $ext = $this->file->getExtension();
2161 $dotExt = $ext === '' ? '' : ".$ext";
2162
2163 foreach ( $this->srcRels as $name => $srcRel ) {
2164 // Skip files that have no hash (missing source).
2165 // Keep private files where they are.
2166 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2167 $hash = $hashes[$name];
2168 $key = $hash . $dotExt;
2169 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2170 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2171 }
2172 }
2173
2174 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2175 // We acquire this lock by running the inserts now, before the file operations.
2176 //
2177 // This potentially has poor lock contention characteristics -- an alternative
2178 // scheme would be to insert stub filearchive entries with no fa_name and commit
2179 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2180 $this->doDBInserts();
2181
2182 // Removes non-existent file from the batch, so we don't get errors.
2183 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
2184
2185 // Execute the file deletion batch
2186 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2187
2188 if ( !$status->isGood() ) {
2189 $this->status->merge( $status );
2190 }
2191
2192 if ( !$this->status->isOK() ) {
2193 // Critical file deletion error
2194 // Roll back inserts, release lock and abort
2195 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2196 $this->file->unlockAndRollback();
2197 wfProfileOut( __METHOD__ );
2198
2199 return $this->status;
2200 }
2201
2202 // Delete image/oldimage rows
2203 $this->doDBDeletes();
2204
2205 // Commit and return
2206 $this->file->unlock();
2207 wfProfileOut( __METHOD__ );
2208
2209 return $this->status;
2210 }
2211
2212 /**
2213 * Removes non-existent files from a deletion batch.
2214 * @param $batch array
2215 * @return array
2216 */
2217 function removeNonexistentFiles( $batch ) {
2218 $files = $newBatch = array();
2219
2220 foreach ( $batch as $batchItem ) {
2221 list( $src, ) = $batchItem;
2222 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2223 }
2224
2225 $result = $this->file->repo->fileExistsBatch( $files );
2226
2227 foreach ( $batch as $batchItem ) {
2228 if ( $result[$batchItem[0]] ) {
2229 $newBatch[] = $batchItem;
2230 }
2231 }
2232
2233 return $newBatch;
2234 }
2235 }
2236
2237 # ------------------------------------------------------------------------------
2238
2239 /**
2240 * Helper class for file undeletion
2241 * @ingroup FileAbstraction
2242 */
2243 class LocalFileRestoreBatch {
2244 /** @var LocalFile */
2245 private $file;
2246
2247 /** @var array List of file IDs to restore */
2248 private $cleanupBatch;
2249
2250 /** @var array List of file IDs to restore */
2251 private $ids;
2252
2253 /** @var bool Add all revisions of the file */
2254 private $all;
2255
2256 /** @var bool Wether to remove all settings for suppressed fields */
2257 private $unsuppress = false;
2258
2259 /**
2260 * @param File $file
2261 * @param bool $unsuppress
2262 */
2263 function __construct( File $file, $unsuppress = false ) {
2264 $this->file = $file;
2265 $this->cleanupBatch = $this->ids = array();
2266 $this->ids = array();
2267 $this->unsuppress = $unsuppress;
2268 }
2269
2270 /**
2271 * Add a file by ID
2272 */
2273 function addId( $fa_id ) {
2274 $this->ids[] = $fa_id;
2275 }
2276
2277 /**
2278 * Add a whole lot of files by ID
2279 */
2280 function addIds( $ids ) {
2281 $this->ids = array_merge( $this->ids, $ids );
2282 }
2283
2284 /**
2285 * Add all revisions of the file
2286 */
2287 function addAll() {
2288 $this->all = true;
2289 }
2290
2291 /**
2292 * Run the transaction, except the cleanup batch.
2293 * The cleanup batch should be run in a separate transaction, because it locks different
2294 * rows and there's no need to keep the image row locked while it's acquiring those locks
2295 * The caller may have its own transaction open.
2296 * So we save the batch and let the caller call cleanup()
2297 * @return FileRepoStatus
2298 */
2299 function execute() {
2300 global $wgLang;
2301
2302 if ( !$this->all && !$this->ids ) {
2303 // Do nothing
2304 return $this->file->repo->newGood();
2305 }
2306
2307 $exists = $this->file->lock();
2308 $dbw = $this->file->repo->getMasterDB();
2309 $status = $this->file->repo->newGood();
2310
2311 // Fetch all or selected archived revisions for the file,
2312 // sorted from the most recent to the oldest.
2313 $conditions = array( 'fa_name' => $this->file->getName() );
2314
2315 if ( !$this->all ) {
2316 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
2317 }
2318
2319 $result = $dbw->select(
2320 'filearchive',
2321 ArchivedFile::selectFields(),
2322 $conditions,
2323 __METHOD__,
2324 array( 'ORDER BY' => 'fa_timestamp DESC' )
2325 );
2326
2327 $idsPresent = array();
2328 $storeBatch = array();
2329 $insertBatch = array();
2330 $insertCurrent = false;
2331 $deleteIds = array();
2332 $first = true;
2333 $archiveNames = array();
2334
2335 foreach ( $result as $row ) {
2336 $idsPresent[] = $row->fa_id;
2337
2338 if ( $row->fa_name != $this->file->getName() ) {
2339 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2340 $status->failCount++;
2341 continue;
2342 }
2343
2344 if ( $row->fa_storage_key == '' ) {
2345 // Revision was missing pre-deletion
2346 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2347 $status->failCount++;
2348 continue;
2349 }
2350
2351 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2352 $row->fa_storage_key;
2353 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2354
2355 if ( isset( $row->fa_sha1 ) ) {
2356 $sha1 = $row->fa_sha1;
2357 } else {
2358 // old row, populate from key
2359 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2360 }
2361
2362 # Fix leading zero
2363 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2364 $sha1 = substr( $sha1, 1 );
2365 }
2366
2367 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2368 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2369 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2370 || is_null( $row->fa_metadata )
2371 ) {
2372 // Refresh our metadata
2373 // Required for a new current revision; nice for older ones too. :)
2374 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2375 } else {
2376 $props = array(
2377 'minor_mime' => $row->fa_minor_mime,
2378 'major_mime' => $row->fa_major_mime,
2379 'media_type' => $row->fa_media_type,
2380 'metadata' => $row->fa_metadata
2381 );
2382 }
2383
2384 if ( $first && !$exists ) {
2385 // This revision will be published as the new current version
2386 $destRel = $this->file->getRel();
2387 $insertCurrent = array(
2388 'img_name' => $row->fa_name,
2389 'img_size' => $row->fa_size,
2390 'img_width' => $row->fa_width,
2391 'img_height' => $row->fa_height,
2392 'img_metadata' => $props['metadata'],
2393 'img_bits' => $row->fa_bits,
2394 'img_media_type' => $props['media_type'],
2395 'img_major_mime' => $props['major_mime'],
2396 'img_minor_mime' => $props['minor_mime'],
2397 'img_description' => $row->fa_description,
2398 'img_user' => $row->fa_user,
2399 'img_user_text' => $row->fa_user_text,
2400 'img_timestamp' => $row->fa_timestamp,
2401 'img_sha1' => $sha1
2402 );
2403
2404 // The live (current) version cannot be hidden!
2405 if ( !$this->unsuppress && $row->fa_deleted ) {
2406 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2407 $this->cleanupBatch[] = $row->fa_storage_key;
2408 }
2409 } else {
2410 $archiveName = $row->fa_archive_name;
2411
2412 if ( $archiveName == '' ) {
2413 // This was originally a current version; we
2414 // have to devise a new archive name for it.
2415 // Format is <timestamp of archiving>!<name>
2416 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2417
2418 do {
2419 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2420 $timestamp++;
2421 } while ( isset( $archiveNames[$archiveName] ) );
2422 }
2423
2424 $archiveNames[$archiveName] = true;
2425 $destRel = $this->file->getArchiveRel( $archiveName );
2426 $insertBatch[] = array(
2427 'oi_name' => $row->fa_name,
2428 'oi_archive_name' => $archiveName,
2429 'oi_size' => $row->fa_size,
2430 'oi_width' => $row->fa_width,
2431 'oi_height' => $row->fa_height,
2432 'oi_bits' => $row->fa_bits,
2433 'oi_description' => $row->fa_description,
2434 'oi_user' => $row->fa_user,
2435 'oi_user_text' => $row->fa_user_text,
2436 'oi_timestamp' => $row->fa_timestamp,
2437 'oi_metadata' => $props['metadata'],
2438 'oi_media_type' => $props['media_type'],
2439 'oi_major_mime' => $props['major_mime'],
2440 'oi_minor_mime' => $props['minor_mime'],
2441 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2442 'oi_sha1' => $sha1 );
2443 }
2444
2445 $deleteIds[] = $row->fa_id;
2446
2447 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2448 // private files can stay where they are
2449 $status->successCount++;
2450 } else {
2451 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2452 $this->cleanupBatch[] = $row->fa_storage_key;
2453 }
2454
2455 $first = false;
2456 }
2457
2458 unset( $result );
2459
2460 // Add a warning to the status object for missing IDs
2461 $missingIds = array_diff( $this->ids, $idsPresent );
2462
2463 foreach ( $missingIds as $id ) {
2464 $status->error( 'undelete-missing-filearchive', $id );
2465 }
2466
2467 // Remove missing files from batch, so we don't get errors when undeleting them
2468 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2469
2470 // Run the store batch
2471 // Use the OVERWRITE_SAME flag to smooth over a common error
2472 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2473 $status->merge( $storeStatus );
2474
2475 if ( !$status->isGood() ) {
2476 // Even if some files could be copied, fail entirely as that is the
2477 // easiest thing to do without data loss
2478 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2479 $status->ok = false;
2480 $this->file->unlock();
2481
2482 return $status;
2483 }
2484
2485 // Run the DB updates
2486 // Because we have locked the image row, key conflicts should be rare.
2487 // If they do occur, we can roll back the transaction at this time with
2488 // no data loss, but leaving unregistered files scattered throughout the
2489 // public zone.
2490 // This is not ideal, which is why it's important to lock the image row.
2491 if ( $insertCurrent ) {
2492 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2493 }
2494
2495 if ( $insertBatch ) {
2496 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2497 }
2498
2499 if ( $deleteIds ) {
2500 $dbw->delete( 'filearchive',
2501 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2502 __METHOD__ );
2503 }
2504
2505 // If store batch is empty (all files are missing), deletion is to be considered successful
2506 if ( $status->successCount > 0 || !$storeBatch ) {
2507 if ( !$exists ) {
2508 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2509
2510 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2511
2512 $this->file->purgeEverything();
2513 } else {
2514 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2515 $this->file->purgeDescription();
2516 $this->file->purgeHistory();
2517 }
2518 }
2519
2520 $this->file->unlock();
2521
2522 return $status;
2523 }
2524
2525 /**
2526 * Removes non-existent files from a store batch.
2527 * @param array $triplets
2528 * @return array
2529 */
2530 function removeNonexistentFiles( $triplets ) {
2531 $files = $filteredTriplets = array();
2532 foreach ( $triplets as $file ) {
2533 $files[$file[0]] = $file[0];
2534 }
2535
2536 $result = $this->file->repo->fileExistsBatch( $files );
2537
2538 foreach ( $triplets as $file ) {
2539 if ( $result[$file[0]] ) {
2540 $filteredTriplets[] = $file;
2541 }
2542 }
2543
2544 return $filteredTriplets;
2545 }
2546
2547 /**
2548 * Removes non-existent files from a cleanup batch.
2549 * @param array $batch
2550 * @return array
2551 */
2552 function removeNonexistentFromCleanup( $batch ) {
2553 $files = $newBatch = array();
2554 $repo = $this->file->repo;
2555
2556 foreach ( $batch as $file ) {
2557 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2558 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2559 }
2560
2561 $result = $repo->fileExistsBatch( $files );
2562
2563 foreach ( $batch as $file ) {
2564 if ( $result[$file] ) {
2565 $newBatch[] = $file;
2566 }
2567 }
2568
2569 return $newBatch;
2570 }
2571
2572 /**
2573 * Delete unused files in the deleted zone.
2574 * This should be called from outside the transaction in which execute() was called.
2575 * @return FileRepoStatus
2576 */
2577 function cleanup() {
2578 if ( !$this->cleanupBatch ) {
2579 return $this->file->repo->newGood();
2580 }
2581
2582 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2583
2584 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2585
2586 return $status;
2587 }
2588
2589 /**
2590 * Cleanup a failed batch. The batch was only partially successful, so
2591 * rollback by removing all items that were succesfully copied.
2592 *
2593 * @param Status $storeStatus
2594 * @param array $storeBatch
2595 */
2596 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2597 $cleanupBatch = array();
2598
2599 foreach ( $storeStatus->success as $i => $success ) {
2600 // Check if this item of the batch was successfully copied
2601 if ( $success ) {
2602 // Item was successfully copied and needs to be removed again
2603 // Extract ($dstZone, $dstRel) from the batch
2604 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2605 }
2606 }
2607 $this->file->repo->cleanupBatch( $cleanupBatch );
2608 }
2609 }
2610
2611 # ------------------------------------------------------------------------------
2612
2613 /**
2614 * Helper class for file movement
2615 * @ingroup FileAbstraction
2616 */
2617 class LocalFileMoveBatch {
2618 /** @var LocalFile */
2619 protected $file;
2620
2621 /** @var Title */
2622 protected $target;
2623
2624 protected $cur;
2625
2626 protected $olds;
2627
2628 protected $oldCount;
2629
2630 protected $archive;
2631
2632 /** @var DatabaseBase */
2633 protected $db;
2634
2635 /**
2636 * @param File $file
2637 * @param Title $target
2638 */
2639 function __construct( File $file, Title $target ) {
2640 $this->file = $file;
2641 $this->target = $target;
2642 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2643 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2644 $this->oldName = $this->file->getName();
2645 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2646 $this->oldRel = $this->oldHash . $this->oldName;
2647 $this->newRel = $this->newHash . $this->newName;
2648 $this->db = $file->getRepo()->getMasterDb();
2649 }
2650
2651 /**
2652 * Add the current image to the batch
2653 */
2654 function addCurrent() {
2655 $this->cur = array( $this->oldRel, $this->newRel );
2656 }
2657
2658 /**
2659 * Add the old versions of the image to the batch
2660 * @return array List of archive names from old versions
2661 */
2662 function addOlds() {
2663 $archiveBase = 'archive';
2664 $this->olds = array();
2665 $this->oldCount = 0;
2666 $archiveNames = array();
2667
2668 $result = $this->db->select( 'oldimage',
2669 array( 'oi_archive_name', 'oi_deleted' ),
2670 array( 'oi_name' => $this->oldName ),
2671 __METHOD__
2672 );
2673
2674 foreach ( $result as $row ) {
2675 $archiveNames[] = $row->oi_archive_name;
2676 $oldName = $row->oi_archive_name;
2677 $bits = explode( '!', $oldName, 2 );
2678
2679 if ( count( $bits ) != 2 ) {
2680 wfDebug( "Old file name missing !: '$oldName' \n" );
2681 continue;
2682 }
2683
2684 list( $timestamp, $filename ) = $bits;
2685
2686 if ( $this->oldName != $filename ) {
2687 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2688 continue;
2689 }
2690
2691 $this->oldCount++;
2692
2693 // Do we want to add those to oldCount?
2694 if ( $row->oi_deleted & File::DELETED_FILE ) {
2695 continue;
2696 }
2697
2698 $this->olds[] = array(
2699 "{$archiveBase}/{$this->oldHash}{$oldName}",
2700 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2701 );
2702 }
2703
2704 return $archiveNames;
2705 }
2706
2707 /**
2708 * Perform the move.
2709 * @return FileRepoStatus
2710 */
2711 function execute() {
2712 $repo = $this->file->repo;
2713 $status = $repo->newGood();
2714
2715 $triplets = $this->getMoveTriplets();
2716 $triplets = $this->removeNonexistentFiles( $triplets );
2717
2718 $this->file->lock(); // begin
2719 // Rename the file versions metadata in the DB.
2720 // This implicitly locks the destination file, which avoids race conditions.
2721 // If we moved the files from A -> C before DB updates, another process could
2722 // move files from B -> C at this point, causing storeBatch() to fail and thus
2723 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2724 $statusDb = $this->doDBUpdates();
2725 if ( !$statusDb->isGood() ) {
2726 $this->file->unlockAndRollback();
2727 $statusDb->ok = false;
2728
2729 return $statusDb;
2730 }
2731 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2732 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2733
2734 // Copy the files into their new location.
2735 // If a prior process fataled copying or cleaning up files we tolerate any
2736 // of the existing files if they are identical to the ones being stored.
2737 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2738 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2739 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2740 if ( !$statusMove->isGood() ) {
2741 // Delete any files copied over (while the destination is still locked)
2742 $this->cleanupTarget( $triplets );
2743 $this->file->unlockAndRollback(); // unlocks the destination
2744 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2745 $statusMove->ok = false;
2746
2747 return $statusMove;
2748 }
2749 $this->file->unlock(); // done
2750
2751 // Everything went ok, remove the source files
2752 $this->cleanupSource( $triplets );
2753
2754 $status->merge( $statusDb );
2755 $status->merge( $statusMove );
2756
2757 return $status;
2758 }
2759
2760 /**
2761 * Do the database updates and return a new FileRepoStatus indicating how
2762 * many rows where updated.
2763 *
2764 * @return FileRepoStatus
2765 */
2766 function doDBUpdates() {
2767 $repo = $this->file->repo;
2768 $status = $repo->newGood();
2769 $dbw = $this->db;
2770
2771 // Update current image
2772 $dbw->update(
2773 'image',
2774 array( 'img_name' => $this->newName ),
2775 array( 'img_name' => $this->oldName ),
2776 __METHOD__
2777 );
2778
2779 if ( $dbw->affectedRows() ) {
2780 $status->successCount++;
2781 } else {
2782 $status->failCount++;
2783 $status->fatal( 'imageinvalidfilename' );
2784
2785 return $status;
2786 }
2787
2788 // Update old images
2789 $dbw->update(
2790 'oldimage',
2791 array(
2792 'oi_name' => $this->newName,
2793 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2794 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2795 ),
2796 array( 'oi_name' => $this->oldName ),
2797 __METHOD__
2798 );
2799
2800 $affected = $dbw->affectedRows();
2801 $total = $this->oldCount;
2802 $status->successCount += $affected;
2803 // Bug 34934: $total is based on files that actually exist.
2804 // There may be more DB rows than such files, in which case $affected
2805 // can be greater than $total. We use max() to avoid negatives here.
2806 $status->failCount += max( 0, $total - $affected );
2807 if ( $status->failCount ) {
2808 $status->error( 'imageinvalidfilename' );
2809 }
2810
2811 return $status;
2812 }
2813
2814 /**
2815 * Generate triplets for FileRepo::storeBatch().
2816 * @return array
2817 */
2818 function getMoveTriplets() {
2819 $moves = array_merge( array( $this->cur ), $this->olds );
2820 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2821
2822 foreach ( $moves as $move ) {
2823 // $move: (oldRelativePath, newRelativePath)
2824 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2825 $triplets[] = array( $srcUrl, 'public', $move[1] );
2826 wfDebugLog(
2827 'imagemove',
2828 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2829 );
2830 }
2831
2832 return $triplets;
2833 }
2834
2835 /**
2836 * Removes non-existent files from move batch.
2837 * @param array $triplets
2838 * @return array
2839 */
2840 function removeNonexistentFiles( $triplets ) {
2841 $files = array();
2842
2843 foreach ( $triplets as $file ) {
2844 $files[$file[0]] = $file[0];
2845 }
2846
2847 $result = $this->file->repo->fileExistsBatch( $files );
2848 $filteredTriplets = array();
2849
2850 foreach ( $triplets as $file ) {
2851 if ( $result[$file[0]] ) {
2852 $filteredTriplets[] = $file;
2853 } else {
2854 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2855 }
2856 }
2857
2858 return $filteredTriplets;
2859 }
2860
2861 /**
2862 * Cleanup a partially moved array of triplets by deleting the target
2863 * files. Called if something went wrong half way.
2864 */
2865 function cleanupTarget( $triplets ) {
2866 // Create dest pairs from the triplets
2867 $pairs = array();
2868 foreach ( $triplets as $triplet ) {
2869 // $triplet: (old source virtual URL, dst zone, dest rel)
2870 $pairs[] = array( $triplet[1], $triplet[2] );
2871 }
2872
2873 $this->file->repo->cleanupBatch( $pairs );
2874 }
2875
2876 /**
2877 * Cleanup a fully moved array of triplets by deleting the source files.
2878 * Called at the end of the move process if everything else went ok.
2879 */
2880 function cleanupSource( $triplets ) {
2881 // Create source file names from the triplets
2882 $files = array();
2883 foreach ( $triplets as $triplet ) {
2884 $files[] = $triplet[0];
2885 }
2886
2887 $this->file->repo->cleanupBatch( $files );
2888 }
2889 }