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