(bug 19195) Make user IDs more readily available with the API
[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->cleanDir( $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 $this->lock(); // begin
1235
1236 $batch = new LocalFileMoveBatch( $this, $target );
1237 $batch->addCurrent();
1238 $batch->addOlds();
1239
1240 $status = $batch->execute();
1241 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1242
1243 $this->purgeEverything();
1244 $this->unlock(); // done
1245
1246 if ( $status->isOk() ) {
1247 // Now switch the object
1248 $this->title = $target;
1249 // Force regeneration of the name and hashpath
1250 unset( $this->name );
1251 unset( $this->hashPath );
1252 // Purge the new image
1253 $this->purgeEverything();
1254 }
1255
1256 return $status;
1257 }
1258
1259 /**
1260 * Delete all versions of the file.
1261 *
1262 * Moves the files into an archive directory (or deletes them)
1263 * and removes the database rows.
1264 *
1265 * Cache purging is done; logging is caller's responsibility.
1266 *
1267 * @param $reason
1268 * @param $suppress
1269 * @return FileRepoStatus object.
1270 */
1271 function delete( $reason, $suppress = false ) {
1272 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1273 return $this->readOnlyFatalStatus();
1274 }
1275
1276 $this->lock(); // begin
1277
1278 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1279 $batch->addCurrent();
1280
1281 # Get old version relative paths
1282 $dbw = $this->repo->getMasterDB();
1283 $result = $dbw->select( 'oldimage',
1284 array( 'oi_archive_name' ),
1285 array( 'oi_name' => $this->getName() ) );
1286 foreach ( $result as $row ) {
1287 $batch->addOld( $row->oi_archive_name );
1288 $this->purgeOldThumbnails( $row->oi_archive_name );
1289 }
1290 $status = $batch->execute();
1291
1292 if ( $status->isOK() ) {
1293 // Update site_stats
1294 $site_stats = $dbw->tableName( 'site_stats' );
1295 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1296 $this->purgeEverything();
1297 }
1298
1299 $this->unlock(); // done
1300
1301 return $status;
1302 }
1303
1304 /**
1305 * Delete an old version of the file.
1306 *
1307 * Moves the file into an archive directory (or deletes it)
1308 * and removes the database row.
1309 *
1310 * Cache purging is done; logging is caller's responsibility.
1311 *
1312 * @param $archiveName String
1313 * @param $reason String
1314 * @param $suppress Boolean
1315 * @throws MWException or FSException on database or file store failure
1316 * @return FileRepoStatus object.
1317 */
1318 function deleteOld( $archiveName, $reason, $suppress = false ) {
1319 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1320 return $this->readOnlyFatalStatus();
1321 }
1322
1323 $this->lock(); // begin
1324
1325 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1326 $batch->addOld( $archiveName );
1327 $this->purgeOldThumbnails( $archiveName );
1328 $status = $batch->execute();
1329
1330 $this->unlock(); // done
1331
1332 if ( $status->isOK() ) {
1333 $this->purgeDescription();
1334 $this->purgeHistory();
1335 }
1336
1337 return $status;
1338 }
1339
1340 /**
1341 * Restore all or specified deleted revisions to the given file.
1342 * Permissions and logging are left to the caller.
1343 *
1344 * May throw database exceptions on error.
1345 *
1346 * @param $versions array set of record ids of deleted items to restore,
1347 * or empty to restore all revisions.
1348 * @param $unsuppress Boolean
1349 * @return FileRepoStatus
1350 */
1351 function restore( $versions = array(), $unsuppress = false ) {
1352 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1353 return $this->readOnlyFatalStatus();
1354 }
1355
1356 $this->lock(); // begin
1357
1358 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1359
1360 if ( !$versions ) {
1361 $batch->addAll();
1362 } else {
1363 $batch->addIds( $versions );
1364 }
1365
1366 $status = $batch->execute();
1367
1368 if ( $status->isGood() ) {
1369 $cleanupStatus = $batch->cleanup();
1370 $cleanupStatus->successCount = 0;
1371 $cleanupStatus->failCount = 0;
1372 $status->merge( $cleanupStatus );
1373 }
1374
1375 $this->unlock(); // done
1376
1377 return $status;
1378 }
1379
1380 /** isMultipage inherited */
1381 /** pageCount inherited */
1382 /** scaleHeight inherited */
1383 /** getImageSize inherited */
1384
1385 /**
1386 * Get the URL of the file description page.
1387 * @return String
1388 */
1389 function getDescriptionUrl() {
1390 return $this->title->getLocalUrl();
1391 }
1392
1393 /**
1394 * Get the HTML text of the description page
1395 * This is not used by ImagePage for local files, since (among other things)
1396 * it skips the parser cache.
1397 * @return bool|mixed
1398 */
1399 function getDescriptionText() {
1400 global $wgParser;
1401 $revision = Revision::newFromTitle( $this->title );
1402 if ( !$revision ) return false;
1403 $text = $revision->getText();
1404 if ( !$text ) return false;
1405 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1406 return $pout->getText();
1407 }
1408
1409 function getDescription() {
1410 $this->load();
1411 return $this->description;
1412 }
1413
1414 function getTimestamp() {
1415 $this->load();
1416 return $this->timestamp;
1417 }
1418
1419 function getSha1() {
1420 $this->load();
1421 // Initialise now if necessary
1422 if ( $this->sha1 == '' && $this->fileExists ) {
1423 $this->lock(); // begin
1424
1425 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1426 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1427 $dbw = $this->repo->getMasterDB();
1428 $dbw->update( 'image',
1429 array( 'img_sha1' => $this->sha1 ),
1430 array( 'img_name' => $this->getName() ),
1431 __METHOD__ );
1432 $this->saveToCache();
1433 }
1434
1435 $this->unlock(); // done
1436 }
1437
1438 return $this->sha1;
1439 }
1440
1441 function isCacheable() {
1442 $this->load();
1443 return strlen( $this->metadata ) <= self::CACHE_FIELD_MAX_LEN; // avoid OOMs
1444 }
1445
1446 /**
1447 * Start a transaction and lock the image for update
1448 * Increments a reference counter if the lock is already held
1449 * @return boolean True if the image exists, false otherwise
1450 */
1451 function lock() {
1452 $dbw = $this->repo->getMasterDB();
1453
1454 if ( !$this->locked ) {
1455 $dbw->begin( __METHOD__ );
1456 $this->locked++;
1457 }
1458
1459 return $dbw->selectField( 'image', '1',
1460 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1461 }
1462
1463 /**
1464 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1465 * the transaction and thereby releases the image lock.
1466 */
1467 function unlock() {
1468 if ( $this->locked ) {
1469 --$this->locked;
1470 if ( !$this->locked ) {
1471 $dbw = $this->repo->getMasterDB();
1472 $dbw->commit( __METHOD__ );
1473 }
1474 }
1475 }
1476
1477 /**
1478 * Roll back the DB transaction and mark the image unlocked
1479 */
1480 function unlockAndRollback() {
1481 $this->locked = false;
1482 $dbw = $this->repo->getMasterDB();
1483 $dbw->rollback( __METHOD__ );
1484 }
1485
1486 /**
1487 * @return Status
1488 */
1489 protected function readOnlyFatalStatus() {
1490 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1491 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1492 }
1493 } // LocalFile class
1494
1495 # ------------------------------------------------------------------------------
1496
1497 /**
1498 * Helper class for file deletion
1499 * @ingroup FileAbstraction
1500 */
1501 class LocalFileDeleteBatch {
1502
1503 /**
1504 * @var LocalFile
1505 */
1506 var $file;
1507
1508 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1509 var $status;
1510
1511 function __construct( File $file, $reason = '', $suppress = false ) {
1512 $this->file = $file;
1513 $this->reason = $reason;
1514 $this->suppress = $suppress;
1515 $this->status = $file->repo->newGood();
1516 }
1517
1518 function addCurrent() {
1519 $this->srcRels['.'] = $this->file->getRel();
1520 }
1521
1522 function addOld( $oldName ) {
1523 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1524 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1525 }
1526
1527 function getOldRels() {
1528 if ( !isset( $this->srcRels['.'] ) ) {
1529 $oldRels =& $this->srcRels;
1530 $deleteCurrent = false;
1531 } else {
1532 $oldRels = $this->srcRels;
1533 unset( $oldRels['.'] );
1534 $deleteCurrent = true;
1535 }
1536
1537 return array( $oldRels, $deleteCurrent );
1538 }
1539
1540 protected function getHashes() {
1541 $hashes = array();
1542 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1543
1544 if ( $deleteCurrent ) {
1545 $hashes['.'] = $this->file->getSha1();
1546 }
1547
1548 if ( count( $oldRels ) ) {
1549 $dbw = $this->file->repo->getMasterDB();
1550 $res = $dbw->select(
1551 'oldimage',
1552 array( 'oi_archive_name', 'oi_sha1' ),
1553 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1554 __METHOD__
1555 );
1556
1557 foreach ( $res as $row ) {
1558 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1559 // Get the hash from the file
1560 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1561 $props = $this->file->repo->getFileProps( $oldUrl );
1562
1563 if ( $props['fileExists'] ) {
1564 // Upgrade the oldimage row
1565 $dbw->update( 'oldimage',
1566 array( 'oi_sha1' => $props['sha1'] ),
1567 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1568 __METHOD__ );
1569 $hashes[$row->oi_archive_name] = $props['sha1'];
1570 } else {
1571 $hashes[$row->oi_archive_name] = false;
1572 }
1573 } else {
1574 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1575 }
1576 }
1577 }
1578
1579 $missing = array_diff_key( $this->srcRels, $hashes );
1580
1581 foreach ( $missing as $name => $rel ) {
1582 $this->status->error( 'filedelete-old-unregistered', $name );
1583 }
1584
1585 foreach ( $hashes as $name => $hash ) {
1586 if ( !$hash ) {
1587 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1588 unset( $hashes[$name] );
1589 }
1590 }
1591
1592 return $hashes;
1593 }
1594
1595 function doDBInserts() {
1596 global $wgUser;
1597
1598 $dbw = $this->file->repo->getMasterDB();
1599 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1600 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1601 $encReason = $dbw->addQuotes( $this->reason );
1602 $encGroup = $dbw->addQuotes( 'deleted' );
1603 $ext = $this->file->getExtension();
1604 $dotExt = $ext === '' ? '' : ".$ext";
1605 $encExt = $dbw->addQuotes( $dotExt );
1606 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1607
1608 // Bitfields to further suppress the content
1609 if ( $this->suppress ) {
1610 $bitfield = 0;
1611 // This should be 15...
1612 $bitfield |= Revision::DELETED_TEXT;
1613 $bitfield |= Revision::DELETED_COMMENT;
1614 $bitfield |= Revision::DELETED_USER;
1615 $bitfield |= Revision::DELETED_RESTRICTED;
1616 } else {
1617 $bitfield = 'oi_deleted';
1618 }
1619
1620 if ( $deleteCurrent ) {
1621 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1622 $where = array( 'img_name' => $this->file->getName() );
1623 $dbw->insertSelect( 'filearchive', 'image',
1624 array(
1625 'fa_storage_group' => $encGroup,
1626 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1627 'fa_deleted_user' => $encUserId,
1628 'fa_deleted_timestamp' => $encTimestamp,
1629 'fa_deleted_reason' => $encReason,
1630 'fa_deleted' => $this->suppress ? $bitfield : 0,
1631
1632 'fa_name' => 'img_name',
1633 'fa_archive_name' => 'NULL',
1634 'fa_size' => 'img_size',
1635 'fa_width' => 'img_width',
1636 'fa_height' => 'img_height',
1637 'fa_metadata' => 'img_metadata',
1638 'fa_bits' => 'img_bits',
1639 'fa_media_type' => 'img_media_type',
1640 'fa_major_mime' => 'img_major_mime',
1641 'fa_minor_mime' => 'img_minor_mime',
1642 'fa_description' => 'img_description',
1643 'fa_user' => 'img_user',
1644 'fa_user_text' => 'img_user_text',
1645 'fa_timestamp' => 'img_timestamp'
1646 ), $where, __METHOD__ );
1647 }
1648
1649 if ( count( $oldRels ) ) {
1650 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1651 $where = array(
1652 'oi_name' => $this->file->getName(),
1653 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1654 $dbw->insertSelect( 'filearchive', 'oldimage',
1655 array(
1656 'fa_storage_group' => $encGroup,
1657 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1658 'fa_deleted_user' => $encUserId,
1659 'fa_deleted_timestamp' => $encTimestamp,
1660 'fa_deleted_reason' => $encReason,
1661 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1662
1663 'fa_name' => 'oi_name',
1664 'fa_archive_name' => 'oi_archive_name',
1665 'fa_size' => 'oi_size',
1666 'fa_width' => 'oi_width',
1667 'fa_height' => 'oi_height',
1668 'fa_metadata' => 'oi_metadata',
1669 'fa_bits' => 'oi_bits',
1670 'fa_media_type' => 'oi_media_type',
1671 'fa_major_mime' => 'oi_major_mime',
1672 'fa_minor_mime' => 'oi_minor_mime',
1673 'fa_description' => 'oi_description',
1674 'fa_user' => 'oi_user',
1675 'fa_user_text' => 'oi_user_text',
1676 'fa_timestamp' => 'oi_timestamp',
1677 ), $where, __METHOD__ );
1678 }
1679 }
1680
1681 function doDBDeletes() {
1682 $dbw = $this->file->repo->getMasterDB();
1683 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1684
1685 if ( count( $oldRels ) ) {
1686 $dbw->delete( 'oldimage',
1687 array(
1688 'oi_name' => $this->file->getName(),
1689 'oi_archive_name' => array_keys( $oldRels )
1690 ), __METHOD__ );
1691 }
1692
1693 if ( $deleteCurrent ) {
1694 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1695 }
1696 }
1697
1698 /**
1699 * Run the transaction
1700 * @return FileRepoStatus
1701 */
1702 function execute() {
1703 global $wgUseSquid;
1704 wfProfileIn( __METHOD__ );
1705
1706 $this->file->lock();
1707 // Leave private files alone
1708 $privateFiles = array();
1709 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1710 $dbw = $this->file->repo->getMasterDB();
1711
1712 if ( !empty( $oldRels ) ) {
1713 $res = $dbw->select( 'oldimage',
1714 array( 'oi_archive_name' ),
1715 array( 'oi_name' => $this->file->getName(),
1716 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1717 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1718 __METHOD__ );
1719
1720 foreach ( $res as $row ) {
1721 $privateFiles[$row->oi_archive_name] = 1;
1722 }
1723 }
1724 // Prepare deletion batch
1725 $hashes = $this->getHashes();
1726 $this->deletionBatch = array();
1727 $ext = $this->file->getExtension();
1728 $dotExt = $ext === '' ? '' : ".$ext";
1729
1730 foreach ( $this->srcRels as $name => $srcRel ) {
1731 // Skip files that have no hash (missing source).
1732 // Keep private files where they are.
1733 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1734 $hash = $hashes[$name];
1735 $key = $hash . $dotExt;
1736 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1737 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1738 }
1739 }
1740
1741 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1742 // We acquire this lock by running the inserts now, before the file operations.
1743 //
1744 // This potentially has poor lock contention characteristics -- an alternative
1745 // scheme would be to insert stub filearchive entries with no fa_name and commit
1746 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1747 $this->doDBInserts();
1748
1749 // Removes non-existent file from the batch, so we don't get errors.
1750 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1751
1752 // Execute the file deletion batch
1753 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1754
1755 if ( !$status->isGood() ) {
1756 $this->status->merge( $status );
1757 }
1758
1759 if ( !$this->status->isOK() ) {
1760 // Critical file deletion error
1761 // Roll back inserts, release lock and abort
1762 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1763 $this->file->unlockAndRollback();
1764 wfProfileOut( __METHOD__ );
1765 return $this->status;
1766 }
1767
1768 // Purge squid
1769 if ( $wgUseSquid ) {
1770 $urls = array();
1771
1772 foreach ( $this->srcRels as $srcRel ) {
1773 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1774 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1775 }
1776 SquidUpdate::purge( $urls );
1777 }
1778
1779 // Delete image/oldimage rows
1780 $this->doDBDeletes();
1781
1782 // Commit and return
1783 $this->file->unlock();
1784 wfProfileOut( __METHOD__ );
1785
1786 return $this->status;
1787 }
1788
1789 /**
1790 * Removes non-existent files from a deletion batch.
1791 * @return array
1792 */
1793 function removeNonexistentFiles( $batch ) {
1794 $files = $newBatch = array();
1795
1796 foreach ( $batch as $batchItem ) {
1797 list( $src, $dest ) = $batchItem;
1798 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1799 }
1800
1801 $result = $this->file->repo->fileExistsBatch( $files );
1802
1803 foreach ( $batch as $batchItem ) {
1804 if ( $result[$batchItem[0]] ) {
1805 $newBatch[] = $batchItem;
1806 }
1807 }
1808
1809 return $newBatch;
1810 }
1811 }
1812
1813 # ------------------------------------------------------------------------------
1814
1815 /**
1816 * Helper class for file undeletion
1817 * @ingroup FileAbstraction
1818 */
1819 class LocalFileRestoreBatch {
1820 /**
1821 * @var LocalFile
1822 */
1823 var $file;
1824
1825 var $cleanupBatch, $ids, $all, $unsuppress = false;
1826
1827 function __construct( File $file, $unsuppress = false ) {
1828 $this->file = $file;
1829 $this->cleanupBatch = $this->ids = array();
1830 $this->ids = array();
1831 $this->unsuppress = $unsuppress;
1832 }
1833
1834 /**
1835 * Add a file by ID
1836 */
1837 function addId( $fa_id ) {
1838 $this->ids[] = $fa_id;
1839 }
1840
1841 /**
1842 * Add a whole lot of files by ID
1843 */
1844 function addIds( $ids ) {
1845 $this->ids = array_merge( $this->ids, $ids );
1846 }
1847
1848 /**
1849 * Add all revisions of the file
1850 */
1851 function addAll() {
1852 $this->all = true;
1853 }
1854
1855 /**
1856 * Run the transaction, except the cleanup batch.
1857 * The cleanup batch should be run in a separate transaction, because it locks different
1858 * rows and there's no need to keep the image row locked while it's acquiring those locks
1859 * The caller may have its own transaction open.
1860 * So we save the batch and let the caller call cleanup()
1861 * @return FileRepoStatus
1862 */
1863 function execute() {
1864 global $wgLang;
1865
1866 if ( !$this->all && !$this->ids ) {
1867 // Do nothing
1868 return $this->file->repo->newGood();
1869 }
1870
1871 $exists = $this->file->lock();
1872 $dbw = $this->file->repo->getMasterDB();
1873 $status = $this->file->repo->newGood();
1874
1875 // Fetch all or selected archived revisions for the file,
1876 // sorted from the most recent to the oldest.
1877 $conditions = array( 'fa_name' => $this->file->getName() );
1878
1879 if ( !$this->all ) {
1880 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1881 }
1882
1883 $result = $dbw->select( 'filearchive', '*',
1884 $conditions,
1885 __METHOD__,
1886 array( 'ORDER BY' => 'fa_timestamp DESC' )
1887 );
1888
1889 $idsPresent = array();
1890 $storeBatch = array();
1891 $insertBatch = array();
1892 $insertCurrent = false;
1893 $deleteIds = array();
1894 $first = true;
1895 $archiveNames = array();
1896
1897 foreach ( $result as $row ) {
1898 $idsPresent[] = $row->fa_id;
1899
1900 if ( $row->fa_name != $this->file->getName() ) {
1901 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1902 $status->failCount++;
1903 continue;
1904 }
1905
1906 if ( $row->fa_storage_key == '' ) {
1907 // Revision was missing pre-deletion
1908 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1909 $status->failCount++;
1910 continue;
1911 }
1912
1913 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1914 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1915
1916 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1917
1918 # Fix leading zero
1919 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1920 $sha1 = substr( $sha1, 1 );
1921 }
1922
1923 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1924 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1925 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1926 || is_null( $row->fa_metadata ) ) {
1927 // Refresh our metadata
1928 // Required for a new current revision; nice for older ones too. :)
1929 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1930 } else {
1931 $props = array(
1932 'minor_mime' => $row->fa_minor_mime,
1933 'major_mime' => $row->fa_major_mime,
1934 'media_type' => $row->fa_media_type,
1935 'metadata' => $row->fa_metadata
1936 );
1937 }
1938
1939 if ( $first && !$exists ) {
1940 // This revision will be published as the new current version
1941 $destRel = $this->file->getRel();
1942 $insertCurrent = array(
1943 'img_name' => $row->fa_name,
1944 'img_size' => $row->fa_size,
1945 'img_width' => $row->fa_width,
1946 'img_height' => $row->fa_height,
1947 'img_metadata' => $props['metadata'],
1948 'img_bits' => $row->fa_bits,
1949 'img_media_type' => $props['media_type'],
1950 'img_major_mime' => $props['major_mime'],
1951 'img_minor_mime' => $props['minor_mime'],
1952 'img_description' => $row->fa_description,
1953 'img_user' => $row->fa_user,
1954 'img_user_text' => $row->fa_user_text,
1955 'img_timestamp' => $row->fa_timestamp,
1956 'img_sha1' => $sha1
1957 );
1958
1959 // The live (current) version cannot be hidden!
1960 if ( !$this->unsuppress && $row->fa_deleted ) {
1961 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1962 $this->cleanupBatch[] = $row->fa_storage_key;
1963 }
1964 } else {
1965 $archiveName = $row->fa_archive_name;
1966
1967 if ( $archiveName == '' ) {
1968 // This was originally a current version; we
1969 // have to devise a new archive name for it.
1970 // Format is <timestamp of archiving>!<name>
1971 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1972
1973 do {
1974 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1975 $timestamp++;
1976 } while ( isset( $archiveNames[$archiveName] ) );
1977 }
1978
1979 $archiveNames[$archiveName] = true;
1980 $destRel = $this->file->getArchiveRel( $archiveName );
1981 $insertBatch[] = array(
1982 'oi_name' => $row->fa_name,
1983 'oi_archive_name' => $archiveName,
1984 'oi_size' => $row->fa_size,
1985 'oi_width' => $row->fa_width,
1986 'oi_height' => $row->fa_height,
1987 'oi_bits' => $row->fa_bits,
1988 'oi_description' => $row->fa_description,
1989 'oi_user' => $row->fa_user,
1990 'oi_user_text' => $row->fa_user_text,
1991 'oi_timestamp' => $row->fa_timestamp,
1992 'oi_metadata' => $props['metadata'],
1993 'oi_media_type' => $props['media_type'],
1994 'oi_major_mime' => $props['major_mime'],
1995 'oi_minor_mime' => $props['minor_mime'],
1996 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1997 'oi_sha1' => $sha1 );
1998 }
1999
2000 $deleteIds[] = $row->fa_id;
2001
2002 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2003 // private files can stay where they are
2004 $status->successCount++;
2005 } else {
2006 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2007 $this->cleanupBatch[] = $row->fa_storage_key;
2008 }
2009
2010 $first = false;
2011 }
2012
2013 unset( $result );
2014
2015 // Add a warning to the status object for missing IDs
2016 $missingIds = array_diff( $this->ids, $idsPresent );
2017
2018 foreach ( $missingIds as $id ) {
2019 $status->error( 'undelete-missing-filearchive', $id );
2020 }
2021
2022 // Remove missing files from batch, so we don't get errors when undeleting them
2023 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2024
2025 // Run the store batch
2026 // Use the OVERWRITE_SAME flag to smooth over a common error
2027 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2028 $status->merge( $storeStatus );
2029
2030 if ( !$status->isGood() ) {
2031 // Even if some files could be copied, fail entirely as that is the
2032 // easiest thing to do without data loss
2033 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2034 $status->ok = false;
2035 $this->file->unlock();
2036
2037 return $status;
2038 }
2039
2040 // Run the DB updates
2041 // Because we have locked the image row, key conflicts should be rare.
2042 // If they do occur, we can roll back the transaction at this time with
2043 // no data loss, but leaving unregistered files scattered throughout the
2044 // public zone.
2045 // This is not ideal, which is why it's important to lock the image row.
2046 if ( $insertCurrent ) {
2047 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2048 }
2049
2050 if ( $insertBatch ) {
2051 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2052 }
2053
2054 if ( $deleteIds ) {
2055 $dbw->delete( 'filearchive',
2056 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2057 __METHOD__ );
2058 }
2059
2060 // If store batch is empty (all files are missing), deletion is to be considered successful
2061 if ( $status->successCount > 0 || !$storeBatch ) {
2062 if ( !$exists ) {
2063 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2064
2065 // Update site_stats
2066 $site_stats = $dbw->tableName( 'site_stats' );
2067 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2068
2069 $this->file->purgeEverything();
2070 } else {
2071 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2072 $this->file->purgeDescription();
2073 $this->file->purgeHistory();
2074 }
2075 }
2076
2077 $this->file->unlock();
2078
2079 return $status;
2080 }
2081
2082 /**
2083 * Removes non-existent files from a store batch.
2084 * @return array
2085 */
2086 function removeNonexistentFiles( $triplets ) {
2087 $files = $filteredTriplets = array();
2088 foreach ( $triplets as $file )
2089 $files[$file[0]] = $file[0];
2090
2091 $result = $this->file->repo->fileExistsBatch( $files );
2092
2093 foreach ( $triplets as $file ) {
2094 if ( $result[$file[0]] ) {
2095 $filteredTriplets[] = $file;
2096 }
2097 }
2098
2099 return $filteredTriplets;
2100 }
2101
2102 /**
2103 * Removes non-existent files from a cleanup batch.
2104 * @return array
2105 */
2106 function removeNonexistentFromCleanup( $batch ) {
2107 $files = $newBatch = array();
2108 $repo = $this->file->repo;
2109
2110 foreach ( $batch as $file ) {
2111 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2112 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2113 }
2114
2115 $result = $repo->fileExistsBatch( $files );
2116
2117 foreach ( $batch as $file ) {
2118 if ( $result[$file] ) {
2119 $newBatch[] = $file;
2120 }
2121 }
2122
2123 return $newBatch;
2124 }
2125
2126 /**
2127 * Delete unused files in the deleted zone.
2128 * This should be called from outside the transaction in which execute() was called.
2129 * @return FileRepoStatus|void
2130 */
2131 function cleanup() {
2132 if ( !$this->cleanupBatch ) {
2133 return $this->file->repo->newGood();
2134 }
2135
2136 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2137
2138 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2139
2140 return $status;
2141 }
2142
2143 /**
2144 * Cleanup a failed batch. The batch was only partially successful, so
2145 * rollback by removing all items that were succesfully copied.
2146 *
2147 * @param Status $storeStatus
2148 * @param array $storeBatch
2149 */
2150 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2151 $cleanupBatch = array();
2152
2153 foreach ( $storeStatus->success as $i => $success ) {
2154 // Check if this item of the batch was successfully copied
2155 if ( $success ) {
2156 // Item was successfully copied and needs to be removed again
2157 // Extract ($dstZone, $dstRel) from the batch
2158 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2159 }
2160 }
2161 $this->file->repo->cleanupBatch( $cleanupBatch );
2162 }
2163 }
2164
2165 # ------------------------------------------------------------------------------
2166
2167 /**
2168 * Helper class for file movement
2169 * @ingroup FileAbstraction
2170 */
2171 class LocalFileMoveBatch {
2172
2173 /**
2174 * @var File
2175 */
2176 var $file;
2177
2178 /**
2179 * @var Title
2180 */
2181 var $target;
2182
2183 var $cur, $olds, $oldCount, $archive, $db;
2184
2185 function __construct( File $file, Title $target ) {
2186 $this->file = $file;
2187 $this->target = $target;
2188 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2189 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2190 $this->oldName = $this->file->getName();
2191 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2192 $this->oldRel = $this->oldHash . $this->oldName;
2193 $this->newRel = $this->newHash . $this->newName;
2194 $this->db = $file->repo->getMasterDb();
2195 }
2196
2197 /**
2198 * Add the current image to the batch
2199 */
2200 function addCurrent() {
2201 $this->cur = array( $this->oldRel, $this->newRel );
2202 }
2203
2204 /**
2205 * Add the old versions of the image to the batch
2206 */
2207 function addOlds() {
2208 $archiveBase = 'archive';
2209 $this->olds = array();
2210 $this->oldCount = 0;
2211
2212 $result = $this->db->select( 'oldimage',
2213 array( 'oi_archive_name', 'oi_deleted' ),
2214 array( 'oi_name' => $this->oldName ),
2215 __METHOD__
2216 );
2217
2218 foreach ( $result as $row ) {
2219 $oldName = $row->oi_archive_name;
2220 $bits = explode( '!', $oldName, 2 );
2221
2222 if ( count( $bits ) != 2 ) {
2223 wfDebug( "Old file name missing !: '$oldName' \n" );
2224 continue;
2225 }
2226
2227 list( $timestamp, $filename ) = $bits;
2228
2229 if ( $this->oldName != $filename ) {
2230 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2231 continue;
2232 }
2233
2234 $this->oldCount++;
2235
2236 // Do we want to add those to oldCount?
2237 if ( $row->oi_deleted & File::DELETED_FILE ) {
2238 continue;
2239 }
2240
2241 $this->olds[] = array(
2242 "{$archiveBase}/{$this->oldHash}{$oldName}",
2243 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2244 );
2245 }
2246 }
2247
2248 /**
2249 * Perform the move.
2250 * @return FileRepoStatus
2251 */
2252 function execute() {
2253 $repo = $this->file->repo;
2254 $status = $repo->newGood();
2255 $triplets = $this->getMoveTriplets();
2256
2257 $triplets = $this->removeNonexistentFiles( $triplets );
2258
2259 // Copy the files into their new location
2260 $statusMove = $repo->storeBatch( $triplets );
2261 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2262 if ( !$statusMove->isGood() ) {
2263 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2264 $this->cleanupTarget( $triplets );
2265 $statusMove->ok = false;
2266 return $statusMove;
2267 }
2268
2269 $this->db->begin( __METHOD__ );
2270 $statusDb = $this->doDBUpdates();
2271 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2272 if ( !$statusDb->isGood() ) {
2273 $this->db->rollback( __METHOD__ );
2274 // Something went wrong with the DB updates, so remove the target files
2275 $this->cleanupTarget( $triplets );
2276 $statusDb->ok = false;
2277 return $statusDb;
2278 }
2279 $this->db->commit( __METHOD__ );
2280
2281 // Everything went ok, remove the source files
2282 $this->cleanupSource( $triplets );
2283
2284 $status->merge( $statusDb );
2285 $status->merge( $statusMove );
2286
2287 return $status;
2288 }
2289
2290 /**
2291 * Do the database updates and return a new FileRepoStatus indicating how
2292 * many rows where updated.
2293 *
2294 * @return FileRepoStatus
2295 */
2296 function doDBUpdates() {
2297 $repo = $this->file->repo;
2298 $status = $repo->newGood();
2299 $dbw = $this->db;
2300
2301 // Update current image
2302 $dbw->update(
2303 'image',
2304 array( 'img_name' => $this->newName ),
2305 array( 'img_name' => $this->oldName ),
2306 __METHOD__
2307 );
2308
2309 if ( $dbw->affectedRows() ) {
2310 $status->successCount++;
2311 } else {
2312 $status->failCount++;
2313 $status->fatal( 'imageinvalidfilename' );
2314 return $status;
2315 }
2316
2317 // Update old images
2318 $dbw->update(
2319 'oldimage',
2320 array(
2321 'oi_name' => $this->newName,
2322 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2323 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2324 ),
2325 array( 'oi_name' => $this->oldName ),
2326 __METHOD__
2327 );
2328
2329 $affected = $dbw->affectedRows();
2330 $total = $this->oldCount;
2331 $status->successCount += $affected;
2332 // Bug 34934: $total is based on files that actually exist.
2333 // There may be more DB rows than such files, in which case $affected
2334 // can be greater than $total. We use max() to avoid negatives here.
2335 $status->failCount += max( 0, $total - $affected );
2336 if ( $status->failCount ) {
2337 $status->error( 'imageinvalidfilename' );
2338 }
2339
2340 return $status;
2341 }
2342
2343 /**
2344 * Generate triplets for FileRepo::storeBatch().
2345 * @return array
2346 */
2347 function getMoveTriplets() {
2348 $moves = array_merge( array( $this->cur ), $this->olds );
2349 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2350
2351 foreach ( $moves as $move ) {
2352 // $move: (oldRelativePath, newRelativePath)
2353 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2354 $triplets[] = array( $srcUrl, 'public', $move[1] );
2355 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2356 }
2357
2358 return $triplets;
2359 }
2360
2361 /**
2362 * Removes non-existent files from move batch.
2363 * @return array
2364 */
2365 function removeNonexistentFiles( $triplets ) {
2366 $files = array();
2367
2368 foreach ( $triplets as $file ) {
2369 $files[$file[0]] = $file[0];
2370 }
2371
2372 $result = $this->file->repo->fileExistsBatch( $files );
2373 $filteredTriplets = array();
2374
2375 foreach ( $triplets as $file ) {
2376 if ( $result[$file[0]] ) {
2377 $filteredTriplets[] = $file;
2378 } else {
2379 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2380 }
2381 }
2382
2383 return $filteredTriplets;
2384 }
2385
2386 /**
2387 * Cleanup a partially moved array of triplets by deleting the target
2388 * files. Called if something went wrong half way.
2389 */
2390 function cleanupTarget( $triplets ) {
2391 // Create dest pairs from the triplets
2392 $pairs = array();
2393 foreach ( $triplets as $triplet ) {
2394 $pairs[] = array( $triplet[1], $triplet[2] );
2395 }
2396
2397 $this->file->repo->cleanupBatch( $pairs );
2398 }
2399
2400 /**
2401 * Cleanup a fully moved array of triplets by deleting the source files.
2402 * Called at the end of the move process if everything else went ok.
2403 */
2404 function cleanupSource( $triplets ) {
2405 // Create source file names from the triplets
2406 $files = array();
2407 foreach ( $triplets as $triplet ) {
2408 $files[] = $triplet[0];
2409 }
2410
2411 $this->file->repo->cleanupBatch( $files );
2412 }
2413 }