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