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