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