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