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