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