Merge "Add SVG versions of enhanced recent changes collapse/show arrows"
[lhc/web/wiklou.git] / includes / filerepo / file / LocalFile.php
1 <?php
2 /**
3 * Local file in the wiki's own database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileAbstraction
22 */
23
24 /**
25 * Bump this number when serialized cache records may be incompatible.
26 */
27 define( 'MW_FILE_VERSION', 9 );
28
29 /**
30 * Class to represent a local file in the wiki's own database
31 *
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
34 *
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
38 *
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
40 *
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
42 * in most cases.
43 *
44 * @ingroup FileAbstraction
45 */
46 class LocalFile extends File {
47 const CACHE_FIELD_MAX_LEN = 1000;
48
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
51
52 /** @var int image width */
53 protected $width;
54
55 /** @var int image height */
56 protected $height;
57
58 /** @var int Returned by getimagesize (loadFromXxx) */
59 protected $bits;
60
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
63
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
65 protected $mime;
66
67 /** @var int Size in bytes (loadFromXxx) */
68 protected $size;
69
70 /** @var string Handler-specific metadata */
71 protected $metadata;
72
73 /** @var string SHA-1 base 36 content hash */
74 protected $sha1;
75
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
78
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
81
82 /** @var int Bitfield akin to rev_deleted */
83 protected $deleted;
84
85 /** @var string */
86 protected $repoClass = 'LocalRepo';
87
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
89 private $historyLine;
90
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
92 private $historyRes;
93
94 /** @var string Major mime type */
95 private $major_mime;
96
97 /** @var string Minor mime type */
98 private $minor_mime;
99
100 /** @var string Upload timestamp */
101 private $timestamp;
102
103 /** @var int User ID of uploader */
104 private $user;
105
106 /** @var string User name of uploader */
107 private $user_text;
108
109 /** @var string Description of current revision of the file */
110 private $description;
111
112 /** @var bool Whether the row was upgraded on load */
113 private $upgraded;
114
115 /** @var bool True if the image row is locked */
116 private $locked;
117
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
120
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
122 private $missing;
123
124 const LOAD_ALL = 1; // integer; load all the lazy fields too (like metadata)
125
126 /**
127 * Create a LocalFile from a title
128 * Do not call this except from inside a repo class.
129 *
130 * Note: $unused param is only here to avoid an E_STRICT
131 *
132 * @param Title $title
133 * @param FileRepo $repo
134 * @param $unused
135 *
136 * @return LocalFile
137 */
138 static function newFromTitle( $title, $repo, $unused = null ) {
139 return new self( $title, $repo );
140 }
141
142 /**
143 * Create a LocalFile from a title
144 * Do not call this except from inside a repo class.
145 *
146 * @param stdClass $row
147 * @param FileRepo $repo
148 *
149 * @return LocalFile
150 */
151 static function newFromRow( $row, $repo ) {
152 $title = Title::makeTitle( NS_FILE, $row->img_name );
153 $file = new self( $title, $repo );
154 $file->loadFromRow( $row );
155
156 return $file;
157 }
158
159 /**
160 * Create a LocalFile from a SHA-1 key
161 * Do not call this except from inside a repo class.
162 *
163 * @param string $sha1 base-36 SHA-1
164 * @param LocalRepo $repo
165 * @param string|bool $timestamp MW_timestamp (optional)
166 * @return bool|LocalFile
167 */
168 static function newFromKey( $sha1, $repo, $timestamp = false ) {
169 $dbr = $repo->getSlaveDB();
170
171 $conds = array( 'img_sha1' => $sha1 );
172 if ( $timestamp ) {
173 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
174 }
175
176 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
177 if ( $row ) {
178 return self::newFromRow( $row, $repo );
179 } else {
180 return false;
181 }
182 }
183
184 /**
185 * Fields in the image table
186 * @return array
187 */
188 static function selectFields() {
189 return array(
190 'img_name',
191 'img_size',
192 'img_width',
193 'img_height',
194 'img_metadata',
195 'img_bits',
196 'img_media_type',
197 'img_major_mime',
198 'img_minor_mime',
199 'img_description',
200 'img_user',
201 'img_user_text',
202 'img_timestamp',
203 'img_sha1',
204 );
205 }
206
207 /**
208 * Constructor.
209 * Do not call this except from inside a repo class.
210 */
211 function __construct( $title, $repo ) {
212 parent::__construct( $title, $repo );
213
214 $this->metadata = '';
215 $this->historyLine = 0;
216 $this->historyRes = null;
217 $this->dataLoaded = false;
218 $this->extraDataLoaded = false;
219
220 $this->assertRepoDefined();
221 $this->assertTitleDefined();
222 }
223
224 /**
225 * Get the memcached key for the main data for this file, or false if
226 * there is no access to the shared cache.
227 * @return bool
228 */
229 function getCacheKey() {
230 $hashedName = md5( $this->getName() );
231
232 return $this->repo->getSharedCacheKey( 'file', $hashedName );
233 }
234
235 /**
236 * Try to load file metadata from memcached. Returns true on success.
237 * @return bool
238 */
239 function loadFromCache() {
240 global $wgMemc;
241
242 wfProfileIn( __METHOD__ );
243 $this->dataLoaded = false;
244 $this->extraDataLoaded = false;
245 $key = $this->getCacheKey();
246
247 if ( !$key ) {
248 wfProfileOut( __METHOD__ );
249
250 return false;
251 }
252
253 $cachedValues = $wgMemc->get( $key );
254
255 // Check if the key existed and belongs to this version of MediaWiki
256 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION ) {
257 wfDebug( "Pulling file metadata from cache key $key\n" );
258 $this->fileExists = $cachedValues['fileExists'];
259 if ( $this->fileExists ) {
260 $this->setProps( $cachedValues );
261 }
262 $this->dataLoaded = true;
263 $this->extraDataLoaded = true;
264 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
265 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
266 }
267 }
268
269 if ( $this->dataLoaded ) {
270 wfIncrStats( 'image_cache_hit' );
271 } else {
272 wfIncrStats( 'image_cache_miss' );
273 }
274
275 wfProfileOut( __METHOD__ );
276
277 return $this->dataLoaded;
278 }
279
280 /**
281 * Save the file metadata to memcached
282 */
283 function saveToCache() {
284 global $wgMemc;
285
286 $this->load();
287 $key = $this->getCacheKey();
288
289 if ( !$key ) {
290 return;
291 }
292
293 $fields = $this->getCacheFields( '' );
294 $cache = array( 'version' => MW_FILE_VERSION );
295 $cache['fileExists'] = $this->fileExists;
296
297 if ( $this->fileExists ) {
298 foreach ( $fields as $field ) {
299 $cache[$field] = $this->$field;
300 }
301 }
302
303 // Strip off excessive entries from the subset of fields that can become large.
304 // If the cache value gets to large it will not fit in memcached and nothing will
305 // get cached at all, causing master queries for any file access.
306 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
307 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
308 unset( $cache[$field] ); // don't let the value get too big
309 }
310 }
311
312 // Cache presence for 1 week and negatives for 1 day
313 $wgMemc->set( $key, $cache, $this->fileExists ? 86400 * 7 : 86400 );
314 }
315
316 /**
317 * Load metadata from the file itself
318 */
319 function loadFromFile() {
320 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
321 $this->setProps( $props );
322 }
323
324 /**
325 * @param $prefix string
326 * @return array
327 */
328 function getCacheFields( $prefix = 'img_' ) {
329 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
330 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
331 'user_text', 'description' );
332 static $results = array();
333
334 if ( $prefix == '' ) {
335 return $fields;
336 }
337
338 if ( !isset( $results[$prefix] ) ) {
339 $prefixedFields = array();
340 foreach ( $fields as $field ) {
341 $prefixedFields[] = $prefix . $field;
342 }
343 $results[$prefix] = $prefixedFields;
344 }
345
346 return $results[$prefix];
347 }
348
349 /**
350 * @param string $prefix
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 array $row Row
434 * @param string $prefix
435 * @throws MWException
436 * @return array
437 */
438 protected function unprefixRow( $row, $prefix = 'img_' ) {
439 $array = (array)$row;
440 $prefixLength = strlen( $prefix );
441
442 // Sanity check prefix once
443 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
444 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
445 }
446
447 $decoded = array();
448 foreach ( $array as $name => $value ) {
449 $decoded[substr( $name, $prefixLength )] = $value;
450 }
451
452 return $decoded;
453 }
454
455 /**
456 * Decode a row from the database (either object or array) to an array
457 * with timestamps and MIME types decoded, and the field prefix removed.
458 * @param $row
459 * @param $prefix string
460 * @throws MWException
461 * @return array
462 */
463 function decodeRow( $row, $prefix = 'img_' ) {
464 $decoded = $this->unprefixRow( $row, $prefix );
465
466 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
467
468 if ( empty( $decoded['major_mime'] ) ) {
469 $decoded['mime'] = 'unknown/unknown';
470 } else {
471 if ( !$decoded['minor_mime'] ) {
472 $decoded['minor_mime'] = 'unknown';
473 }
474 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
475 }
476
477 # Trim zero padding from char/binary field
478 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
479
480 return $decoded;
481 }
482
483 /**
484 * Load file metadata from a DB result row
485 */
486 function loadFromRow( $row, $prefix = 'img_' ) {
487 $this->dataLoaded = true;
488 $this->extraDataLoaded = true;
489
490 $array = $this->decodeRow( $row, $prefix );
491
492 foreach ( $array as $name => $value ) {
493 $this->$name = $value;
494 }
495
496 $this->fileExists = true;
497 $this->maybeUpgradeRow();
498 }
499
500 /**
501 * Load file metadata from cache or DB, unless already loaded
502 * @param integer $flags
503 */
504 function load( $flags = 0 ) {
505 if ( !$this->dataLoaded ) {
506 if ( !$this->loadFromCache() ) {
507 $this->loadFromDB();
508 $this->saveToCache();
509 }
510 $this->dataLoaded = true;
511 }
512 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
513 $this->loadExtraFromDB();
514 }
515 }
516
517 /**
518 * Upgrade a row if it needs it
519 */
520 function maybeUpgradeRow() {
521 global $wgUpdateCompatibleMetadata;
522 if ( wfReadOnly() ) {
523 return;
524 }
525
526 if ( is_null( $this->media_type ) ||
527 $this->mime == 'image/svg'
528 ) {
529 $this->upgradeRow();
530 $this->upgraded = true;
531 } else {
532 $handler = $this->getHandler();
533 if ( $handler ) {
534 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
535 if ( $validity === MediaHandler::METADATA_BAD
536 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
537 ) {
538 $this->upgradeRow();
539 $this->upgraded = true;
540 }
541 }
542 }
543 }
544
545 function getUpgraded() {
546 return $this->upgraded;
547 }
548
549 /**
550 * Fix assorted version-related problems with the image row by reloading it from the file
551 */
552 function upgradeRow() {
553 wfProfileIn( __METHOD__ );
554
555 $this->lock(); // begin
556
557 $this->loadFromFile();
558
559 # Don't destroy file info of missing files
560 if ( !$this->fileExists ) {
561 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
562 wfProfileOut( __METHOD__ );
563
564 return;
565 }
566
567 $dbw = $this->repo->getMasterDB();
568 list( $major, $minor ) = self::splitMime( $this->mime );
569
570 if ( wfReadOnly() ) {
571 wfProfileOut( __METHOD__ );
572
573 return;
574 }
575 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
576
577 $dbw->update( 'image',
578 array(
579 'img_size' => $this->size, // sanity
580 'img_width' => $this->width,
581 'img_height' => $this->height,
582 'img_bits' => $this->bits,
583 'img_media_type' => $this->media_type,
584 'img_major_mime' => $major,
585 'img_minor_mime' => $minor,
586 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
587 'img_sha1' => $this->sha1,
588 ),
589 array( 'img_name' => $this->getName() ),
590 __METHOD__
591 );
592
593 $this->saveToCache();
594
595 $this->unlock(); // done
596
597 wfProfileOut( __METHOD__ );
598 }
599
600 /**
601 * Set properties in this object to be equal to those given in the
602 * associative array $info. Only cacheable fields can be set.
603 * All fields *must* be set in $info except for getLazyCacheFields().
604 *
605 * If 'mime' is given, it will be split into major_mime/minor_mime.
606 * If major_mime/minor_mime are given, $this->mime will also be set.
607 */
608 function setProps( $info ) {
609 $this->dataLoaded = true;
610 $fields = $this->getCacheFields( '' );
611 $fields[] = 'fileExists';
612
613 foreach ( $fields as $field ) {
614 if ( isset( $info[$field] ) ) {
615 $this->$field = $info[$field];
616 }
617 }
618
619 // Fix up mime fields
620 if ( isset( $info['major_mime'] ) ) {
621 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
622 } elseif ( isset( $info['mime'] ) ) {
623 $this->mime = $info['mime'];
624 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
625 }
626 }
627
628 /** splitMime inherited */
629 /** getName inherited */
630 /** getTitle inherited */
631 /** getURL inherited */
632 /** getViewURL inherited */
633 /** getPath inherited */
634 /** isVisible inhereted */
635
636 /**
637 * @return bool
638 */
639 function isMissing() {
640 if ( $this->missing === null ) {
641 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
642 $this->missing = !$fileExists;
643 }
644
645 return $this->missing;
646 }
647
648 /**
649 * Return the width of the image
650 *
651 * @param int $page
652 * @return int
653 */
654 public function getWidth( $page = 1 ) {
655 $this->load();
656
657 if ( $this->isMultipage() ) {
658 $handler = $this->getHandler();
659 if ( !$handler ) {
660 return 0;
661 }
662 $dim = $handler->getPageDimensions( $this, $page );
663 if ( $dim ) {
664 return $dim['width'];
665 } else {
666 // For non-paged media, the false goes through an
667 // intval, turning failure into 0, so do same here.
668 return 0;
669 }
670 } else {
671 return $this->width;
672 }
673 }
674
675 /**
676 * Return the height of the image
677 *
678 * @param int $page
679 * @return int
680 */
681 public function getHeight( $page = 1 ) {
682 $this->load();
683
684 if ( $this->isMultipage() ) {
685 $handler = $this->getHandler();
686 if ( !$handler ) {
687 return 0;
688 }
689 $dim = $handler->getPageDimensions( $this, $page );
690 if ( $dim ) {
691 return $dim['height'];
692 } else {
693 // For non-paged media, the false goes through an
694 // intval, turning failure into 0, so do same here.
695 return 0;
696 }
697 } else {
698 return $this->height;
699 }
700 }
701
702 /**
703 * Returns ID or name of user who uploaded the file
704 *
705 * @param string $type 'text' or 'id'
706 * @return int|string
707 */
708 function getUser( $type = 'text' ) {
709 $this->load();
710
711 if ( $type == 'text' ) {
712 return $this->user_text;
713 } elseif ( $type == 'id' ) {
714 return $this->user;
715 }
716 }
717
718 /**
719 * Get handler-specific metadata
720 * @return string
721 */
722 function getMetadata() {
723 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
724 return $this->metadata;
725 }
726
727 /**
728 * @return int
729 */
730 function getBitDepth() {
731 $this->load();
732
733 return $this->bits;
734 }
735
736 /**
737 * Returns the size of the image file, in bytes
738 * @return int
739 */
740 public function getSize() {
741 $this->load();
742
743 return $this->size;
744 }
745
746 /**
747 * Returns the mime type of the file.
748 * @return string
749 */
750 function getMimeType() {
751 $this->load();
752
753 return $this->mime;
754 }
755
756 /**
757 * Returns the type of the media in the file.
758 * Use the value returned by this function with the MEDIATYPE_xxx constants.
759 * @return string
760 */
761 function getMediaType() {
762 $this->load();
763
764 return $this->media_type;
765 }
766
767 /** canRender inherited */
768 /** mustRender inherited */
769 /** allowInlineDisplay inherited */
770 /** isSafeFile inherited */
771 /** isTrustedFile inherited */
772
773 /**
774 * Returns true if the file exists on disk.
775 * @return bool Whether file exist on disk.
776 */
777 public function exists() {
778 $this->load();
779
780 return $this->fileExists;
781 }
782
783 /** getTransformScript inherited */
784 /** getUnscaledThumb inherited */
785 /** thumbName inherited */
786 /** createThumb inherited */
787 /** transform inherited */
788
789 /**
790 * Fix thumbnail files from 1.4 or before, with extreme prejudice
791 * @todo Do we still care about this? Perhaps a maintenance script
792 * can be made instead. Enabling this code results in a serious
793 * RTT regression for wikis without 404 handling.
794 */
795 function migrateThumbFile( $thumbName ) {
796 /* Old code for bug 2532
797 $thumbDir = $this->getThumbPath();
798 $thumbPath = "$thumbDir/$thumbName";
799 if ( is_dir( $thumbPath ) ) {
800 // Directory where file should be
801 // This happened occasionally due to broken migration code in 1.5
802 // Rename to broken-*
803 for ( $i = 0; $i < 100; $i++ ) {
804 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
805 if ( !file_exists( $broken ) ) {
806 rename( $thumbPath, $broken );
807 break;
808 }
809 }
810 // Doesn't exist anymore
811 clearstatcache();
812 }
813 */
814 /*
815 if ( $this->repo->fileExists( $thumbDir ) ) {
816 // Delete file where directory should be
817 $this->repo->cleanupBatch( array( $thumbDir ) );
818 }
819 */
820 }
821
822 /** getHandler inherited */
823 /** iconThumb inherited */
824 /** getLastError inherited */
825
826 /**
827 * Get all thumbnail names previously generated for this file
828 * @param string|bool $archiveName Name of an archive file, default false
829 * @return array first element is the base dir, then files in that base dir.
830 */
831 function getThumbnails( $archiveName = false ) {
832 if ( $archiveName ) {
833 $dir = $this->getArchiveThumbPath( $archiveName );
834 } else {
835 $dir = $this->getThumbPath();
836 }
837
838 $backend = $this->repo->getBackend();
839 $files = array( $dir );
840 try {
841 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
842 foreach ( $iterator as $file ) {
843 $files[] = $file;
844 }
845 } catch ( FileBackendError $e ) {
846 } // suppress (bug 54674)
847
848 return $files;
849 }
850
851 /**
852 * Refresh metadata in memcached, but don't touch thumbnails or squid
853 */
854 function purgeMetadataCache() {
855 $this->loadFromDB();
856 $this->saveToCache();
857 $this->purgeHistory();
858 }
859
860 /**
861 * Purge the shared history (OldLocalFile) cache.
862 *
863 * @note This used to purge old thumbnails as well.
864 */
865 function purgeHistory() {
866 global $wgMemc;
867
868 $hashedName = md5( $this->getName() );
869 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
870
871 if ( $oldKey ) {
872 $wgMemc->delete( $oldKey );
873 }
874 }
875
876 /**
877 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
878 *
879 * @param array $options An array potentially with the key forThumbRefresh.
880 *
881 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
882 */
883 function purgeCache( $options = array() ) {
884 wfProfileIn( __METHOD__ );
885 // Refresh metadata cache
886 $this->purgeMetadataCache();
887
888 // Delete thumbnails
889 $this->purgeThumbnails( $options );
890
891 // Purge squid cache for this file
892 SquidUpdate::purge( array( $this->getURL() ) );
893 wfProfileOut( __METHOD__ );
894 }
895
896 /**
897 * Delete cached transformed files for an archived version only.
898 * @param string $archiveName Name of the archived file
899 */
900 function purgeOldThumbnails( $archiveName ) {
901 global $wgUseSquid;
902 wfProfileIn( __METHOD__ );
903
904 // Get a list of old thumbnails and URLs
905 $files = $this->getThumbnails( $archiveName );
906 $dir = array_shift( $files );
907 $this->purgeThumbList( $dir, $files );
908
909 // Purge any custom thumbnail caches
910 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
911
912 // Purge the squid
913 if ( $wgUseSquid ) {
914 $urls = array();
915 foreach ( $files as $file ) {
916 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
917 }
918 SquidUpdate::purge( $urls );
919 }
920
921 wfProfileOut( __METHOD__ );
922 }
923
924 /**
925 * Delete cached transformed files for the current version only.
926 */
927 function purgeThumbnails( $options = array() ) {
928 global $wgUseSquid;
929 wfProfileIn( __METHOD__ );
930
931 // Delete thumbnails
932 $files = $this->getThumbnails();
933 // Always purge all files from squid regardless of handler filters
934 $urls = array();
935 if ( $wgUseSquid ) {
936 foreach ( $files as $file ) {
937 $urls[] = $this->getThumbUrl( $file );
938 }
939 array_shift( $urls ); // don't purge directory
940 }
941
942 // Give media handler a chance to filter the file purge list
943 if ( !empty( $options['forThumbRefresh'] ) ) {
944 $handler = $this->getHandler();
945 if ( $handler ) {
946 $handler->filterThumbnailPurgeList( $files, $options );
947 }
948 }
949
950 $dir = array_shift( $files );
951 $this->purgeThumbList( $dir, $files );
952
953 // Purge any custom thumbnail caches
954 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
955
956 // Purge the squid
957 if ( $wgUseSquid ) {
958 SquidUpdate::purge( $urls );
959 }
960
961 wfProfileOut( __METHOD__ );
962 }
963
964 /**
965 * Delete a list of thumbnails visible at urls
966 * @param string $dir Base dir of the files.
967 * @param array $files Array of strings: relative filenames (to $dir)
968 */
969 protected function purgeThumbList( $dir, $files ) {
970 $fileListDebug = strtr(
971 var_export( $files, true ),
972 array( "\n" => '' )
973 );
974 wfDebug( __METHOD__ . ": $fileListDebug\n" );
975
976 $purgeList = array();
977 foreach ( $files as $file ) {
978 # Check that the base file name is part of the thumb name
979 # This is a basic sanity check to avoid erasing unrelated directories
980 if ( strpos( $file, $this->getName() ) !== false
981 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
982 ) {
983 $purgeList[] = "{$dir}/{$file}";
984 }
985 }
986
987 # Delete the thumbnails
988 $this->repo->quickPurgeBatch( $purgeList );
989 # Clear out the thumbnail directory if empty
990 $this->repo->quickCleanDir( $dir );
991 }
992
993 /** purgeDescription inherited */
994 /** purgeEverything inherited */
995
996 /**
997 * @param int $limit Optional: Limit to number of results
998 * @param int $start Optional: Timestamp, start from
999 * @param int $end Optional: Timestamp, end at
1000 * @param bool $inc
1001 * @return array
1002 */
1003 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1004 $dbr = $this->repo->getSlaveDB();
1005 $tables = array( 'oldimage' );
1006 $fields = OldLocalFile::selectFields();
1007 $conds = $opts = $join_conds = array();
1008 $eq = $inc ? '=' : '';
1009 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1010
1011 if ( $start ) {
1012 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1013 }
1014
1015 if ( $end ) {
1016 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1017 }
1018
1019 if ( $limit ) {
1020 $opts['LIMIT'] = $limit;
1021 }
1022
1023 // Search backwards for time > x queries
1024 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1025 $opts['ORDER BY'] = "oi_timestamp $order";
1026 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1027
1028 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1029 &$conds, &$opts, &$join_conds ) );
1030
1031 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1032 $r = array();
1033
1034 foreach ( $res as $row ) {
1035 $r[] = $this->repo->newFileFromRow( $row );
1036 }
1037
1038 if ( $order == 'ASC' ) {
1039 $r = array_reverse( $r ); // make sure it ends up descending
1040 }
1041
1042 return $r;
1043 }
1044
1045 /**
1046 * Returns the history of this file, line by line.
1047 * starts with current version, then old versions.
1048 * uses $this->historyLine to check which line to return:
1049 * 0 return line for current version
1050 * 1 query for old versions, return first one
1051 * 2, ... return next old version from above query
1052 * @return bool
1053 */
1054 public function nextHistoryLine() {
1055 # Polymorphic function name to distinguish foreign and local fetches
1056 $fname = get_class( $this ) . '::' . __FUNCTION__;
1057
1058 $dbr = $this->repo->getSlaveDB();
1059
1060 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1061 $this->historyRes = $dbr->select( 'image',
1062 array(
1063 '*',
1064 "'' AS oi_archive_name",
1065 '0 as oi_deleted',
1066 'img_sha1'
1067 ),
1068 array( 'img_name' => $this->title->getDBkey() ),
1069 $fname
1070 );
1071
1072 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1073 $this->historyRes = null;
1074
1075 return false;
1076 }
1077 } elseif ( $this->historyLine == 1 ) {
1078 $this->historyRes = $dbr->select( 'oldimage', '*',
1079 array( 'oi_name' => $this->title->getDBkey() ),
1080 $fname,
1081 array( 'ORDER BY' => 'oi_timestamp DESC' )
1082 );
1083 }
1084 $this->historyLine++;
1085
1086 return $dbr->fetchObject( $this->historyRes );
1087 }
1088
1089 /**
1090 * Reset the history pointer to the first element of the history
1091 */
1092 public function resetHistory() {
1093 $this->historyLine = 0;
1094
1095 if ( !is_null( $this->historyRes ) ) {
1096 $this->historyRes = null;
1097 }
1098 }
1099
1100 /** getHashPath inherited */
1101 /** getRel inherited */
1102 /** getUrlRel inherited */
1103 /** getArchiveRel inherited */
1104 /** getArchivePath inherited */
1105 /** getThumbPath inherited */
1106 /** getArchiveUrl inherited */
1107 /** getThumbUrl inherited */
1108 /** getArchiveVirtualUrl inherited */
1109 /** getThumbVirtualUrl inherited */
1110 /** isHashed inherited */
1111
1112 /**
1113 * Upload a file and record it in the DB
1114 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1115 * @param string $comment Upload description
1116 * @param string $pageText Text to use for the new description page,
1117 * if a new description page is created
1118 * @param int|bool $flags Flags for publish()
1119 * @param array|bool $props File properties, if known. This can be used to
1120 * reduce the upload time when uploading virtual URLs for which the file
1121 * info is already known
1122 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1123 * current time
1124 * @param User|null $user User object or null to use $wgUser
1125 *
1126 * @return FileRepoStatus object. On success, the value member contains the
1127 * archive name, or an empty string if it was a new file.
1128 */
1129 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1130 $timestamp = false, $user = null
1131 ) {
1132 global $wgContLang;
1133
1134 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1135 return $this->readOnlyFatalStatus();
1136 }
1137
1138 if ( !$props ) {
1139 wfProfileIn( __METHOD__ . '-getProps' );
1140 if ( $this->repo->isVirtualUrl( $srcPath )
1141 || FileBackend::isStoragePath( $srcPath )
1142 ) {
1143 $props = $this->repo->getFileProps( $srcPath );
1144 } else {
1145 $props = FSFile::getPropsFromPath( $srcPath );
1146 }
1147 wfProfileOut( __METHOD__ . '-getProps' );
1148 }
1149
1150 $options = array();
1151 $handler = MediaHandler::getHandler( $props['mime'] );
1152 if ( $handler ) {
1153 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1154 } else {
1155 $options['headers'] = array();
1156 }
1157
1158 // Trim spaces on user supplied text
1159 $comment = trim( $comment );
1160
1161 // truncate nicely or the DB will do it for us
1162 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1163 $comment = $wgContLang->truncate( $comment, 255 );
1164 $this->lock(); // begin
1165 $status = $this->publish( $srcPath, $flags, $options );
1166
1167 if ( $status->successCount > 0 ) {
1168 # Essentially we are displacing any existing current file and saving
1169 # a new current file at the old location. If just the first succeeded,
1170 # we still need to displace the current DB entry and put in a new one.
1171 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
1172 $status->fatal( 'filenotfound', $srcPath );
1173 }
1174 }
1175
1176 $this->unlock(); // done
1177
1178 return $status;
1179 }
1180
1181 /**
1182 * Record a file upload in the upload log and the image table
1183 * @param string $oldver
1184 * @param string $desc
1185 * @param string $license
1186 * @param string $copyStatus
1187 * @param string $source
1188 * @param bool $watch
1189 * @param string|bool $timestamp
1190 * @param User|null $user User object or null to use $wgUser
1191 * @return bool
1192 */
1193 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1194 $watch = false, $timestamp = false, User $user = null ) {
1195 if ( !$user ) {
1196 global $wgUser;
1197 $user = $wgUser;
1198 }
1199
1200 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1201
1202 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1203 return false;
1204 }
1205
1206 if ( $watch ) {
1207 $user->addWatch( $this->getTitle() );
1208 }
1209
1210 return true;
1211 }
1212
1213 /**
1214 * Record a file upload in the upload log and the image table
1215 * @param string $oldver
1216 * @param string $comment
1217 * @param string $pageText
1218 * @param bool|array $props
1219 * @param string|bool $timestamp
1220 * @param null|User $user
1221 * @return bool
1222 */
1223 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1224 $user = null
1225 ) {
1226 wfProfileIn( __METHOD__ );
1227
1228 if ( is_null( $user ) ) {
1229 global $wgUser;
1230 $user = $wgUser;
1231 }
1232
1233 $dbw = $this->repo->getMasterDB();
1234 $dbw->begin( __METHOD__ );
1235
1236 if ( !$props ) {
1237 wfProfileIn( __METHOD__ . '-getProps' );
1238 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
1239 wfProfileOut( __METHOD__ . '-getProps' );
1240 }
1241
1242 if ( $timestamp === false ) {
1243 $timestamp = $dbw->timestamp();
1244 }
1245
1246 $props['description'] = $comment;
1247 $props['user'] = $user->getId();
1248 $props['user_text'] = $user->getName();
1249 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1250 $this->setProps( $props );
1251
1252 # Fail now if the file isn't there
1253 if ( !$this->fileExists ) {
1254 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1255 wfProfileOut( __METHOD__ );
1256
1257 return false;
1258 }
1259
1260 $reupload = false;
1261
1262 # Test to see if the row exists using INSERT IGNORE
1263 # This avoids race conditions by locking the row until the commit, and also
1264 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1265 $dbw->insert( 'image',
1266 array(
1267 'img_name' => $this->getName(),
1268 'img_size' => $this->size,
1269 'img_width' => intval( $this->width ),
1270 'img_height' => intval( $this->height ),
1271 'img_bits' => $this->bits,
1272 'img_media_type' => $this->media_type,
1273 'img_major_mime' => $this->major_mime,
1274 'img_minor_mime' => $this->minor_mime,
1275 'img_timestamp' => $timestamp,
1276 'img_description' => $comment,
1277 'img_user' => $user->getId(),
1278 'img_user_text' => $user->getName(),
1279 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1280 'img_sha1' => $this->sha1
1281 ),
1282 __METHOD__,
1283 'IGNORE'
1284 );
1285 if ( $dbw->affectedRows() == 0 ) {
1286 # (bug 34993) Note: $oldver can be empty here, if the previous
1287 # version of the file was broken. Allow registration of the new
1288 # version to continue anyway, because that's better than having
1289 # an image that's not fixable by user operations.
1290
1291 $reupload = true;
1292 # Collision, this is an update of a file
1293 # Insert previous contents into oldimage
1294 $dbw->insertSelect( 'oldimage', 'image',
1295 array(
1296 'oi_name' => 'img_name',
1297 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1298 'oi_size' => 'img_size',
1299 'oi_width' => 'img_width',
1300 'oi_height' => 'img_height',
1301 'oi_bits' => 'img_bits',
1302 'oi_timestamp' => 'img_timestamp',
1303 'oi_description' => 'img_description',
1304 'oi_user' => 'img_user',
1305 'oi_user_text' => 'img_user_text',
1306 'oi_metadata' => 'img_metadata',
1307 'oi_media_type' => 'img_media_type',
1308 'oi_major_mime' => 'img_major_mime',
1309 'oi_minor_mime' => 'img_minor_mime',
1310 'oi_sha1' => 'img_sha1'
1311 ),
1312 array( 'img_name' => $this->getName() ),
1313 __METHOD__
1314 );
1315
1316 # Update the current image row
1317 $dbw->update( 'image',
1318 array( /* SET */
1319 'img_size' => $this->size,
1320 'img_width' => intval( $this->width ),
1321 'img_height' => intval( $this->height ),
1322 'img_bits' => $this->bits,
1323 'img_media_type' => $this->media_type,
1324 'img_major_mime' => $this->major_mime,
1325 'img_minor_mime' => $this->minor_mime,
1326 'img_timestamp' => $timestamp,
1327 'img_description' => $comment,
1328 'img_user' => $user->getId(),
1329 'img_user_text' => $user->getName(),
1330 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1331 'img_sha1' => $this->sha1
1332 ),
1333 array( 'img_name' => $this->getName() ),
1334 __METHOD__
1335 );
1336 } else {
1337 # This is a new file, so update the image count
1338 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
1339 }
1340
1341 $descTitle = $this->getTitle();
1342 $wikiPage = new WikiFilePage( $descTitle );
1343 $wikiPage->setFile( $this );
1344
1345 # Add the log entry
1346 $action = $reupload ? 'overwrite' : 'upload';
1347
1348 $logEntry = new ManualLogEntry( 'upload', $action );
1349 $logEntry->setPerformer( $user );
1350 $logEntry->setComment( $comment );
1351 $logEntry->setTarget( $descTitle );
1352
1353 // Allow people using the api to associate log entries with the upload.
1354 // Log has a timestamp, but sometimes different from upload timestamp.
1355 $logEntry->setParameters(
1356 array(
1357 'img_sha1' => $this->sha1,
1358 'img_timestamp' => $timestamp,
1359 )
1360 );
1361 // Note we keep $logId around since during new image
1362 // creation, page doesn't exist yet, so log_page = 0
1363 // but we want it to point to the page we're making,
1364 // so we later modify the log entry.
1365 // For a similar reason, we avoid making an RC entry
1366 // now and wait until the page exists.
1367 $logId = $logEntry->insert();
1368
1369 $exists = $descTitle->exists();
1370 if ( $exists ) {
1371 // Page exists, do RC entry now (otherwise we wait for later).
1372 $logEntry->publish( $logId );
1373 }
1374 wfProfileIn( __METHOD__ . '-edit' );
1375
1376 if ( $exists ) {
1377 # Create a null revision
1378 $latest = $descTitle->getLatestRevID();
1379 $editSummary = LogFormatter::newFromEntry( $logEntry )->getPlainActionText();
1380
1381 $nullRevision = Revision::newNullRevision(
1382 $dbw,
1383 $descTitle->getArticleID(),
1384 $editSummary,
1385 false
1386 );
1387 if ( !is_null( $nullRevision ) ) {
1388 $nullRevision->insertOn( $dbw );
1389
1390 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1391 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1392 }
1393 }
1394
1395 # Commit the transaction now, in case something goes wrong later
1396 # The most important thing is that files don't get lost, especially archives
1397 # NOTE: once we have support for nested transactions, the commit may be moved
1398 # to after $wikiPage->doEdit has been called.
1399 $dbw->commit( __METHOD__ );
1400
1401 if ( $exists ) {
1402 # Invalidate the cache for the description page
1403 $descTitle->invalidateCache();
1404 $descTitle->purgeSquid();
1405 } else {
1406 # New file; create the description page.
1407 # There's already a log entry, so don't make a second RC entry
1408 # Squid and file cache for the description page are purged by doEditContent.
1409 $content = ContentHandler::makeContent( $pageText, $descTitle );
1410 $status = $wikiPage->doEditContent(
1411 $content,
1412 $comment,
1413 EDIT_NEW | EDIT_SUPPRESS_RC,
1414 false,
1415 $user
1416 );
1417
1418 $dbw->begin( __METHOD__ ); // XXX; doEdit() uses a transaction
1419 // Now that the page exists, make an RC entry.
1420 $logEntry->publish( $logId );
1421 if ( isset( $status->value['revision'] ) ) {
1422 $dbw->update( 'logging',
1423 array( 'log_page' => $status->value['revision']->getPage() ),
1424 array( 'log_id' => $logId ),
1425 __METHOD__
1426 );
1427 }
1428 $dbw->commit( __METHOD__ ); // commit before anything bad can happen
1429 }
1430
1431 wfProfileOut( __METHOD__ . '-edit' );
1432
1433 # Save to cache and purge the squid
1434 # We shall not saveToCache before the commit since otherwise
1435 # in case of a rollback there is an usable file from memcached
1436 # which in fact doesn't really exist (bug 24978)
1437 $this->saveToCache();
1438
1439 if ( $reupload ) {
1440 # Delete old thumbnails
1441 wfProfileIn( __METHOD__ . '-purge' );
1442 $this->purgeThumbnails();
1443 wfProfileOut( __METHOD__ . '-purge' );
1444
1445 # Remove the old file from the squid cache
1446 SquidUpdate::purge( array( $this->getURL() ) );
1447 }
1448
1449 # Hooks, hooks, the magic of hooks...
1450 wfProfileIn( __METHOD__ . '-hooks' );
1451 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1452 wfProfileOut( __METHOD__ . '-hooks' );
1453
1454 # Invalidate cache for all pages using this file
1455 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1456 $update->doUpdate();
1457 if ( !$reupload ) {
1458 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1459 }
1460
1461 # Invalidate cache for all pages that redirects on this page
1462 $redirs = $this->getTitle()->getRedirectsHere();
1463
1464 foreach ( $redirs as $redir ) {
1465 if ( !$reupload && $redir->getNamespace() === NS_FILE ) {
1466 LinksUpdate::queueRecursiveJobsForTable( $redir, 'imagelinks' );
1467 }
1468 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1469 $update->doUpdate();
1470 }
1471
1472 wfProfileOut( __METHOD__ );
1473
1474 return true;
1475 }
1476
1477 /**
1478 * Move or copy a file to its public location. If a file exists at the
1479 * destination, move it to an archive. Returns a FileRepoStatus object with
1480 * the archive name in the "value" member on success.
1481 *
1482 * The archive name should be passed through to recordUpload for database
1483 * registration.
1484 *
1485 * @param string $srcPath Local filesystem path to the source image
1486 * @param int $flags A bitwise combination of:
1487 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1488 * @param array $options Optional additional parameters
1489 * @return FileRepoStatus On success, the value member contains the
1490 * archive name, or an empty string if it was a new file.
1491 */
1492 function publish( $srcPath, $flags = 0, array $options = array() ) {
1493 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1494 }
1495
1496 /**
1497 * Move or copy a file to a specified location. Returns a FileRepoStatus
1498 * object with the archive name in the "value" member on success.
1499 *
1500 * The archive name should be passed through to recordUpload for database
1501 * registration.
1502 *
1503 * @param string $srcPath Local filesystem path to the source image
1504 * @param string $dstRel Target relative path
1505 * @param int $flags A bitwise combination of:
1506 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1507 * @param array $options Optional additional parameters
1508 * @return FileRepoStatus On success, the value member contains the
1509 * archive name, or an empty string if it was a new file.
1510 */
1511 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1512 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1513 return $this->readOnlyFatalStatus();
1514 }
1515
1516 $this->lock(); // begin
1517
1518 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1519 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1520 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1521 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1522
1523 if ( $status->value == 'new' ) {
1524 $status->value = '';
1525 } else {
1526 $status->value = $archiveName;
1527 }
1528
1529 $this->unlock(); // done
1530
1531 return $status;
1532 }
1533
1534 /** getLinksTo inherited */
1535 /** getExifData inherited */
1536 /** isLocal inherited */
1537 /** wasDeleted inherited */
1538
1539 /**
1540 * Move file to the new title
1541 *
1542 * Move current, old version and all thumbnails
1543 * to the new filename. Old file is deleted.
1544 *
1545 * Cache purging is done; checks for validity
1546 * and logging are caller's responsibility
1547 *
1548 * @param Title $target New file name
1549 * @return FileRepoStatus
1550 */
1551 function move( $target ) {
1552 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1553 return $this->readOnlyFatalStatus();
1554 }
1555
1556 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1557 $batch = new LocalFileMoveBatch( $this, $target );
1558
1559 $this->lock(); // begin
1560 $batch->addCurrent();
1561 $archiveNames = $batch->addOlds();
1562 $status = $batch->execute();
1563 $this->unlock(); // done
1564
1565 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1566
1567 // Purge the source and target files...
1568 $oldTitleFile = wfLocalFile( $this->title );
1569 $newTitleFile = wfLocalFile( $target );
1570 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1571 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1572 $this->getRepo()->getMasterDB()->onTransactionIdle(
1573 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1574 $oldTitleFile->purgeEverything();
1575 foreach ( $archiveNames as $archiveName ) {
1576 $oldTitleFile->purgeOldThumbnails( $archiveName );
1577 }
1578 $newTitleFile->purgeEverything();
1579 }
1580 );
1581
1582 if ( $status->isOK() ) {
1583 // Now switch the object
1584 $this->title = $target;
1585 // Force regeneration of the name and hashpath
1586 unset( $this->name );
1587 unset( $this->hashPath );
1588 }
1589
1590 return $status;
1591 }
1592
1593 /**
1594 * Delete all versions of the file.
1595 *
1596 * Moves the files into an archive directory (or deletes them)
1597 * and removes the database rows.
1598 *
1599 * Cache purging is done; logging is caller's responsibility.
1600 *
1601 * @param string $reason
1602 * @param bool $suppress
1603 * @return FileRepoStatus
1604 */
1605 function delete( $reason, $suppress = false ) {
1606 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1607 return $this->readOnlyFatalStatus();
1608 }
1609
1610 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1611
1612 $this->lock(); // begin
1613 $batch->addCurrent();
1614 # Get old version relative paths
1615 $archiveNames = $batch->addOlds();
1616 $status = $batch->execute();
1617 $this->unlock(); // done
1618
1619 if ( $status->isOK() ) {
1620 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1621 }
1622
1623 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1624 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1625 $file = $this;
1626 $this->getRepo()->getMasterDB()->onTransactionIdle(
1627 function () use ( $file, $archiveNames ) {
1628 global $wgUseSquid;
1629
1630 $file->purgeEverything();
1631 foreach ( $archiveNames as $archiveName ) {
1632 $file->purgeOldThumbnails( $archiveName );
1633 }
1634
1635 if ( $wgUseSquid ) {
1636 // Purge the squid
1637 $purgeUrls = array();
1638 foreach ( $archiveNames as $archiveName ) {
1639 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1640 }
1641 SquidUpdate::purge( $purgeUrls );
1642 }
1643 }
1644 );
1645
1646 return $status;
1647 }
1648
1649 /**
1650 * Delete an old version of the file.
1651 *
1652 * Moves the file into an archive directory (or deletes it)
1653 * and removes the database row.
1654 *
1655 * Cache purging is done; logging is caller's responsibility.
1656 *
1657 * @param string $archiveName
1658 * @param string $reason
1659 * @param bool $suppress
1660 * @throws MWException Exception on database or file store failure
1661 * @return FileRepoStatus
1662 */
1663 function deleteOld( $archiveName, $reason, $suppress = false ) {
1664 global $wgUseSquid;
1665 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1666 return $this->readOnlyFatalStatus();
1667 }
1668
1669 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1670
1671 $this->lock(); // begin
1672 $batch->addOld( $archiveName );
1673 $status = $batch->execute();
1674 $this->unlock(); // done
1675
1676 $this->purgeOldThumbnails( $archiveName );
1677 if ( $status->isOK() ) {
1678 $this->purgeDescription();
1679 $this->purgeHistory();
1680 }
1681
1682 if ( $wgUseSquid ) {
1683 // Purge the squid
1684 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1685 }
1686
1687 return $status;
1688 }
1689
1690 /**
1691 * Restore all or specified deleted revisions to the given file.
1692 * Permissions and logging are left to the caller.
1693 *
1694 * May throw database exceptions on error.
1695 *
1696 * @param array $versions set of record ids of deleted items to restore,
1697 * or empty to restore all revisions.
1698 * @param bool $unsuppress
1699 * @return FileRepoStatus
1700 */
1701 function restore( $versions = array(), $unsuppress = false ) {
1702 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1703 return $this->readOnlyFatalStatus();
1704 }
1705
1706 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1707
1708 $this->lock(); // begin
1709 if ( !$versions ) {
1710 $batch->addAll();
1711 } else {
1712 $batch->addIds( $versions );
1713 }
1714 $status = $batch->execute();
1715 if ( $status->isGood() ) {
1716 $cleanupStatus = $batch->cleanup();
1717 $cleanupStatus->successCount = 0;
1718 $cleanupStatus->failCount = 0;
1719 $status->merge( $cleanupStatus );
1720 }
1721 $this->unlock(); // done
1722
1723 return $status;
1724 }
1725
1726 /** isMultipage inherited */
1727 /** pageCount inherited */
1728 /** scaleHeight inherited */
1729 /** getImageSize inherited */
1730
1731 /**
1732 * Get the URL of the file description page.
1733 * @return string
1734 */
1735 function getDescriptionUrl() {
1736 return $this->title->getLocalURL();
1737 }
1738
1739 /**
1740 * Get the HTML text of the description page
1741 * This is not used by ImagePage for local files, since (among other things)
1742 * it skips the parser cache.
1743 *
1744 * @param Language $lang What language to get description in (Optional)
1745 * @return bool|mixed
1746 */
1747 function getDescriptionText( $lang = null ) {
1748 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1749 if ( !$revision ) {
1750 return false;
1751 }
1752 $content = $revision->getContent();
1753 if ( !$content ) {
1754 return false;
1755 }
1756 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1757
1758 return $pout->getText();
1759 }
1760
1761 /**
1762 * @param int $audience
1763 * @param User $user
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 * @throws MWException
1828 * @return bool True if the image exists, false otherwise
1829 */
1830 function lock() {
1831 $dbw = $this->repo->getMasterDB();
1832
1833 if ( !$this->locked ) {
1834 if ( !$dbw->trxLevel() ) {
1835 $dbw->begin( __METHOD__ );
1836 $this->lockedOwnTrx = true;
1837 }
1838 $this->locked++;
1839 // Bug 54736: use simple lock to handle when the file does not exist.
1840 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1841 $cache = wfGetMainCache();
1842 $key = $this->getCacheKey();
1843 if ( !$cache->lock( $key, 60 ) ) {
1844 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1845 }
1846 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1847 $cache->unlock( $key ); // release on commit
1848 } );
1849 }
1850
1851 return $dbw->selectField( 'image', '1',
1852 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1853 }
1854
1855 /**
1856 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1857 * the transaction and thereby releases the image lock.
1858 */
1859 function unlock() {
1860 if ( $this->locked ) {
1861 --$this->locked;
1862 if ( !$this->locked && $this->lockedOwnTrx ) {
1863 $dbw = $this->repo->getMasterDB();
1864 $dbw->commit( __METHOD__ );
1865 $this->lockedOwnTrx = false;
1866 }
1867 }
1868 }
1869
1870 /**
1871 * Roll back the DB transaction and mark the image unlocked
1872 */
1873 function unlockAndRollback() {
1874 $this->locked = false;
1875 $dbw = $this->repo->getMasterDB();
1876 $dbw->rollback( __METHOD__ );
1877 $this->lockedOwnTrx = false;
1878 }
1879
1880 /**
1881 * @return Status
1882 */
1883 protected function readOnlyFatalStatus() {
1884 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1885 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1886 }
1887 } // LocalFile class
1888
1889 # ------------------------------------------------------------------------------
1890
1891 /**
1892 * Helper class for file deletion
1893 * @ingroup FileAbstraction
1894 */
1895 class LocalFileDeleteBatch {
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 string $reason
1920 * @param bool $suppress
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 string $oldName
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 bool $unsuppress
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 array $triplets
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 array $batch
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 /** @var DatabaseBase */
2647 protected $db;
2648
2649 /**
2650 * @param File $file
2651 * @param Title $target
2652 */
2653 function __construct( File $file, Title $target ) {
2654 $this->file = $file;
2655 $this->target = $target;
2656 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2657 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2658 $this->oldName = $this->file->getName();
2659 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2660 $this->oldRel = $this->oldHash . $this->oldName;
2661 $this->newRel = $this->newHash . $this->newName;
2662 $this->db = $file->getRepo()->getMasterDb();
2663 }
2664
2665 /**
2666 * Add the current image to the batch
2667 */
2668 function addCurrent() {
2669 $this->cur = array( $this->oldRel, $this->newRel );
2670 }
2671
2672 /**
2673 * Add the old versions of the image to the batch
2674 * @return array List of archive names from old versions
2675 */
2676 function addOlds() {
2677 $archiveBase = 'archive';
2678 $this->olds = array();
2679 $this->oldCount = 0;
2680 $archiveNames = array();
2681
2682 $result = $this->db->select( 'oldimage',
2683 array( 'oi_archive_name', 'oi_deleted' ),
2684 array( 'oi_name' => $this->oldName ),
2685 __METHOD__
2686 );
2687
2688 foreach ( $result as $row ) {
2689 $archiveNames[] = $row->oi_archive_name;
2690 $oldName = $row->oi_archive_name;
2691 $bits = explode( '!', $oldName, 2 );
2692
2693 if ( count( $bits ) != 2 ) {
2694 wfDebug( "Old file name missing !: '$oldName' \n" );
2695 continue;
2696 }
2697
2698 list( $timestamp, $filename ) = $bits;
2699
2700 if ( $this->oldName != $filename ) {
2701 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2702 continue;
2703 }
2704
2705 $this->oldCount++;
2706
2707 // Do we want to add those to oldCount?
2708 if ( $row->oi_deleted & File::DELETED_FILE ) {
2709 continue;
2710 }
2711
2712 $this->olds[] = array(
2713 "{$archiveBase}/{$this->oldHash}{$oldName}",
2714 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2715 );
2716 }
2717
2718 return $archiveNames;
2719 }
2720
2721 /**
2722 * Perform the move.
2723 * @return FileRepoStatus
2724 */
2725 function execute() {
2726 $repo = $this->file->repo;
2727 $status = $repo->newGood();
2728
2729 $triplets = $this->getMoveTriplets();
2730 $triplets = $this->removeNonexistentFiles( $triplets );
2731
2732 $this->file->lock(); // begin
2733 // Rename the file versions metadata in the DB.
2734 // This implicitly locks the destination file, which avoids race conditions.
2735 // If we moved the files from A -> C before DB updates, another process could
2736 // move files from B -> C at this point, causing storeBatch() to fail and thus
2737 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2738 $statusDb = $this->doDBUpdates();
2739 if ( !$statusDb->isGood() ) {
2740 $this->file->unlockAndRollback();
2741 $statusDb->ok = false;
2742
2743 return $statusDb;
2744 }
2745 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2746 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2747
2748 // Copy the files into their new location.
2749 // If a prior process fataled copying or cleaning up files we tolerate any
2750 // of the existing files if they are identical to the ones being stored.
2751 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2752 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2753 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2754 if ( !$statusMove->isGood() ) {
2755 // Delete any files copied over (while the destination is still locked)
2756 $this->cleanupTarget( $triplets );
2757 $this->file->unlockAndRollback(); // unlocks the destination
2758 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2759 $statusMove->ok = false;
2760
2761 return $statusMove;
2762 }
2763 $this->file->unlock(); // done
2764
2765 // Everything went ok, remove the source files
2766 $this->cleanupSource( $triplets );
2767
2768 $status->merge( $statusDb );
2769 $status->merge( $statusMove );
2770
2771 return $status;
2772 }
2773
2774 /**
2775 * Do the database updates and return a new FileRepoStatus indicating how
2776 * many rows where updated.
2777 *
2778 * @return FileRepoStatus
2779 */
2780 function doDBUpdates() {
2781 $repo = $this->file->repo;
2782 $status = $repo->newGood();
2783 $dbw = $this->db;
2784
2785 // Update current image
2786 $dbw->update(
2787 'image',
2788 array( 'img_name' => $this->newName ),
2789 array( 'img_name' => $this->oldName ),
2790 __METHOD__
2791 );
2792
2793 if ( $dbw->affectedRows() ) {
2794 $status->successCount++;
2795 } else {
2796 $status->failCount++;
2797 $status->fatal( 'imageinvalidfilename' );
2798
2799 return $status;
2800 }
2801
2802 // Update old images
2803 $dbw->update(
2804 'oldimage',
2805 array(
2806 'oi_name' => $this->newName,
2807 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2808 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2809 ),
2810 array( 'oi_name' => $this->oldName ),
2811 __METHOD__
2812 );
2813
2814 $affected = $dbw->affectedRows();
2815 $total = $this->oldCount;
2816 $status->successCount += $affected;
2817 // Bug 34934: $total is based on files that actually exist.
2818 // There may be more DB rows than such files, in which case $affected
2819 // can be greater than $total. We use max() to avoid negatives here.
2820 $status->failCount += max( 0, $total - $affected );
2821 if ( $status->failCount ) {
2822 $status->error( 'imageinvalidfilename' );
2823 }
2824
2825 return $status;
2826 }
2827
2828 /**
2829 * Generate triplets for FileRepo::storeBatch().
2830 * @return array
2831 */
2832 function getMoveTriplets() {
2833 $moves = array_merge( array( $this->cur ), $this->olds );
2834 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2835
2836 foreach ( $moves as $move ) {
2837 // $move: (oldRelativePath, newRelativePath)
2838 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2839 $triplets[] = array( $srcUrl, 'public', $move[1] );
2840 wfDebugLog(
2841 'imagemove',
2842 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2843 );
2844 }
2845
2846 return $triplets;
2847 }
2848
2849 /**
2850 * Removes non-existent files from move batch.
2851 * @param array $triplets
2852 * @return array
2853 */
2854 function removeNonexistentFiles( $triplets ) {
2855 $files = array();
2856
2857 foreach ( $triplets as $file ) {
2858 $files[$file[0]] = $file[0];
2859 }
2860
2861 $result = $this->file->repo->fileExistsBatch( $files );
2862 $filteredTriplets = array();
2863
2864 foreach ( $triplets as $file ) {
2865 if ( $result[$file[0]] ) {
2866 $filteredTriplets[] = $file;
2867 } else {
2868 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2869 }
2870 }
2871
2872 return $filteredTriplets;
2873 }
2874
2875 /**
2876 * Cleanup a partially moved array of triplets by deleting the target
2877 * files. Called if something went wrong half way.
2878 */
2879 function cleanupTarget( $triplets ) {
2880 // Create dest pairs from the triplets
2881 $pairs = array();
2882 foreach ( $triplets as $triplet ) {
2883 // $triplet: (old source virtual URL, dst zone, dest rel)
2884 $pairs[] = array( $triplet[1], $triplet[2] );
2885 }
2886
2887 $this->file->repo->cleanupBatch( $pairs );
2888 }
2889
2890 /**
2891 * Cleanup a fully moved array of triplets by deleting the source files.
2892 * Called at the end of the move process if everything else went ok.
2893 */
2894 function cleanupSource( $triplets ) {
2895 // Create source file names from the triplets
2896 $files = array();
2897 foreach ( $triplets as $triplet ) {
2898 $files[] = $triplet[0];
2899 }
2900
2901 $this->file->repo->cleanupBatch( $files );
2902 }
2903 }