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