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