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