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