Merge "Remove check for PHP version in install.php"
[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|bool
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 $dbw->rollback( __METHOD__ );
1272 wfProfileOut( __METHOD__ );
1273
1274 return false;
1275 }
1276
1277 $reupload = false;
1278
1279 # Test to see if the row exists using INSERT IGNORE
1280 # This avoids race conditions by locking the row until the commit, and also
1281 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1282 $dbw->insert( 'image',
1283 array(
1284 'img_name' => $this->getName(),
1285 'img_size' => $this->size,
1286 'img_width' => intval( $this->width ),
1287 'img_height' => intval( $this->height ),
1288 'img_bits' => $this->bits,
1289 'img_media_type' => $this->media_type,
1290 'img_major_mime' => $this->major_mime,
1291 'img_minor_mime' => $this->minor_mime,
1292 'img_timestamp' => $timestamp,
1293 'img_description' => $comment,
1294 'img_user' => $user->getId(),
1295 'img_user_text' => $user->getName(),
1296 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1297 'img_sha1' => $this->sha1
1298 ),
1299 __METHOD__,
1300 'IGNORE'
1301 );
1302 if ( $dbw->affectedRows() == 0 ) {
1303 if ( $allowTimeKludge ) {
1304 # Use FOR UPDATE to ignore any transaction snapshotting
1305 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1306 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1307 $lUnixtime = $ltimestamp ? wfTimestamp( TS_UNIX, $ltimestamp ) : false;
1308 # Avoid a timestamp that is not newer than the last version
1309 # TODO: the image/oldimage tables should be like page/revision with an ID field
1310 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1311 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1312 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1313 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1314 }
1315 }
1316
1317 # (bug 34993) Note: $oldver can be empty here, if the previous
1318 # version of the file was broken. Allow registration of the new
1319 # version to continue anyway, because that's better than having
1320 # an image that's not fixable by user operations.
1321
1322 $reupload = true;
1323 # Collision, this is an update of a file
1324 # Insert previous contents into oldimage
1325 $dbw->insertSelect( 'oldimage', 'image',
1326 array(
1327 'oi_name' => 'img_name',
1328 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1329 'oi_size' => 'img_size',
1330 'oi_width' => 'img_width',
1331 'oi_height' => 'img_height',
1332 'oi_bits' => 'img_bits',
1333 'oi_timestamp' => 'img_timestamp',
1334 'oi_description' => 'img_description',
1335 'oi_user' => 'img_user',
1336 'oi_user_text' => 'img_user_text',
1337 'oi_metadata' => 'img_metadata',
1338 'oi_media_type' => 'img_media_type',
1339 'oi_major_mime' => 'img_major_mime',
1340 'oi_minor_mime' => 'img_minor_mime',
1341 'oi_sha1' => 'img_sha1'
1342 ),
1343 array( 'img_name' => $this->getName() ),
1344 __METHOD__
1345 );
1346
1347 # Update the current image row
1348 $dbw->update( 'image',
1349 array( /* SET */
1350 'img_size' => $this->size,
1351 'img_width' => intval( $this->width ),
1352 'img_height' => intval( $this->height ),
1353 'img_bits' => $this->bits,
1354 'img_media_type' => $this->media_type,
1355 'img_major_mime' => $this->major_mime,
1356 'img_minor_mime' => $this->minor_mime,
1357 'img_timestamp' => $timestamp,
1358 'img_description' => $comment,
1359 'img_user' => $user->getId(),
1360 'img_user_text' => $user->getName(),
1361 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1362 'img_sha1' => $this->sha1
1363 ),
1364 array( 'img_name' => $this->getName() ),
1365 __METHOD__
1366 );
1367 } else {
1368 # This is a new file, so update the image count
1369 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
1370 }
1371
1372 $descTitle = $this->getTitle();
1373 $wikiPage = new WikiFilePage( $descTitle );
1374 $wikiPage->setFile( $this );
1375
1376 # Add the log entry
1377 $action = $reupload ? 'overwrite' : 'upload';
1378
1379 $logEntry = new ManualLogEntry( 'upload', $action );
1380 $logEntry->setPerformer( $user );
1381 $logEntry->setComment( $comment );
1382 $logEntry->setTarget( $descTitle );
1383
1384 // Allow people using the api to associate log entries with the upload.
1385 // Log has a timestamp, but sometimes different from upload timestamp.
1386 $logEntry->setParameters(
1387 array(
1388 'img_sha1' => $this->sha1,
1389 'img_timestamp' => $timestamp,
1390 )
1391 );
1392 // Note we keep $logId around since during new image
1393 // creation, page doesn't exist yet, so log_page = 0
1394 // but we want it to point to the page we're making,
1395 // so we later modify the log entry.
1396 // For a similar reason, we avoid making an RC entry
1397 // now and wait until the page exists.
1398 $logId = $logEntry->insert();
1399
1400 $exists = $descTitle->exists();
1401 if ( $exists ) {
1402 // Page exists, do RC entry now (otherwise we wait for later).
1403 $logEntry->publish( $logId );
1404 }
1405 wfProfileIn( __METHOD__ . '-edit' );
1406
1407 if ( $exists ) {
1408 # Create a null revision
1409 $latest = $descTitle->getLatestRevID();
1410 $editSummary = LogFormatter::newFromEntry( $logEntry )->getPlainActionText();
1411
1412 $nullRevision = Revision::newNullRevision(
1413 $dbw,
1414 $descTitle->getArticleID(),
1415 $editSummary,
1416 false,
1417 $user
1418 );
1419 if ( !is_null( $nullRevision ) ) {
1420 $nullRevision->insertOn( $dbw );
1421
1422 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1423 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1424 }
1425 }
1426
1427 # Commit the transaction now, in case something goes wrong later
1428 # The most important thing is that files don't get lost, especially archives
1429 # NOTE: once we have support for nested transactions, the commit may be moved
1430 # to after $wikiPage->doEdit has been called.
1431 $dbw->commit( __METHOD__ );
1432
1433 # Save to memcache.
1434 # We shall not saveToCache before the commit since otherwise
1435 # in case of a rollback there is an usable file from memcached
1436 # which in fact doesn't really exist (bug 24978)
1437 $this->saveToCache();
1438
1439 if ( $exists ) {
1440 # Invalidate the cache for the description page
1441 $descTitle->invalidateCache();
1442 $descTitle->purgeSquid();
1443 } else {
1444 # New file; create the description page.
1445 # There's already a log entry, so don't make a second RC entry
1446 # Squid and file cache for the description page are purged by doEditContent.
1447 $content = ContentHandler::makeContent( $pageText, $descTitle );
1448 $status = $wikiPage->doEditContent(
1449 $content,
1450 $comment,
1451 EDIT_NEW | EDIT_SUPPRESS_RC,
1452 false,
1453 $user
1454 );
1455
1456 $dbw->begin( __METHOD__ ); // XXX; doEdit() uses a transaction
1457 // Now that the page exists, make an RC entry.
1458 $logEntry->publish( $logId );
1459 if ( isset( $status->value['revision'] ) ) {
1460 $dbw->update( 'logging',
1461 array( 'log_page' => $status->value['revision']->getPage() ),
1462 array( 'log_id' => $logId ),
1463 __METHOD__
1464 );
1465 }
1466 $dbw->commit( __METHOD__ ); // commit before anything bad can happen
1467 }
1468
1469 wfProfileOut( __METHOD__ . '-edit' );
1470
1471 if ( $reupload ) {
1472 # Delete old thumbnails
1473 wfProfileIn( __METHOD__ . '-purge' );
1474 $this->purgeThumbnails();
1475 wfProfileOut( __METHOD__ . '-purge' );
1476
1477 # Remove the old file from the squid cache
1478 SquidUpdate::purge( array( $this->getURL() ) );
1479 }
1480
1481 # Hooks, hooks, the magic of hooks...
1482 wfProfileIn( __METHOD__ . '-hooks' );
1483 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1484 wfProfileOut( __METHOD__ . '-hooks' );
1485
1486 # Invalidate cache for all pages using this file
1487 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1488 $update->doUpdate();
1489 if ( !$reupload ) {
1490 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1491 }
1492
1493 wfProfileOut( __METHOD__ );
1494
1495 return true;
1496 }
1497
1498 /**
1499 * Move or copy a file to its public location. If a file exists at the
1500 * destination, move it to an archive. Returns a FileRepoStatus object with
1501 * the archive name in the "value" member on success.
1502 *
1503 * The archive name should be passed through to recordUpload for database
1504 * registration.
1505 *
1506 * @param string $srcPath Local filesystem path to the source image
1507 * @param int $flags A bitwise combination of:
1508 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1509 * @param array $options Optional additional parameters
1510 * @return FileRepoStatus On success, the value member contains the
1511 * archive name, or an empty string if it was a new file.
1512 */
1513 function publish( $srcPath, $flags = 0, array $options = array() ) {
1514 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1515 }
1516
1517 /**
1518 * Move or copy a file to a specified location. Returns a FileRepoStatus
1519 * object with the archive name in the "value" member on success.
1520 *
1521 * The archive name should be passed through to recordUpload for database
1522 * registration.
1523 *
1524 * @param string $srcPath Local filesystem path to the source image
1525 * @param string $dstRel Target relative path
1526 * @param int $flags A bitwise combination of:
1527 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1528 * @param array $options Optional additional parameters
1529 * @return FileRepoStatus On success, the value member contains the
1530 * archive name, or an empty string if it was a new file.
1531 */
1532 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1533 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1534 return $this->readOnlyFatalStatus();
1535 }
1536
1537 $this->lock(); // begin
1538
1539 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1540 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1541 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1542 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1543
1544 if ( $status->value == 'new' ) {
1545 $status->value = '';
1546 } else {
1547 $status->value = $archiveName;
1548 }
1549
1550 $this->unlock(); // done
1551
1552 return $status;
1553 }
1554
1555 /** getLinksTo inherited */
1556 /** getExifData inherited */
1557 /** isLocal inherited */
1558 /** wasDeleted inherited */
1559
1560 /**
1561 * Move file to the new title
1562 *
1563 * Move current, old version and all thumbnails
1564 * to the new filename. Old file is deleted.
1565 *
1566 * Cache purging is done; checks for validity
1567 * and logging are caller's responsibility
1568 *
1569 * @param Title $target New file name
1570 * @return FileRepoStatus
1571 */
1572 function move( $target ) {
1573 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1574 return $this->readOnlyFatalStatus();
1575 }
1576
1577 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1578 $batch = new LocalFileMoveBatch( $this, $target );
1579
1580 $this->lock(); // begin
1581 $batch->addCurrent();
1582 $archiveNames = $batch->addOlds();
1583 $status = $batch->execute();
1584 $this->unlock(); // done
1585
1586 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1587
1588 // Purge the source and target files...
1589 $oldTitleFile = wfLocalFile( $this->title );
1590 $newTitleFile = wfLocalFile( $target );
1591 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1592 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1593 $this->getRepo()->getMasterDB()->onTransactionIdle(
1594 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1595 $oldTitleFile->purgeEverything();
1596 foreach ( $archiveNames as $archiveName ) {
1597 $oldTitleFile->purgeOldThumbnails( $archiveName );
1598 }
1599 $newTitleFile->purgeEverything();
1600 }
1601 );
1602
1603 if ( $status->isOK() ) {
1604 // Now switch the object
1605 $this->title = $target;
1606 // Force regeneration of the name and hashpath
1607 unset( $this->name );
1608 unset( $this->hashPath );
1609 }
1610
1611 return $status;
1612 }
1613
1614 /**
1615 * Delete all versions of the file.
1616 *
1617 * Moves the files into an archive directory (or deletes them)
1618 * and removes the database rows.
1619 *
1620 * Cache purging is done; logging is caller's responsibility.
1621 *
1622 * @param string $reason
1623 * @param bool $suppress
1624 * @param User|null $user
1625 * @return FileRepoStatus
1626 */
1627 function delete( $reason, $suppress = false, $user = null ) {
1628 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1629 return $this->readOnlyFatalStatus();
1630 }
1631
1632 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1633
1634 $this->lock(); // begin
1635 $batch->addCurrent();
1636 # Get old version relative paths
1637 $archiveNames = $batch->addOlds();
1638 $status = $batch->execute();
1639 $this->unlock(); // done
1640
1641 if ( $status->isOK() ) {
1642 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1643 }
1644
1645 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1646 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1647 $file = $this;
1648 $this->getRepo()->getMasterDB()->onTransactionIdle(
1649 function () use ( $file, $archiveNames ) {
1650 global $wgUseSquid;
1651
1652 $file->purgeEverything();
1653 foreach ( $archiveNames as $archiveName ) {
1654 $file->purgeOldThumbnails( $archiveName );
1655 }
1656
1657 if ( $wgUseSquid ) {
1658 // Purge the squid
1659 $purgeUrls = array();
1660 foreach ( $archiveNames as $archiveName ) {
1661 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1662 }
1663 SquidUpdate::purge( $purgeUrls );
1664 }
1665 }
1666 );
1667
1668 return $status;
1669 }
1670
1671 /**
1672 * Delete an old version of the file.
1673 *
1674 * Moves the file into an archive directory (or deletes it)
1675 * and removes the database row.
1676 *
1677 * Cache purging is done; logging is caller's responsibility.
1678 *
1679 * @param string $archiveName
1680 * @param string $reason
1681 * @param bool $suppress
1682 * @param User|null $user
1683 * @throws MWException Exception on database or file store failure
1684 * @return FileRepoStatus
1685 */
1686 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1687 global $wgUseSquid;
1688 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1689 return $this->readOnlyFatalStatus();
1690 }
1691
1692 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1693
1694 $this->lock(); // begin
1695 $batch->addOld( $archiveName );
1696 $status = $batch->execute();
1697 $this->unlock(); // done
1698
1699 $this->purgeOldThumbnails( $archiveName );
1700 if ( $status->isOK() ) {
1701 $this->purgeDescription();
1702 $this->purgeHistory();
1703 }
1704
1705 if ( $wgUseSquid ) {
1706 // Purge the squid
1707 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1708 }
1709
1710 return $status;
1711 }
1712
1713 /**
1714 * Restore all or specified deleted revisions to the given file.
1715 * Permissions and logging are left to the caller.
1716 *
1717 * May throw database exceptions on error.
1718 *
1719 * @param array $versions Set of record ids of deleted items to restore,
1720 * or empty to restore all revisions.
1721 * @param bool $unsuppress
1722 * @return FileRepoStatus
1723 */
1724 function restore( $versions = array(), $unsuppress = false ) {
1725 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1726 return $this->readOnlyFatalStatus();
1727 }
1728
1729 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1730
1731 $this->lock(); // begin
1732 if ( !$versions ) {
1733 $batch->addAll();
1734 } else {
1735 $batch->addIds( $versions );
1736 }
1737 $status = $batch->execute();
1738 if ( $status->isGood() ) {
1739 $cleanupStatus = $batch->cleanup();
1740 $cleanupStatus->successCount = 0;
1741 $cleanupStatus->failCount = 0;
1742 $status->merge( $cleanupStatus );
1743 }
1744 $this->unlock(); // done
1745
1746 return $status;
1747 }
1748
1749 /** isMultipage inherited */
1750 /** pageCount inherited */
1751 /** scaleHeight inherited */
1752 /** getImageSize inherited */
1753
1754 /**
1755 * Get the URL of the file description page.
1756 * @return string
1757 */
1758 function getDescriptionUrl() {
1759 return $this->title->getLocalURL();
1760 }
1761
1762 /**
1763 * Get the HTML text of the description page
1764 * This is not used by ImagePage for local files, since (among other things)
1765 * it skips the parser cache.
1766 *
1767 * @param Language $lang What language to get description in (Optional)
1768 * @return bool|mixed
1769 */
1770 function getDescriptionText( $lang = null ) {
1771 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1772 if ( !$revision ) {
1773 return false;
1774 }
1775 $content = $revision->getContent();
1776 if ( !$content ) {
1777 return false;
1778 }
1779 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1780
1781 return $pout->getText();
1782 }
1783
1784 /**
1785 * @param int $audience
1786 * @param User $user
1787 * @return string
1788 */
1789 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1790 $this->load();
1791 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1792 return '';
1793 } elseif ( $audience == self::FOR_THIS_USER
1794 && !$this->userCan( self::DELETED_COMMENT, $user )
1795 ) {
1796 return '';
1797 } else {
1798 return $this->description;
1799 }
1800 }
1801
1802 /**
1803 * @return bool|string
1804 */
1805 function getTimestamp() {
1806 $this->load();
1807
1808 return $this->timestamp;
1809 }
1810
1811 /**
1812 * @return string
1813 */
1814 function getSha1() {
1815 $this->load();
1816 // Initialise now if necessary
1817 if ( $this->sha1 == '' && $this->fileExists ) {
1818 $this->lock(); // begin
1819
1820 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1821 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1822 $dbw = $this->repo->getMasterDB();
1823 $dbw->update( 'image',
1824 array( 'img_sha1' => $this->sha1 ),
1825 array( 'img_name' => $this->getName() ),
1826 __METHOD__ );
1827 $this->saveToCache();
1828 }
1829
1830 $this->unlock(); // done
1831 }
1832
1833 return $this->sha1;
1834 }
1835
1836 /**
1837 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1838 */
1839 function isCacheable() {
1840 $this->load();
1841
1842 // If extra data (metadata) was not loaded then it must have been large
1843 return $this->extraDataLoaded
1844 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1845 }
1846
1847 /**
1848 * Start a transaction and lock the image for update
1849 * Increments a reference counter if the lock is already held
1850 * @throws MWException Throws an error if the lock was not acquired
1851 * @return bool Success
1852 */
1853 function lock() {
1854 $dbw = $this->repo->getMasterDB();
1855
1856 if ( !$this->locked ) {
1857 if ( !$dbw->trxLevel() ) {
1858 $dbw->begin( __METHOD__ );
1859 $this->lockedOwnTrx = true;
1860 }
1861 $this->locked++;
1862 // Bug 54736: use simple lock to handle when the file does not exist.
1863 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1864 // Also, that would cause contention on INSERT of similarly named rows.
1865 $backend = $this->getRepo()->getBackend();
1866 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1867 $status = $backend->lockFiles( $lockPaths, LockManager::LOCK_EX, 5 );
1868 if ( !$status->isGood() ) {
1869 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1870 }
1871 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1872 $backend->unlockFiles( $lockPaths, LockManager::LOCK_EX ); // release on commit
1873 } );
1874 }
1875
1876 $this->markVolatile(); // file may change soon
1877
1878 return true;
1879 }
1880
1881 /**
1882 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1883 * the transaction and thereby releases the image lock.
1884 */
1885 function unlock() {
1886 if ( $this->locked ) {
1887 --$this->locked;
1888 if ( !$this->locked && $this->lockedOwnTrx ) {
1889 $dbw = $this->repo->getMasterDB();
1890 $dbw->commit( __METHOD__ );
1891 $this->lockedOwnTrx = false;
1892 }
1893 }
1894 }
1895
1896 /**
1897 * Mark a file as about to be changed
1898 *
1899 * This sets a cache key that alters master/slave DB loading behavior
1900 *
1901 * @return bool Success
1902 */
1903 protected function markVolatile() {
1904 global $wgMemc;
1905
1906 $key = $this->repo->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1907 if ( $key ) {
1908 $this->lastMarkedVolatile = time();
1909 return $wgMemc->set( $key, $this->lastMarkedVolatile, self::VOLATILE_TTL );
1910 }
1911
1912 return true;
1913 }
1914
1915 /**
1916 * Check if a file is about to be changed or has been changed recently
1917 *
1918 * @see LocalFile::isVolatile()
1919 * @return bool Whether the file is volatile
1920 */
1921 protected function isVolatile() {
1922 global $wgMemc;
1923
1924 $key = $this->repo->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1925 if ( !$key ) {
1926 // repo unavailable; bail.
1927 return false;
1928 }
1929
1930 if ( $this->lastMarkedVolatile === 0 ) {
1931 $this->lastMarkedVolatile = $wgMemc->get( $key ) ?: 0;
1932 }
1933
1934 $volatileDuration = time() - $this->lastMarkedVolatile;
1935 return $volatileDuration <= self::VOLATILE_TTL;
1936 }
1937
1938 /**
1939 * Roll back the DB transaction and mark the image unlocked
1940 */
1941 function unlockAndRollback() {
1942 $this->locked = false;
1943 $dbw = $this->repo->getMasterDB();
1944 $dbw->rollback( __METHOD__ );
1945 $this->lockedOwnTrx = false;
1946 }
1947
1948 /**
1949 * @return Status
1950 */
1951 protected function readOnlyFatalStatus() {
1952 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1953 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1954 }
1955
1956 /**
1957 * Clean up any dangling locks
1958 */
1959 function __destruct() {
1960 $this->unlock();
1961 }
1962 } // LocalFile class
1963
1964 # ------------------------------------------------------------------------------
1965
1966 /**
1967 * Helper class for file deletion
1968 * @ingroup FileAbstraction
1969 */
1970 class LocalFileDeleteBatch {
1971 /** @var LocalFile */
1972 private $file;
1973
1974 /** @var string */
1975 private $reason;
1976
1977 /** @var array */
1978 private $srcRels = array();
1979
1980 /** @var array */
1981 private $archiveUrls = array();
1982
1983 /** @var array Items to be processed in the deletion batch */
1984 private $deletionBatch;
1985
1986 /** @var bool Wether to suppress all suppressable fields when deleting */
1987 private $suppress;
1988
1989 /** @var FileRepoStatus */
1990 private $status;
1991
1992 /** @var User */
1993 private $user;
1994
1995 /**
1996 * @param File $file
1997 * @param string $reason
1998 * @param bool $suppress
1999 * @param User|null $user
2000 */
2001 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2002 $this->file = $file;
2003 $this->reason = $reason;
2004 $this->suppress = $suppress;
2005 if ( $user ) {
2006 $this->user = $user;
2007 } else {
2008 global $wgUser;
2009 $this->user = $wgUser;
2010 }
2011 $this->status = $file->repo->newGood();
2012 }
2013
2014 function addCurrent() {
2015 $this->srcRels['.'] = $this->file->getRel();
2016 }
2017
2018 /**
2019 * @param string $oldName
2020 */
2021 function addOld( $oldName ) {
2022 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2023 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2024 }
2025
2026 /**
2027 * Add the old versions of the image to the batch
2028 * @return array List of archive names from old versions
2029 */
2030 function addOlds() {
2031 $archiveNames = array();
2032
2033 $dbw = $this->file->repo->getMasterDB();
2034 $result = $dbw->select( 'oldimage',
2035 array( 'oi_archive_name' ),
2036 array( 'oi_name' => $this->file->getName() ),
2037 __METHOD__
2038 );
2039
2040 foreach ( $result as $row ) {
2041 $this->addOld( $row->oi_archive_name );
2042 $archiveNames[] = $row->oi_archive_name;
2043 }
2044
2045 return $archiveNames;
2046 }
2047
2048 /**
2049 * @return array
2050 */
2051 function getOldRels() {
2052 if ( !isset( $this->srcRels['.'] ) ) {
2053 $oldRels =& $this->srcRels;
2054 $deleteCurrent = false;
2055 } else {
2056 $oldRels = $this->srcRels;
2057 unset( $oldRels['.'] );
2058 $deleteCurrent = true;
2059 }
2060
2061 return array( $oldRels, $deleteCurrent );
2062 }
2063
2064 /**
2065 * @return array
2066 */
2067 protected function getHashes() {
2068 $hashes = array();
2069 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2070
2071 if ( $deleteCurrent ) {
2072 $hashes['.'] = $this->file->getSha1();
2073 }
2074
2075 if ( count( $oldRels ) ) {
2076 $dbw = $this->file->repo->getMasterDB();
2077 $res = $dbw->select(
2078 'oldimage',
2079 array( 'oi_archive_name', 'oi_sha1' ),
2080 array( 'oi_archive_name' => array_keys( $oldRels ),
2081 'oi_name' => $this->file->getName() ), // performance
2082 __METHOD__
2083 );
2084
2085 foreach ( $res as $row ) {
2086 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2087 // Get the hash from the file
2088 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2089 $props = $this->file->repo->getFileProps( $oldUrl );
2090
2091 if ( $props['fileExists'] ) {
2092 // Upgrade the oldimage row
2093 $dbw->update( 'oldimage',
2094 array( 'oi_sha1' => $props['sha1'] ),
2095 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
2096 __METHOD__ );
2097 $hashes[$row->oi_archive_name] = $props['sha1'];
2098 } else {
2099 $hashes[$row->oi_archive_name] = false;
2100 }
2101 } else {
2102 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2103 }
2104 }
2105 }
2106
2107 $missing = array_diff_key( $this->srcRels, $hashes );
2108
2109 foreach ( $missing as $name => $rel ) {
2110 $this->status->error( 'filedelete-old-unregistered', $name );
2111 }
2112
2113 foreach ( $hashes as $name => $hash ) {
2114 if ( !$hash ) {
2115 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2116 unset( $hashes[$name] );
2117 }
2118 }
2119
2120 return $hashes;
2121 }
2122
2123 function doDBInserts() {
2124 $dbw = $this->file->repo->getMasterDB();
2125 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2126 $encUserId = $dbw->addQuotes( $this->user->getId() );
2127 $encReason = $dbw->addQuotes( $this->reason );
2128 $encGroup = $dbw->addQuotes( 'deleted' );
2129 $ext = $this->file->getExtension();
2130 $dotExt = $ext === '' ? '' : ".$ext";
2131 $encExt = $dbw->addQuotes( $dotExt );
2132 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2133
2134 // Bitfields to further suppress the content
2135 if ( $this->suppress ) {
2136 $bitfield = 0;
2137 // This should be 15...
2138 $bitfield |= Revision::DELETED_TEXT;
2139 $bitfield |= Revision::DELETED_COMMENT;
2140 $bitfield |= Revision::DELETED_USER;
2141 $bitfield |= Revision::DELETED_RESTRICTED;
2142 } else {
2143 $bitfield = 'oi_deleted';
2144 }
2145
2146 if ( $deleteCurrent ) {
2147 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2148 $where = array( 'img_name' => $this->file->getName() );
2149 $dbw->insertSelect( 'filearchive', 'image',
2150 array(
2151 'fa_storage_group' => $encGroup,
2152 'fa_storage_key' => $dbw->conditional(
2153 array( 'img_sha1' => '' ),
2154 $dbw->addQuotes( '' ),
2155 $concat
2156 ),
2157 'fa_deleted_user' => $encUserId,
2158 'fa_deleted_timestamp' => $encTimestamp,
2159 'fa_deleted_reason' => $encReason,
2160 'fa_deleted' => $this->suppress ? $bitfield : 0,
2161
2162 'fa_name' => 'img_name',
2163 'fa_archive_name' => 'NULL',
2164 'fa_size' => 'img_size',
2165 'fa_width' => 'img_width',
2166 'fa_height' => 'img_height',
2167 'fa_metadata' => 'img_metadata',
2168 'fa_bits' => 'img_bits',
2169 'fa_media_type' => 'img_media_type',
2170 'fa_major_mime' => 'img_major_mime',
2171 'fa_minor_mime' => 'img_minor_mime',
2172 'fa_description' => 'img_description',
2173 'fa_user' => 'img_user',
2174 'fa_user_text' => 'img_user_text',
2175 'fa_timestamp' => 'img_timestamp',
2176 'fa_sha1' => 'img_sha1',
2177 ), $where, __METHOD__ );
2178 }
2179
2180 if ( count( $oldRels ) ) {
2181 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2182 $where = array(
2183 'oi_name' => $this->file->getName(),
2184 'oi_archive_name' => array_keys( $oldRels ) );
2185 $dbw->insertSelect( 'filearchive', 'oldimage',
2186 array(
2187 'fa_storage_group' => $encGroup,
2188 'fa_storage_key' => $dbw->conditional(
2189 array( 'oi_sha1' => '' ),
2190 $dbw->addQuotes( '' ),
2191 $concat
2192 ),
2193 'fa_deleted_user' => $encUserId,
2194 'fa_deleted_timestamp' => $encTimestamp,
2195 'fa_deleted_reason' => $encReason,
2196 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2197
2198 'fa_name' => 'oi_name',
2199 'fa_archive_name' => 'oi_archive_name',
2200 'fa_size' => 'oi_size',
2201 'fa_width' => 'oi_width',
2202 'fa_height' => 'oi_height',
2203 'fa_metadata' => 'oi_metadata',
2204 'fa_bits' => 'oi_bits',
2205 'fa_media_type' => 'oi_media_type',
2206 'fa_major_mime' => 'oi_major_mime',
2207 'fa_minor_mime' => 'oi_minor_mime',
2208 'fa_description' => 'oi_description',
2209 'fa_user' => 'oi_user',
2210 'fa_user_text' => 'oi_user_text',
2211 'fa_timestamp' => 'oi_timestamp',
2212 'fa_sha1' => 'oi_sha1',
2213 ), $where, __METHOD__ );
2214 }
2215 }
2216
2217 function doDBDeletes() {
2218 $dbw = $this->file->repo->getMasterDB();
2219 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2220
2221 if ( count( $oldRels ) ) {
2222 $dbw->delete( 'oldimage',
2223 array(
2224 'oi_name' => $this->file->getName(),
2225 'oi_archive_name' => array_keys( $oldRels )
2226 ), __METHOD__ );
2227 }
2228
2229 if ( $deleteCurrent ) {
2230 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
2231 }
2232 }
2233
2234 /**
2235 * Run the transaction
2236 * @return FileRepoStatus
2237 */
2238 function execute() {
2239 wfProfileIn( __METHOD__ );
2240
2241 $this->file->lock();
2242 // Leave private files alone
2243 $privateFiles = array();
2244 list( $oldRels, ) = $this->getOldRels();
2245 $dbw = $this->file->repo->getMasterDB();
2246
2247 if ( !empty( $oldRels ) ) {
2248 $res = $dbw->select( 'oldimage',
2249 array( 'oi_archive_name' ),
2250 array( 'oi_name' => $this->file->getName(),
2251 'oi_archive_name' => array_keys( $oldRels ),
2252 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
2253 __METHOD__ );
2254
2255 foreach ( $res as $row ) {
2256 $privateFiles[$row->oi_archive_name] = 1;
2257 }
2258 }
2259 // Prepare deletion batch
2260 $hashes = $this->getHashes();
2261 $this->deletionBatch = array();
2262 $ext = $this->file->getExtension();
2263 $dotExt = $ext === '' ? '' : ".$ext";
2264
2265 foreach ( $this->srcRels as $name => $srcRel ) {
2266 // Skip files that have no hash (missing source).
2267 // Keep private files where they are.
2268 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2269 $hash = $hashes[$name];
2270 $key = $hash . $dotExt;
2271 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2272 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2273 }
2274 }
2275
2276 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2277 // We acquire this lock by running the inserts now, before the file operations.
2278 //
2279 // This potentially has poor lock contention characteristics -- an alternative
2280 // scheme would be to insert stub filearchive entries with no fa_name and commit
2281 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2282 $this->doDBInserts();
2283
2284 // Removes non-existent file from the batch, so we don't get errors.
2285 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
2286
2287 // Execute the file deletion batch
2288 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2289
2290 if ( !$status->isGood() ) {
2291 $this->status->merge( $status );
2292 }
2293
2294 if ( !$this->status->isOK() ) {
2295 // Critical file deletion error
2296 // Roll back inserts, release lock and abort
2297 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2298 $this->file->unlockAndRollback();
2299 wfProfileOut( __METHOD__ );
2300
2301 return $this->status;
2302 }
2303
2304 // Delete image/oldimage rows
2305 $this->doDBDeletes();
2306
2307 // Commit and return
2308 $this->file->unlock();
2309 wfProfileOut( __METHOD__ );
2310
2311 return $this->status;
2312 }
2313
2314 /**
2315 * Removes non-existent files from a deletion batch.
2316 * @param array $batch
2317 * @return array
2318 */
2319 function removeNonexistentFiles( $batch ) {
2320 $files = $newBatch = array();
2321
2322 foreach ( $batch as $batchItem ) {
2323 list( $src, ) = $batchItem;
2324 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2325 }
2326
2327 $result = $this->file->repo->fileExistsBatch( $files );
2328
2329 foreach ( $batch as $batchItem ) {
2330 if ( $result[$batchItem[0]] ) {
2331 $newBatch[] = $batchItem;
2332 }
2333 }
2334
2335 return $newBatch;
2336 }
2337 }
2338
2339 # ------------------------------------------------------------------------------
2340
2341 /**
2342 * Helper class for file undeletion
2343 * @ingroup FileAbstraction
2344 */
2345 class LocalFileRestoreBatch {
2346 /** @var LocalFile */
2347 private $file;
2348
2349 /** @var array List of file IDs to restore */
2350 private $cleanupBatch;
2351
2352 /** @var array List of file IDs to restore */
2353 private $ids;
2354
2355 /** @var bool Add all revisions of the file */
2356 private $all;
2357
2358 /** @var bool Wether to remove all settings for suppressed fields */
2359 private $unsuppress = false;
2360
2361 /**
2362 * @param File $file
2363 * @param bool $unsuppress
2364 */
2365 function __construct( File $file, $unsuppress = false ) {
2366 $this->file = $file;
2367 $this->cleanupBatch = $this->ids = array();
2368 $this->ids = array();
2369 $this->unsuppress = $unsuppress;
2370 }
2371
2372 /**
2373 * Add a file by ID
2374 */
2375 function addId( $fa_id ) {
2376 $this->ids[] = $fa_id;
2377 }
2378
2379 /**
2380 * Add a whole lot of files by ID
2381 */
2382 function addIds( $ids ) {
2383 $this->ids = array_merge( $this->ids, $ids );
2384 }
2385
2386 /**
2387 * Add all revisions of the file
2388 */
2389 function addAll() {
2390 $this->all = true;
2391 }
2392
2393 /**
2394 * Run the transaction, except the cleanup batch.
2395 * The cleanup batch should be run in a separate transaction, because it locks different
2396 * rows and there's no need to keep the image row locked while it's acquiring those locks
2397 * The caller may have its own transaction open.
2398 * So we save the batch and let the caller call cleanup()
2399 * @return FileRepoStatus
2400 */
2401 function execute() {
2402 global $wgLang;
2403
2404 if ( !$this->all && !$this->ids ) {
2405 // Do nothing
2406 return $this->file->repo->newGood();
2407 }
2408
2409 $this->file->lock();
2410
2411 $dbw = $this->file->repo->getMasterDB();
2412 $status = $this->file->repo->newGood();
2413
2414 $exists = (bool)$dbw->selectField( 'image', '1',
2415 array( 'img_name' => $this->file->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
2416
2417 // Fetch all or selected archived revisions for the file,
2418 // sorted from the most recent to the oldest.
2419 $conditions = array( 'fa_name' => $this->file->getName() );
2420
2421 if ( !$this->all ) {
2422 $conditions['fa_id'] = $this->ids;
2423 }
2424
2425 $result = $dbw->select(
2426 'filearchive',
2427 ArchivedFile::selectFields(),
2428 $conditions,
2429 __METHOD__,
2430 array( 'ORDER BY' => 'fa_timestamp DESC' )
2431 );
2432
2433 $idsPresent = array();
2434 $storeBatch = array();
2435 $insertBatch = array();
2436 $insertCurrent = false;
2437 $deleteIds = array();
2438 $first = true;
2439 $archiveNames = array();
2440
2441 foreach ( $result as $row ) {
2442 $idsPresent[] = $row->fa_id;
2443
2444 if ( $row->fa_name != $this->file->getName() ) {
2445 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2446 $status->failCount++;
2447 continue;
2448 }
2449
2450 if ( $row->fa_storage_key == '' ) {
2451 // Revision was missing pre-deletion
2452 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2453 $status->failCount++;
2454 continue;
2455 }
2456
2457 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2458 $row->fa_storage_key;
2459 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2460
2461 if ( isset( $row->fa_sha1 ) ) {
2462 $sha1 = $row->fa_sha1;
2463 } else {
2464 // old row, populate from key
2465 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2466 }
2467
2468 # Fix leading zero
2469 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2470 $sha1 = substr( $sha1, 1 );
2471 }
2472
2473 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2474 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2475 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2476 || is_null( $row->fa_metadata )
2477 ) {
2478 // Refresh our metadata
2479 // Required for a new current revision; nice for older ones too. :)
2480 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2481 } else {
2482 $props = array(
2483 'minor_mime' => $row->fa_minor_mime,
2484 'major_mime' => $row->fa_major_mime,
2485 'media_type' => $row->fa_media_type,
2486 'metadata' => $row->fa_metadata
2487 );
2488 }
2489
2490 if ( $first && !$exists ) {
2491 // This revision will be published as the new current version
2492 $destRel = $this->file->getRel();
2493 $insertCurrent = array(
2494 'img_name' => $row->fa_name,
2495 'img_size' => $row->fa_size,
2496 'img_width' => $row->fa_width,
2497 'img_height' => $row->fa_height,
2498 'img_metadata' => $props['metadata'],
2499 'img_bits' => $row->fa_bits,
2500 'img_media_type' => $props['media_type'],
2501 'img_major_mime' => $props['major_mime'],
2502 'img_minor_mime' => $props['minor_mime'],
2503 'img_description' => $row->fa_description,
2504 'img_user' => $row->fa_user,
2505 'img_user_text' => $row->fa_user_text,
2506 'img_timestamp' => $row->fa_timestamp,
2507 'img_sha1' => $sha1
2508 );
2509
2510 // The live (current) version cannot be hidden!
2511 if ( !$this->unsuppress && $row->fa_deleted ) {
2512 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2513 $this->cleanupBatch[] = $row->fa_storage_key;
2514 }
2515 } else {
2516 $archiveName = $row->fa_archive_name;
2517
2518 if ( $archiveName == '' ) {
2519 // This was originally a current version; we
2520 // have to devise a new archive name for it.
2521 // Format is <timestamp of archiving>!<name>
2522 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2523
2524 do {
2525 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2526 $timestamp++;
2527 } while ( isset( $archiveNames[$archiveName] ) );
2528 }
2529
2530 $archiveNames[$archiveName] = true;
2531 $destRel = $this->file->getArchiveRel( $archiveName );
2532 $insertBatch[] = array(
2533 'oi_name' => $row->fa_name,
2534 'oi_archive_name' => $archiveName,
2535 'oi_size' => $row->fa_size,
2536 'oi_width' => $row->fa_width,
2537 'oi_height' => $row->fa_height,
2538 'oi_bits' => $row->fa_bits,
2539 'oi_description' => $row->fa_description,
2540 'oi_user' => $row->fa_user,
2541 'oi_user_text' => $row->fa_user_text,
2542 'oi_timestamp' => $row->fa_timestamp,
2543 'oi_metadata' => $props['metadata'],
2544 'oi_media_type' => $props['media_type'],
2545 'oi_major_mime' => $props['major_mime'],
2546 'oi_minor_mime' => $props['minor_mime'],
2547 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2548 'oi_sha1' => $sha1 );
2549 }
2550
2551 $deleteIds[] = $row->fa_id;
2552
2553 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2554 // private files can stay where they are
2555 $status->successCount++;
2556 } else {
2557 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2558 $this->cleanupBatch[] = $row->fa_storage_key;
2559 }
2560
2561 $first = false;
2562 }
2563
2564 unset( $result );
2565
2566 // Add a warning to the status object for missing IDs
2567 $missingIds = array_diff( $this->ids, $idsPresent );
2568
2569 foreach ( $missingIds as $id ) {
2570 $status->error( 'undelete-missing-filearchive', $id );
2571 }
2572
2573 // Remove missing files from batch, so we don't get errors when undeleting them
2574 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2575
2576 // Run the store batch
2577 // Use the OVERWRITE_SAME flag to smooth over a common error
2578 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2579 $status->merge( $storeStatus );
2580
2581 if ( !$status->isGood() ) {
2582 // Even if some files could be copied, fail entirely as that is the
2583 // easiest thing to do without data loss
2584 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2585 $status->ok = false;
2586 $this->file->unlock();
2587
2588 return $status;
2589 }
2590
2591 // Run the DB updates
2592 // Because we have locked the image row, key conflicts should be rare.
2593 // If they do occur, we can roll back the transaction at this time with
2594 // no data loss, but leaving unregistered files scattered throughout the
2595 // public zone.
2596 // This is not ideal, which is why it's important to lock the image row.
2597 if ( $insertCurrent ) {
2598 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2599 }
2600
2601 if ( $insertBatch ) {
2602 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2603 }
2604
2605 if ( $deleteIds ) {
2606 $dbw->delete( 'filearchive',
2607 array( 'fa_id' => $deleteIds ),
2608 __METHOD__ );
2609 }
2610
2611 // If store batch is empty (all files are missing), deletion is to be considered successful
2612 if ( $status->successCount > 0 || !$storeBatch ) {
2613 if ( !$exists ) {
2614 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2615
2616 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2617
2618 $this->file->purgeEverything();
2619 } else {
2620 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2621 $this->file->purgeDescription();
2622 $this->file->purgeHistory();
2623 }
2624 }
2625
2626 $this->file->unlock();
2627
2628 return $status;
2629 }
2630
2631 /**
2632 * Removes non-existent files from a store batch.
2633 * @param array $triplets
2634 * @return array
2635 */
2636 function removeNonexistentFiles( $triplets ) {
2637 $files = $filteredTriplets = array();
2638 foreach ( $triplets as $file ) {
2639 $files[$file[0]] = $file[0];
2640 }
2641
2642 $result = $this->file->repo->fileExistsBatch( $files );
2643
2644 foreach ( $triplets as $file ) {
2645 if ( $result[$file[0]] ) {
2646 $filteredTriplets[] = $file;
2647 }
2648 }
2649
2650 return $filteredTriplets;
2651 }
2652
2653 /**
2654 * Removes non-existent files from a cleanup batch.
2655 * @param array $batch
2656 * @return array
2657 */
2658 function removeNonexistentFromCleanup( $batch ) {
2659 $files = $newBatch = array();
2660 $repo = $this->file->repo;
2661
2662 foreach ( $batch as $file ) {
2663 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2664 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2665 }
2666
2667 $result = $repo->fileExistsBatch( $files );
2668
2669 foreach ( $batch as $file ) {
2670 if ( $result[$file] ) {
2671 $newBatch[] = $file;
2672 }
2673 }
2674
2675 return $newBatch;
2676 }
2677
2678 /**
2679 * Delete unused files in the deleted zone.
2680 * This should be called from outside the transaction in which execute() was called.
2681 * @return FileRepoStatus
2682 */
2683 function cleanup() {
2684 if ( !$this->cleanupBatch ) {
2685 return $this->file->repo->newGood();
2686 }
2687
2688 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2689
2690 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2691
2692 return $status;
2693 }
2694
2695 /**
2696 * Cleanup a failed batch. The batch was only partially successful, so
2697 * rollback by removing all items that were succesfully copied.
2698 *
2699 * @param Status $storeStatus
2700 * @param array $storeBatch
2701 */
2702 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2703 $cleanupBatch = array();
2704
2705 foreach ( $storeStatus->success as $i => $success ) {
2706 // Check if this item of the batch was successfully copied
2707 if ( $success ) {
2708 // Item was successfully copied and needs to be removed again
2709 // Extract ($dstZone, $dstRel) from the batch
2710 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2711 }
2712 }
2713 $this->file->repo->cleanupBatch( $cleanupBatch );
2714 }
2715 }
2716
2717 # ------------------------------------------------------------------------------
2718
2719 /**
2720 * Helper class for file movement
2721 * @ingroup FileAbstraction
2722 */
2723 class LocalFileMoveBatch {
2724 /** @var LocalFile */
2725 protected $file;
2726
2727 /** @var Title */
2728 protected $target;
2729
2730 protected $cur;
2731
2732 protected $olds;
2733
2734 protected $oldCount;
2735
2736 protected $archive;
2737
2738 /** @var DatabaseBase */
2739 protected $db;
2740
2741 /**
2742 * @param File $file
2743 * @param Title $target
2744 */
2745 function __construct( File $file, Title $target ) {
2746 $this->file = $file;
2747 $this->target = $target;
2748 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2749 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2750 $this->oldName = $this->file->getName();
2751 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2752 $this->oldRel = $this->oldHash . $this->oldName;
2753 $this->newRel = $this->newHash . $this->newName;
2754 $this->db = $file->getRepo()->getMasterDb();
2755 }
2756
2757 /**
2758 * Add the current image to the batch
2759 */
2760 function addCurrent() {
2761 $this->cur = array( $this->oldRel, $this->newRel );
2762 }
2763
2764 /**
2765 * Add the old versions of the image to the batch
2766 * @return array List of archive names from old versions
2767 */
2768 function addOlds() {
2769 $archiveBase = 'archive';
2770 $this->olds = array();
2771 $this->oldCount = 0;
2772 $archiveNames = array();
2773
2774 $result = $this->db->select( 'oldimage',
2775 array( 'oi_archive_name', 'oi_deleted' ),
2776 array( 'oi_name' => $this->oldName ),
2777 __METHOD__,
2778 array( 'FOR UPDATE' ) // ignore snapshot
2779 );
2780
2781 foreach ( $result as $row ) {
2782 $archiveNames[] = $row->oi_archive_name;
2783 $oldName = $row->oi_archive_name;
2784 $bits = explode( '!', $oldName, 2 );
2785
2786 if ( count( $bits ) != 2 ) {
2787 wfDebug( "Old file name missing !: '$oldName' \n" );
2788 continue;
2789 }
2790
2791 list( $timestamp, $filename ) = $bits;
2792
2793 if ( $this->oldName != $filename ) {
2794 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2795 continue;
2796 }
2797
2798 $this->oldCount++;
2799
2800 // Do we want to add those to oldCount?
2801 if ( $row->oi_deleted & File::DELETED_FILE ) {
2802 continue;
2803 }
2804
2805 $this->olds[] = array(
2806 "{$archiveBase}/{$this->oldHash}{$oldName}",
2807 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2808 );
2809 }
2810
2811 return $archiveNames;
2812 }
2813
2814 /**
2815 * Perform the move.
2816 * @return FileRepoStatus
2817 */
2818 function execute() {
2819 $repo = $this->file->repo;
2820 $status = $repo->newGood();
2821
2822 $triplets = $this->getMoveTriplets();
2823 $triplets = $this->removeNonexistentFiles( $triplets );
2824 $destFile = wfLocalFile( $this->target );
2825
2826 $this->file->lock(); // begin
2827 $destFile->lock(); // quickly fail if destination is not available
2828 // Rename the file versions metadata in the DB.
2829 // This implicitly locks the destination file, which avoids race conditions.
2830 // If we moved the files from A -> C before DB updates, another process could
2831 // move files from B -> C at this point, causing storeBatch() to fail and thus
2832 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2833 $statusDb = $this->doDBUpdates();
2834 if ( !$statusDb->isGood() ) {
2835 $destFile->unlock();
2836 $this->file->unlockAndRollback();
2837 $statusDb->ok = false;
2838
2839 return $statusDb;
2840 }
2841 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2842 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2843
2844 // Copy the files into their new location.
2845 // If a prior process fataled copying or cleaning up files we tolerate any
2846 // of the existing files if they are identical to the ones being stored.
2847 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2848 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2849 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2850 if ( !$statusMove->isGood() ) {
2851 // Delete any files copied over (while the destination is still locked)
2852 $this->cleanupTarget( $triplets );
2853 $destFile->unlock();
2854 $this->file->unlockAndRollback(); // unlocks the destination
2855 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2856 $statusMove->ok = false;
2857
2858 return $statusMove;
2859 }
2860 $destFile->unlock();
2861 $this->file->unlock(); // done
2862
2863 // Everything went ok, remove the source files
2864 $this->cleanupSource( $triplets );
2865
2866 $status->merge( $statusDb );
2867 $status->merge( $statusMove );
2868
2869 return $status;
2870 }
2871
2872 /**
2873 * Do the database updates and return a new FileRepoStatus indicating how
2874 * many rows where updated.
2875 *
2876 * @return FileRepoStatus
2877 */
2878 function doDBUpdates() {
2879 $repo = $this->file->repo;
2880 $status = $repo->newGood();
2881 $dbw = $this->db;
2882
2883 // Update current image
2884 $dbw->update(
2885 'image',
2886 array( 'img_name' => $this->newName ),
2887 array( 'img_name' => $this->oldName ),
2888 __METHOD__
2889 );
2890
2891 if ( $dbw->affectedRows() ) {
2892 $status->successCount++;
2893 } else {
2894 $status->failCount++;
2895 $status->fatal( 'imageinvalidfilename' );
2896
2897 return $status;
2898 }
2899
2900 // Update old images
2901 $dbw->update(
2902 'oldimage',
2903 array(
2904 'oi_name' => $this->newName,
2905 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2906 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2907 ),
2908 array( 'oi_name' => $this->oldName ),
2909 __METHOD__
2910 );
2911
2912 $affected = $dbw->affectedRows();
2913 $total = $this->oldCount;
2914 $status->successCount += $affected;
2915 // Bug 34934: $total is based on files that actually exist.
2916 // There may be more DB rows than such files, in which case $affected
2917 // can be greater than $total. We use max() to avoid negatives here.
2918 $status->failCount += max( 0, $total - $affected );
2919 if ( $status->failCount ) {
2920 $status->error( 'imageinvalidfilename' );
2921 }
2922
2923 return $status;
2924 }
2925
2926 /**
2927 * Generate triplets for FileRepo::storeBatch().
2928 * @return array
2929 */
2930 function getMoveTriplets() {
2931 $moves = array_merge( array( $this->cur ), $this->olds );
2932 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2933
2934 foreach ( $moves as $move ) {
2935 // $move: (oldRelativePath, newRelativePath)
2936 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2937 $triplets[] = array( $srcUrl, 'public', $move[1] );
2938 wfDebugLog(
2939 'imagemove',
2940 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2941 );
2942 }
2943
2944 return $triplets;
2945 }
2946
2947 /**
2948 * Removes non-existent files from move batch.
2949 * @param array $triplets
2950 * @return array
2951 */
2952 function removeNonexistentFiles( $triplets ) {
2953 $files = array();
2954
2955 foreach ( $triplets as $file ) {
2956 $files[$file[0]] = $file[0];
2957 }
2958
2959 $result = $this->file->repo->fileExistsBatch( $files );
2960 $filteredTriplets = array();
2961
2962 foreach ( $triplets as $file ) {
2963 if ( $result[$file[0]] ) {
2964 $filteredTriplets[] = $file;
2965 } else {
2966 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2967 }
2968 }
2969
2970 return $filteredTriplets;
2971 }
2972
2973 /**
2974 * Cleanup a partially moved array of triplets by deleting the target
2975 * files. Called if something went wrong half way.
2976 */
2977 function cleanupTarget( $triplets ) {
2978 // Create dest pairs from the triplets
2979 $pairs = array();
2980 foreach ( $triplets as $triplet ) {
2981 // $triplet: (old source virtual URL, dst zone, dest rel)
2982 $pairs[] = array( $triplet[1], $triplet[2] );
2983 }
2984
2985 $this->file->repo->cleanupBatch( $pairs );
2986 }
2987
2988 /**
2989 * Cleanup a fully moved array of triplets by deleting the source files.
2990 * Called at the end of the move process if everything else went ok.
2991 */
2992 function cleanupSource( $triplets ) {
2993 // Create source file names from the triplets
2994 $files = array();
2995 foreach ( $triplets as $triplet ) {
2996 $files[] = $triplet[0];
2997 }
2998
2999 $this->file->repo->cleanupBatch( $files );
3000 }
3001 }