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