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