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