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