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