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