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