Merge r94252 to trunk
[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 */
617 function getThumbnails() {
618 $this->load();
619
620 $files = array();
621 $dir = $this->getThumbPath();
622
623 if ( is_dir( $dir ) ) {
624 $handle = opendir( $dir );
625
626 if ( $handle ) {
627 while ( false !== ( $file = readdir( $handle ) ) ) {
628 if ( $file { 0 } != '.' ) {
629 $files[] = $file;
630 }
631 }
632
633 closedir( $handle );
634 }
635 }
636
637 return $files;
638 }
639
640 /**
641 * Refresh metadata in memcached, but don't touch thumbnails or squid
642 */
643 function purgeMetadataCache() {
644 $this->loadFromDB();
645 $this->saveToCache();
646 $this->purgeHistory();
647 }
648
649 /**
650 * Purge the shared history (OldLocalFile) cache
651 */
652 function purgeHistory() {
653 global $wgMemc;
654
655 $hashedName = md5( $this->getName() );
656 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
657
658 // Must purge thumbnails for old versions too! bug 30192
659 foreach( $this->getHistory() as $oldFile ) {
660 $oldFile->purgeThumbnails();
661 }
662
663 if ( $oldKey ) {
664 $wgMemc->delete( $oldKey );
665 }
666 }
667
668 /**
669 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
670 */
671 function purgeCache() {
672 // Refresh metadata cache
673 $this->purgeMetadataCache();
674
675 // Delete thumbnails
676 $this->purgeThumbnails();
677
678 // Purge squid cache for this file
679 SquidUpdate::purge( array( $this->getURL() ) );
680 }
681
682 /**
683 * Delete cached transformed files
684 */
685 function purgeThumbnails() {
686 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
687
688 // Delete thumbnails
689 $files = $this->getThumbnails();
690 $dir = $this->getThumbPath();
691 $urls = array();
692
693 foreach ( $files as $file ) {
694 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
695 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION );
696 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
697 continue;
698 }
699
700 # Check that the base file name is part of the thumb name
701 # This is a basic sanity check to avoid erasing unrelated directories
702 if ( strpos( $file, $this->getName() ) !== false ) {
703 $url = $this->getThumbUrl( $file );
704 $urls[] = $url;
705 wfSuppressWarnings();
706 unlink( "$dir/$file" );
707 wfRestoreWarnings();
708 }
709 }
710
711 // Purge the squid
712 if ( $wgUseSquid ) {
713 SquidUpdate::purge( $urls );
714 }
715 }
716
717 /** purgeDescription inherited */
718 /** purgeEverything inherited */
719
720 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
721 $dbr = $this->repo->getSlaveDB();
722 $tables = array( 'oldimage' );
723 $fields = OldLocalFile::selectFields();
724 $conds = $opts = $join_conds = array();
725 $eq = $inc ? '=' : '';
726 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
727
728 if ( $start ) {
729 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
730 }
731
732 if ( $end ) {
733 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
734 }
735
736 if ( $limit ) {
737 $opts['LIMIT'] = $limit;
738 }
739
740 // Search backwards for time > x queries
741 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
742 $opts['ORDER BY'] = "oi_timestamp $order";
743 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
744
745 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
746 &$conds, &$opts, &$join_conds ) );
747
748 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
749 $r = array();
750
751 foreach ( $res as $row ) {
752 if ( $this->repo->oldFileFromRowFactory ) {
753 $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
754 } else {
755 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
756 }
757 }
758
759 if ( $order == 'ASC' ) {
760 $r = array_reverse( $r ); // make sure it ends up descending
761 }
762
763 return $r;
764 }
765
766 /**
767 * Return the history of this file, line by line.
768 * starts with current version, then old versions.
769 * uses $this->historyLine to check which line to return:
770 * 0 return line for current version
771 * 1 query for old versions, return first one
772 * 2, ... return next old version from above query
773 */
774 public function nextHistoryLine() {
775 # Polymorphic function name to distinguish foreign and local fetches
776 $fname = get_class( $this ) . '::' . __FUNCTION__;
777
778 $dbr = $this->repo->getSlaveDB();
779
780 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
781 $this->historyRes = $dbr->select( 'image',
782 array(
783 '*',
784 "'' AS oi_archive_name",
785 '0 as oi_deleted',
786 'img_sha1'
787 ),
788 array( 'img_name' => $this->title->getDBkey() ),
789 $fname
790 );
791
792 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
793 $this->historyRes = null;
794 return false;
795 }
796 } elseif ( $this->historyLine == 1 ) {
797 $this->historyRes = $dbr->select( 'oldimage', '*',
798 array( 'oi_name' => $this->title->getDBkey() ),
799 $fname,
800 array( 'ORDER BY' => 'oi_timestamp DESC' )
801 );
802 }
803 $this->historyLine ++;
804
805 return $dbr->fetchObject( $this->historyRes );
806 }
807
808 /**
809 * Reset the history pointer to the first element of the history
810 */
811 public function resetHistory() {
812 $this->historyLine = 0;
813
814 if ( !is_null( $this->historyRes ) ) {
815 $this->historyRes = null;
816 }
817 }
818
819 /** getFullPath inherited */
820 /** getHashPath inherited */
821 /** getRel inherited */
822 /** getUrlRel inherited */
823 /** getArchiveRel inherited */
824 /** getArchivePath inherited */
825 /** getThumbPath inherited */
826 /** getArchiveUrl inherited */
827 /** getThumbUrl inherited */
828 /** getArchiveVirtualUrl inherited */
829 /** getThumbVirtualUrl inherited */
830 /** isHashed inherited */
831
832 /**
833 * Upload a file and record it in the DB
834 * @param $srcPath String: source path or virtual URL
835 * @param $comment String: upload description
836 * @param $pageText String: text to use for the new description page,
837 * if a new description page is created
838 * @param $flags Integer: flags for publish()
839 * @param $props Array: File properties, if known. This can be used to reduce the
840 * upload time when uploading virtual URLs for which the file info
841 * is already known
842 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
843 * @param $user Mixed: User object or null to use $wgUser
844 *
845 * @return FileRepoStatus object. On success, the value member contains the
846 * archive name, or an empty string if it was a new file.
847 */
848 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
849 $this->lock();
850 $status = $this->publish( $srcPath, $flags );
851
852 if ( $status->ok ) {
853 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
854 $status->fatal( 'filenotfound', $srcPath );
855 }
856 }
857
858 $this->unlock();
859
860 return $status;
861 }
862
863 /**
864 * Record a file upload in the upload log and the image table
865 */
866 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
867 $watch = false, $timestamp = false )
868 {
869 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
870
871 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
872 return false;
873 }
874
875 if ( $watch ) {
876 global $wgUser;
877 $wgUser->addWatch( $this->getTitle() );
878 }
879 return true;
880 }
881
882 /**
883 * Record a file upload in the upload log and the image table
884 */
885 function recordUpload2(
886 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
887 ) {
888 if ( is_null( $user ) ) {
889 global $wgUser;
890 $user = $wgUser;
891 }
892
893 $dbw = $this->repo->getMasterDB();
894 $dbw->begin();
895
896 if ( !$props ) {
897 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
898 }
899
900 if ( $timestamp === false ) {
901 $timestamp = $dbw->timestamp();
902 }
903
904 $props['description'] = $comment;
905 $props['user'] = $user->getId();
906 $props['user_text'] = $user->getName();
907 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
908 $this->setProps( $props );
909
910 # Delete thumbnails
911 $this->purgeThumbnails();
912
913 # The file is already on its final location, remove it from the squid cache
914 SquidUpdate::purge( array( $this->getURL() ) );
915
916 # Fail now if the file isn't there
917 if ( !$this->fileExists ) {
918 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
919 return false;
920 }
921
922 $reupload = false;
923
924 # Test to see if the row exists using INSERT IGNORE
925 # This avoids race conditions by locking the row until the commit, and also
926 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
927 $dbw->insert( 'image',
928 array(
929 'img_name' => $this->getName(),
930 'img_size' => $this->size,
931 'img_width' => intval( $this->width ),
932 'img_height' => intval( $this->height ),
933 'img_bits' => $this->bits,
934 'img_media_type' => $this->media_type,
935 'img_major_mime' => $this->major_mime,
936 'img_minor_mime' => $this->minor_mime,
937 'img_timestamp' => $timestamp,
938 'img_description' => $comment,
939 'img_user' => $user->getId(),
940 'img_user_text' => $user->getName(),
941 'img_metadata' => $this->metadata,
942 'img_sha1' => $this->sha1
943 ),
944 __METHOD__,
945 'IGNORE'
946 );
947
948 if ( $dbw->affectedRows() == 0 ) {
949 $reupload = true;
950
951 # Collision, this is an update of a file
952 # Insert previous contents into oldimage
953 $dbw->insertSelect( 'oldimage', 'image',
954 array(
955 'oi_name' => 'img_name',
956 'oi_archive_name' => $dbw->addQuotes( $oldver ),
957 'oi_size' => 'img_size',
958 'oi_width' => 'img_width',
959 'oi_height' => 'img_height',
960 'oi_bits' => 'img_bits',
961 'oi_timestamp' => 'img_timestamp',
962 'oi_description' => 'img_description',
963 'oi_user' => 'img_user',
964 'oi_user_text' => 'img_user_text',
965 'oi_metadata' => 'img_metadata',
966 'oi_media_type' => 'img_media_type',
967 'oi_major_mime' => 'img_major_mime',
968 'oi_minor_mime' => 'img_minor_mime',
969 'oi_sha1' => 'img_sha1'
970 ), array( 'img_name' => $this->getName() ), __METHOD__
971 );
972
973 # Update the current image row
974 $dbw->update( 'image',
975 array( /* SET */
976 'img_size' => $this->size,
977 'img_width' => intval( $this->width ),
978 'img_height' => intval( $this->height ),
979 'img_bits' => $this->bits,
980 'img_media_type' => $this->media_type,
981 'img_major_mime' => $this->major_mime,
982 'img_minor_mime' => $this->minor_mime,
983 'img_timestamp' => $timestamp,
984 'img_description' => $comment,
985 'img_user' => $user->getId(),
986 'img_user_text' => $user->getName(),
987 'img_metadata' => $this->metadata,
988 'img_sha1' => $this->sha1
989 ), array( /* WHERE */
990 'img_name' => $this->getName()
991 ), __METHOD__
992 );
993 } else {
994 # This is a new file
995 # Update the image count
996 $dbw->begin( __METHOD__ );
997 $dbw->update(
998 'site_stats',
999 array( 'ss_images' => 'ss_images+1' ),
1000 array(),
1001 __METHOD__
1002 );
1003 $dbw->commit( __METHOD__ );
1004 }
1005
1006 $descTitle = $this->getTitle();
1007 $article = new ImagePage( $descTitle );
1008 $article->setFile( $this );
1009
1010 # Add the log entry
1011 $log = new LogPage( 'upload' );
1012 $action = $reupload ? 'overwrite' : 'upload';
1013 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1014
1015 if ( $descTitle->exists() ) {
1016 # Create a null revision
1017 $latest = $descTitle->getLatestRevID();
1018 $nullRevision = Revision::newNullRevision(
1019 $dbw,
1020 $descTitle->getArticleId(),
1021 $log->getRcComment(),
1022 false
1023 );
1024 if (!is_null($nullRevision)) {
1025 $nullRevision->insertOn( $dbw );
1026
1027 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1028 $article->updateRevisionOn( $dbw, $nullRevision );
1029 }
1030 # Invalidate the cache for the description page
1031 $descTitle->invalidateCache();
1032 $descTitle->purgeSquid();
1033 } else {
1034 # New file; create the description page.
1035 # There's already a log entry, so don't make a second RC entry
1036 # Squid and file cache for the description page are purged by doEdit.
1037 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
1038 }
1039
1040 # Commit the transaction now, in case something goes wrong later
1041 # The most important thing is that files don't get lost, especially archives
1042 $dbw->commit();
1043
1044 # Save to cache and purge the squid
1045 # We shall not saveToCache before the commit since otherwise
1046 # in case of a rollback there is an usable file from memcached
1047 # which in fact doesn't really exist (bug 24978)
1048 $this->saveToCache();
1049
1050 # Hooks, hooks, the magic of hooks...
1051 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1052
1053 # Invalidate cache for all pages using this file
1054 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1055 $update->doUpdate();
1056
1057 # Invalidate cache for all pages that redirects on this page
1058 $redirs = $this->getTitle()->getRedirectsHere();
1059
1060 foreach ( $redirs as $redir ) {
1061 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1062 $update->doUpdate();
1063 }
1064
1065 return true;
1066 }
1067
1068 /**
1069 * Move or copy a file to its public location. If a file exists at the
1070 * destination, move it to an archive. Returns a FileRepoStatus object with
1071 * the archive name in the "value" member on success.
1072 *
1073 * The archive name should be passed through to recordUpload for database
1074 * registration.
1075 *
1076 * @param $srcPath String: local filesystem path to the source image
1077 * @param $flags Integer: a bitwise combination of:
1078 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1079 * @return FileRepoStatus object. On success, the value member contains the
1080 * archive name, or an empty string if it was a new file.
1081 */
1082 function publish( $srcPath, $flags = 0 ) {
1083 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1084 }
1085
1086 /**
1087 * Move or copy a file to a specified location. Returns a FileRepoStatus
1088 * object with the archive name in the "value" member on success.
1089 *
1090 * The archive name should be passed through to recordUpload for database
1091 * registration.
1092 *
1093 * @param $srcPath String: local filesystem path to the source image
1094 * @param $dstRel String: target relative path
1095 * @param $flags Integer: a bitwise combination of:
1096 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1097 * @return FileRepoStatus object. On success, the value member contains the
1098 * archive name, or an empty string if it was a new file.
1099 */
1100 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1101 $this->lock();
1102
1103 $archiveName = wfTimestamp( TS_MW ) . '!'. $this->getName();
1104 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1105 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1106 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
1107
1108 if ( $status->value == 'new' ) {
1109 $status->value = '';
1110 } else {
1111 $status->value = $archiveName;
1112 }
1113
1114 $this->unlock();
1115
1116 return $status;
1117 }
1118
1119 /** getLinksTo inherited */
1120 /** getExifData inherited */
1121 /** isLocal inherited */
1122 /** wasDeleted inherited */
1123
1124 /**
1125 * Move file to the new title
1126 *
1127 * Move current, old version and all thumbnails
1128 * to the new filename. Old file is deleted.
1129 *
1130 * Cache purging is done; checks for validity
1131 * and logging are caller's responsibility
1132 *
1133 * @param $target Title New file name
1134 * @return FileRepoStatus object.
1135 */
1136 function move( $target ) {
1137 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1138 $this->lock();
1139
1140 $batch = new LocalFileMoveBatch( $this, $target );
1141 $batch->addCurrent();
1142 $batch->addOlds();
1143
1144 $status = $batch->execute();
1145 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1146
1147 $this->purgeEverything();
1148 $this->unlock();
1149
1150 if ( $status->isOk() ) {
1151 // Now switch the object
1152 $this->title = $target;
1153 // Force regeneration of the name and hashpath
1154 unset( $this->name );
1155 unset( $this->hashPath );
1156 // Purge the new image
1157 $this->purgeEverything();
1158 }
1159
1160 return $status;
1161 }
1162
1163 /**
1164 * Delete all versions of the file.
1165 *
1166 * Moves the files into an archive directory (or deletes them)
1167 * and removes the database rows.
1168 *
1169 * Cache purging is done; logging is caller's responsibility.
1170 *
1171 * @param $reason
1172 * @param $suppress
1173 * @return FileRepoStatus object.
1174 */
1175 function delete( $reason, $suppress = false ) {
1176 $this->lock();
1177
1178 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1179 $batch->addCurrent();
1180
1181 # Get old version relative paths
1182 $dbw = $this->repo->getMasterDB();
1183 $result = $dbw->select( 'oldimage',
1184 array( 'oi_archive_name' ),
1185 array( 'oi_name' => $this->getName() ) );
1186 foreach ( $result as $row ) {
1187 $batch->addOld( $row->oi_archive_name );
1188 }
1189 $status = $batch->execute();
1190
1191 if ( $status->ok ) {
1192 // Update site_stats
1193 $site_stats = $dbw->tableName( 'site_stats' );
1194 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1195 $this->purgeEverything();
1196 }
1197
1198 $this->unlock();
1199
1200 return $status;
1201 }
1202
1203 /**
1204 * Delete an old version of the file.
1205 *
1206 * Moves the file into an archive directory (or deletes it)
1207 * and removes the database row.
1208 *
1209 * Cache purging is done; logging is caller's responsibility.
1210 *
1211 * @param $archiveName String
1212 * @param $reason String
1213 * @param $suppress Boolean
1214 * @throws MWException or FSException on database or file store failure
1215 * @return FileRepoStatus object.
1216 */
1217 function deleteOld( $archiveName, $reason, $suppress = false ) {
1218 $this->lock();
1219
1220 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1221 $batch->addOld( $archiveName );
1222 $status = $batch->execute();
1223
1224 $this->unlock();
1225
1226 if ( $status->ok ) {
1227 $this->purgeDescription();
1228 $this->purgeHistory();
1229 }
1230
1231 return $status;
1232 }
1233
1234 /**
1235 * Restore all or specified deleted revisions to the given file.
1236 * Permissions and logging are left to the caller.
1237 *
1238 * May throw database exceptions on error.
1239 *
1240 * @param $versions set of record ids of deleted items to restore,
1241 * or empty to restore all revisions.
1242 * @param $unsuppress Boolean
1243 * @return FileRepoStatus
1244 */
1245 function restore( $versions = array(), $unsuppress = false ) {
1246 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1247
1248 if ( !$versions ) {
1249 $batch->addAll();
1250 } else {
1251 $batch->addIds( $versions );
1252 }
1253
1254 $status = $batch->execute();
1255
1256 if ( !$status->isGood() ) {
1257 return $status;
1258 }
1259
1260 $cleanupStatus = $batch->cleanup();
1261 $cleanupStatus->successCount = 0;
1262 $cleanupStatus->failCount = 0;
1263 $status->merge( $cleanupStatus );
1264
1265 return $status;
1266 }
1267
1268 /** isMultipage inherited */
1269 /** pageCount inherited */
1270 /** scaleHeight inherited */
1271 /** getImageSize inherited */
1272
1273 /**
1274 * Get the URL of the file description page.
1275 */
1276 function getDescriptionUrl() {
1277 return $this->title->getLocalUrl();
1278 }
1279
1280 /**
1281 * Get the HTML text of the description page
1282 * This is not used by ImagePage for local files, since (among other things)
1283 * it skips the parser cache.
1284 */
1285 function getDescriptionText() {
1286 global $wgParser;
1287 $revision = Revision::newFromTitle( $this->title );
1288 if ( !$revision ) return false;
1289 $text = $revision->getText();
1290 if ( !$text ) return false;
1291 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1292 return $pout->getText();
1293 }
1294
1295 function getDescription() {
1296 $this->load();
1297 return $this->description;
1298 }
1299
1300 function getTimestamp() {
1301 $this->load();
1302 return $this->timestamp;
1303 }
1304
1305 function getSha1() {
1306 $this->load();
1307 // Initialise now if necessary
1308 if ( $this->sha1 == '' && $this->fileExists ) {
1309 $this->sha1 = File::sha1Base36( $this->getPath() );
1310 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1311 $dbw = $this->repo->getMasterDB();
1312 $dbw->update( 'image',
1313 array( 'img_sha1' => $this->sha1 ),
1314 array( 'img_name' => $this->getName() ),
1315 __METHOD__ );
1316 $this->saveToCache();
1317 }
1318 }
1319
1320 return $this->sha1;
1321 }
1322
1323 /**
1324 * Start a transaction and lock the image for update
1325 * Increments a reference counter if the lock is already held
1326 * @return boolean True if the image exists, false otherwise
1327 */
1328 function lock() {
1329 $dbw = $this->repo->getMasterDB();
1330
1331 if ( !$this->locked ) {
1332 $dbw->begin();
1333 $this->locked++;
1334 }
1335
1336 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1337 }
1338
1339 /**
1340 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1341 * the transaction and thereby releases the image lock.
1342 */
1343 function unlock() {
1344 if ( $this->locked ) {
1345 --$this->locked;
1346 if ( !$this->locked ) {
1347 $dbw = $this->repo->getMasterDB();
1348 $dbw->commit();
1349 }
1350 }
1351 }
1352
1353 /**
1354 * Roll back the DB transaction and mark the image unlocked
1355 */
1356 function unlockAndRollback() {
1357 $this->locked = false;
1358 $dbw = $this->repo->getMasterDB();
1359 $dbw->rollback();
1360 }
1361 } // LocalFile class
1362
1363 # ------------------------------------------------------------------------------
1364
1365 /**
1366 * Helper class for file deletion
1367 * @ingroup FileRepo
1368 */
1369 class LocalFileDeleteBatch {
1370
1371 /**
1372 * @var LocalFile
1373 */
1374 var $file;
1375
1376 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1377 var $status;
1378
1379 function __construct( File $file, $reason = '', $suppress = false ) {
1380 $this->file = $file;
1381 $this->reason = $reason;
1382 $this->suppress = $suppress;
1383 $this->status = $file->repo->newGood();
1384 }
1385
1386 function addCurrent() {
1387 $this->srcRels['.'] = $this->file->getRel();
1388 }
1389
1390 function addOld( $oldName ) {
1391 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1392 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1393 }
1394
1395 function getOldRels() {
1396 if ( !isset( $this->srcRels['.'] ) ) {
1397 $oldRels =& $this->srcRels;
1398 $deleteCurrent = false;
1399 } else {
1400 $oldRels = $this->srcRels;
1401 unset( $oldRels['.'] );
1402 $deleteCurrent = true;
1403 }
1404
1405 return array( $oldRels, $deleteCurrent );
1406 }
1407
1408 protected function getHashes() {
1409 $hashes = array();
1410 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1411
1412 if ( $deleteCurrent ) {
1413 $hashes['.'] = $this->file->getSha1();
1414 }
1415
1416 if ( count( $oldRels ) ) {
1417 $dbw = $this->file->repo->getMasterDB();
1418 $res = $dbw->select(
1419 'oldimage',
1420 array( 'oi_archive_name', 'oi_sha1' ),
1421 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1422 __METHOD__
1423 );
1424
1425 foreach ( $res as $row ) {
1426 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1427 // Get the hash from the file
1428 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1429 $props = $this->file->repo->getFileProps( $oldUrl );
1430
1431 if ( $props['fileExists'] ) {
1432 // Upgrade the oldimage row
1433 $dbw->update( 'oldimage',
1434 array( 'oi_sha1' => $props['sha1'] ),
1435 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1436 __METHOD__ );
1437 $hashes[$row->oi_archive_name] = $props['sha1'];
1438 } else {
1439 $hashes[$row->oi_archive_name] = false;
1440 }
1441 } else {
1442 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1443 }
1444 }
1445 }
1446
1447 $missing = array_diff_key( $this->srcRels, $hashes );
1448
1449 foreach ( $missing as $name => $rel ) {
1450 $this->status->error( 'filedelete-old-unregistered', $name );
1451 }
1452
1453 foreach ( $hashes as $name => $hash ) {
1454 if ( !$hash ) {
1455 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1456 unset( $hashes[$name] );
1457 }
1458 }
1459
1460 return $hashes;
1461 }
1462
1463 function doDBInserts() {
1464 global $wgUser;
1465
1466 $dbw = $this->file->repo->getMasterDB();
1467 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1468 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1469 $encReason = $dbw->addQuotes( $this->reason );
1470 $encGroup = $dbw->addQuotes( 'deleted' );
1471 $ext = $this->file->getExtension();
1472 $dotExt = $ext === '' ? '' : ".$ext";
1473 $encExt = $dbw->addQuotes( $dotExt );
1474 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1475
1476 // Bitfields to further suppress the content
1477 if ( $this->suppress ) {
1478 $bitfield = 0;
1479 // This should be 15...
1480 $bitfield |= Revision::DELETED_TEXT;
1481 $bitfield |= Revision::DELETED_COMMENT;
1482 $bitfield |= Revision::DELETED_USER;
1483 $bitfield |= Revision::DELETED_RESTRICTED;
1484 } else {
1485 $bitfield = 'oi_deleted';
1486 }
1487
1488 if ( $deleteCurrent ) {
1489 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1490 $where = array( 'img_name' => $this->file->getName() );
1491 $dbw->insertSelect( 'filearchive', 'image',
1492 array(
1493 'fa_storage_group' => $encGroup,
1494 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1495 'fa_deleted_user' => $encUserId,
1496 'fa_deleted_timestamp' => $encTimestamp,
1497 'fa_deleted_reason' => $encReason,
1498 'fa_deleted' => $this->suppress ? $bitfield : 0,
1499
1500 'fa_name' => 'img_name',
1501 'fa_archive_name' => 'NULL',
1502 'fa_size' => 'img_size',
1503 'fa_width' => 'img_width',
1504 'fa_height' => 'img_height',
1505 'fa_metadata' => 'img_metadata',
1506 'fa_bits' => 'img_bits',
1507 'fa_media_type' => 'img_media_type',
1508 'fa_major_mime' => 'img_major_mime',
1509 'fa_minor_mime' => 'img_minor_mime',
1510 'fa_description' => 'img_description',
1511 'fa_user' => 'img_user',
1512 'fa_user_text' => 'img_user_text',
1513 'fa_timestamp' => 'img_timestamp'
1514 ), $where, __METHOD__ );
1515 }
1516
1517 if ( count( $oldRels ) ) {
1518 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1519 $where = array(
1520 'oi_name' => $this->file->getName(),
1521 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1522 $dbw->insertSelect( 'filearchive', 'oldimage',
1523 array(
1524 'fa_storage_group' => $encGroup,
1525 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1526 'fa_deleted_user' => $encUserId,
1527 'fa_deleted_timestamp' => $encTimestamp,
1528 'fa_deleted_reason' => $encReason,
1529 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1530
1531 'fa_name' => 'oi_name',
1532 'fa_archive_name' => 'oi_archive_name',
1533 'fa_size' => 'oi_size',
1534 'fa_width' => 'oi_width',
1535 'fa_height' => 'oi_height',
1536 'fa_metadata' => 'oi_metadata',
1537 'fa_bits' => 'oi_bits',
1538 'fa_media_type' => 'oi_media_type',
1539 'fa_major_mime' => 'oi_major_mime',
1540 'fa_minor_mime' => 'oi_minor_mime',
1541 'fa_description' => 'oi_description',
1542 'fa_user' => 'oi_user',
1543 'fa_user_text' => 'oi_user_text',
1544 'fa_timestamp' => 'oi_timestamp',
1545 'fa_deleted' => $bitfield
1546 ), $where, __METHOD__ );
1547 }
1548 }
1549
1550 function doDBDeletes() {
1551 $dbw = $this->file->repo->getMasterDB();
1552 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1553
1554 if ( count( $oldRels ) ) {
1555 $dbw->delete( 'oldimage',
1556 array(
1557 'oi_name' => $this->file->getName(),
1558 'oi_archive_name' => array_keys( $oldRels )
1559 ), __METHOD__ );
1560 }
1561
1562 if ( $deleteCurrent ) {
1563 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1564 }
1565 }
1566
1567 /**
1568 * Run the transaction
1569 */
1570 function execute() {
1571 global $wgUseSquid;
1572 wfProfileIn( __METHOD__ );
1573
1574 $this->file->lock();
1575 // Leave private files alone
1576 $privateFiles = array();
1577 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1578 $dbw = $this->file->repo->getMasterDB();
1579
1580 if ( !empty( $oldRels ) ) {
1581 $res = $dbw->select( 'oldimage',
1582 array( 'oi_archive_name' ),
1583 array( 'oi_name' => $this->file->getName(),
1584 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1585 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1586 __METHOD__ );
1587
1588 foreach ( $res as $row ) {
1589 $privateFiles[$row->oi_archive_name] = 1;
1590 }
1591 }
1592 // Prepare deletion batch
1593 $hashes = $this->getHashes();
1594 $this->deletionBatch = array();
1595 $ext = $this->file->getExtension();
1596 $dotExt = $ext === '' ? '' : ".$ext";
1597
1598 foreach ( $this->srcRels as $name => $srcRel ) {
1599 // Skip files that have no hash (missing source).
1600 // Keep private files where they are.
1601 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1602 $hash = $hashes[$name];
1603 $key = $hash . $dotExt;
1604 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1605 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1606 }
1607 }
1608
1609 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1610 // We acquire this lock by running the inserts now, before the file operations.
1611 //
1612 // This potentially has poor lock contention characteristics -- an alternative
1613 // scheme would be to insert stub filearchive entries with no fa_name and commit
1614 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1615 $this->doDBInserts();
1616
1617 // Removes non-existent file from the batch, so we don't get errors.
1618 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1619
1620 // Execute the file deletion batch
1621 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1622
1623 if ( !$status->isGood() ) {
1624 $this->status->merge( $status );
1625 }
1626
1627 if ( !$this->status->ok ) {
1628 // Critical file deletion error
1629 // Roll back inserts, release lock and abort
1630 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1631 $this->file->unlockAndRollback();
1632 wfProfileOut( __METHOD__ );
1633 return $this->status;
1634 }
1635
1636 // Purge squid
1637 if ( $wgUseSquid ) {
1638 $urls = array();
1639
1640 foreach ( $this->srcRels as $srcRel ) {
1641 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1642 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1643 }
1644 SquidUpdate::purge( $urls );
1645 }
1646
1647 // Delete image/oldimage rows
1648 $this->doDBDeletes();
1649
1650 // Commit and return
1651 $this->file->unlock();
1652 wfProfileOut( __METHOD__ );
1653
1654 return $this->status;
1655 }
1656
1657 /**
1658 * Removes non-existent files from a deletion batch.
1659 */
1660 function removeNonexistentFiles( $batch ) {
1661 $files = $newBatch = array();
1662
1663 foreach ( $batch as $batchItem ) {
1664 list( $src, $dest ) = $batchItem;
1665 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1666 }
1667
1668 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1669
1670 foreach ( $batch as $batchItem ) {
1671 if ( $result[$batchItem[0]] ) {
1672 $newBatch[] = $batchItem;
1673 }
1674 }
1675
1676 return $newBatch;
1677 }
1678 }
1679
1680 # ------------------------------------------------------------------------------
1681
1682 /**
1683 * Helper class for file undeletion
1684 * @ingroup FileRepo
1685 */
1686 class LocalFileRestoreBatch {
1687 /**
1688 * @var LocalFile
1689 */
1690 var $file;
1691
1692 var $cleanupBatch, $ids, $all, $unsuppress = false;
1693
1694 function __construct( File $file, $unsuppress = false ) {
1695 $this->file = $file;
1696 $this->cleanupBatch = $this->ids = array();
1697 $this->ids = array();
1698 $this->unsuppress = $unsuppress;
1699 }
1700
1701 /**
1702 * Add a file by ID
1703 */
1704 function addId( $fa_id ) {
1705 $this->ids[] = $fa_id;
1706 }
1707
1708 /**
1709 * Add a whole lot of files by ID
1710 */
1711 function addIds( $ids ) {
1712 $this->ids = array_merge( $this->ids, $ids );
1713 }
1714
1715 /**
1716 * Add all revisions of the file
1717 */
1718 function addAll() {
1719 $this->all = true;
1720 }
1721
1722 /**
1723 * Run the transaction, except the cleanup batch.
1724 * The cleanup batch should be run in a separate transaction, because it locks different
1725 * rows and there's no need to keep the image row locked while it's acquiring those locks
1726 * The caller may have its own transaction open.
1727 * So we save the batch and let the caller call cleanup()
1728 */
1729 function execute() {
1730 global $wgLang;
1731
1732 if ( !$this->all && !$this->ids ) {
1733 // Do nothing
1734 return $this->file->repo->newGood();
1735 }
1736
1737 $exists = $this->file->lock();
1738 $dbw = $this->file->repo->getMasterDB();
1739 $status = $this->file->repo->newGood();
1740
1741 // Fetch all or selected archived revisions for the file,
1742 // sorted from the most recent to the oldest.
1743 $conditions = array( 'fa_name' => $this->file->getName() );
1744
1745 if ( !$this->all ) {
1746 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1747 }
1748
1749 $result = $dbw->select( 'filearchive', '*',
1750 $conditions,
1751 __METHOD__,
1752 array( 'ORDER BY' => 'fa_timestamp DESC' )
1753 );
1754
1755 $idsPresent = array();
1756 $storeBatch = array();
1757 $insertBatch = array();
1758 $insertCurrent = false;
1759 $deleteIds = array();
1760 $first = true;
1761 $archiveNames = array();
1762
1763 foreach ( $result as $row ) {
1764 $idsPresent[] = $row->fa_id;
1765
1766 if ( $row->fa_name != $this->file->getName() ) {
1767 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1768 $status->failCount++;
1769 continue;
1770 }
1771
1772 if ( $row->fa_storage_key == '' ) {
1773 // Revision was missing pre-deletion
1774 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1775 $status->failCount++;
1776 continue;
1777 }
1778
1779 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1780 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1781
1782 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1783
1784 # Fix leading zero
1785 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1786 $sha1 = substr( $sha1, 1 );
1787 }
1788
1789 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1790 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1791 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1792 || is_null( $row->fa_metadata ) ) {
1793 // Refresh our metadata
1794 // Required for a new current revision; nice for older ones too. :)
1795 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1796 } else {
1797 $props = array(
1798 'minor_mime' => $row->fa_minor_mime,
1799 'major_mime' => $row->fa_major_mime,
1800 'media_type' => $row->fa_media_type,
1801 'metadata' => $row->fa_metadata
1802 );
1803 }
1804
1805 if ( $first && !$exists ) {
1806 // This revision will be published as the new current version
1807 $destRel = $this->file->getRel();
1808 $insertCurrent = array(
1809 'img_name' => $row->fa_name,
1810 'img_size' => $row->fa_size,
1811 'img_width' => $row->fa_width,
1812 'img_height' => $row->fa_height,
1813 'img_metadata' => $props['metadata'],
1814 'img_bits' => $row->fa_bits,
1815 'img_media_type' => $props['media_type'],
1816 'img_major_mime' => $props['major_mime'],
1817 'img_minor_mime' => $props['minor_mime'],
1818 'img_description' => $row->fa_description,
1819 'img_user' => $row->fa_user,
1820 'img_user_text' => $row->fa_user_text,
1821 'img_timestamp' => $row->fa_timestamp,
1822 'img_sha1' => $sha1
1823 );
1824
1825 // The live (current) version cannot be hidden!
1826 if ( !$this->unsuppress && $row->fa_deleted ) {
1827 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1828 $this->cleanupBatch[] = $row->fa_storage_key;
1829 }
1830 } else {
1831 $archiveName = $row->fa_archive_name;
1832
1833 if ( $archiveName == '' ) {
1834 // This was originally a current version; we
1835 // have to devise a new archive name for it.
1836 // Format is <timestamp of archiving>!<name>
1837 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1838
1839 do {
1840 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1841 $timestamp++;
1842 } while ( isset( $archiveNames[$archiveName] ) );
1843 }
1844
1845 $archiveNames[$archiveName] = true;
1846 $destRel = $this->file->getArchiveRel( $archiveName );
1847 $insertBatch[] = array(
1848 'oi_name' => $row->fa_name,
1849 'oi_archive_name' => $archiveName,
1850 'oi_size' => $row->fa_size,
1851 'oi_width' => $row->fa_width,
1852 'oi_height' => $row->fa_height,
1853 'oi_bits' => $row->fa_bits,
1854 'oi_description' => $row->fa_description,
1855 'oi_user' => $row->fa_user,
1856 'oi_user_text' => $row->fa_user_text,
1857 'oi_timestamp' => $row->fa_timestamp,
1858 'oi_metadata' => $props['metadata'],
1859 'oi_media_type' => $props['media_type'],
1860 'oi_major_mime' => $props['major_mime'],
1861 'oi_minor_mime' => $props['minor_mime'],
1862 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1863 'oi_sha1' => $sha1 );
1864 }
1865
1866 $deleteIds[] = $row->fa_id;
1867
1868 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1869 // private files can stay where they are
1870 $status->successCount++;
1871 } else {
1872 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1873 $this->cleanupBatch[] = $row->fa_storage_key;
1874 }
1875
1876 $first = false;
1877 }
1878
1879 unset( $result );
1880
1881 // Add a warning to the status object for missing IDs
1882 $missingIds = array_diff( $this->ids, $idsPresent );
1883
1884 foreach ( $missingIds as $id ) {
1885 $status->error( 'undelete-missing-filearchive', $id );
1886 }
1887
1888 // Remove missing files from batch, so we don't get errors when undeleting them
1889 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1890
1891 // Run the store batch
1892 // Use the OVERWRITE_SAME flag to smooth over a common error
1893 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1894 $status->merge( $storeStatus );
1895
1896 if ( !$status->isGood() ) {
1897 // Even if some files could be copied, fail entirely as that is the
1898 // easiest thing to do without data loss
1899 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1900 $status->ok = false;
1901 $this->file->unlock();
1902
1903 return $status;
1904 }
1905
1906 // Run the DB updates
1907 // Because we have locked the image row, key conflicts should be rare.
1908 // If they do occur, we can roll back the transaction at this time with
1909 // no data loss, but leaving unregistered files scattered throughout the
1910 // public zone.
1911 // This is not ideal, which is why it's important to lock the image row.
1912 if ( $insertCurrent ) {
1913 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1914 }
1915
1916 if ( $insertBatch ) {
1917 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1918 }
1919
1920 if ( $deleteIds ) {
1921 $dbw->delete( 'filearchive',
1922 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1923 __METHOD__ );
1924 }
1925
1926 // If store batch is empty (all files are missing), deletion is to be considered successful
1927 if ( $status->successCount > 0 || !$storeBatch ) {
1928 if ( !$exists ) {
1929 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1930
1931 // Update site_stats
1932 $site_stats = $dbw->tableName( 'site_stats' );
1933 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1934
1935 $this->file->purgeEverything();
1936 } else {
1937 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1938 $this->file->purgeDescription();
1939 $this->file->purgeHistory();
1940 }
1941 }
1942
1943 $this->file->unlock();
1944
1945 return $status;
1946 }
1947
1948 /**
1949 * Removes non-existent files from a store batch.
1950 */
1951 function removeNonexistentFiles( $triplets ) {
1952 $files = $filteredTriplets = array();
1953 foreach ( $triplets as $file )
1954 $files[$file[0]] = $file[0];
1955
1956 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1957
1958 foreach ( $triplets as $file ) {
1959 if ( $result[$file[0]] ) {
1960 $filteredTriplets[] = $file;
1961 }
1962 }
1963
1964 return $filteredTriplets;
1965 }
1966
1967 /**
1968 * Removes non-existent files from a cleanup batch.
1969 */
1970 function removeNonexistentFromCleanup( $batch ) {
1971 $files = $newBatch = array();
1972 $repo = $this->file->repo;
1973
1974 foreach ( $batch as $file ) {
1975 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1976 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1977 }
1978
1979 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1980
1981 foreach ( $batch as $file ) {
1982 if ( $result[$file] ) {
1983 $newBatch[] = $file;
1984 }
1985 }
1986
1987 return $newBatch;
1988 }
1989
1990 /**
1991 * Delete unused files in the deleted zone.
1992 * This should be called from outside the transaction in which execute() was called.
1993 */
1994 function cleanup() {
1995 if ( !$this->cleanupBatch ) {
1996 return $this->file->repo->newGood();
1997 }
1998
1999 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2000
2001 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2002
2003 return $status;
2004 }
2005
2006 /**
2007 * Cleanup a failed batch. The batch was only partially successful, so
2008 * rollback by removing all items that were succesfully copied.
2009 *
2010 * @param Status $storeStatus
2011 * @param array $storeBatch
2012 */
2013 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2014 $cleanupBatch = array();
2015
2016 foreach ( $storeStatus->success as $i => $success ) {
2017 // Check if this item of the batch was successfully copied
2018 if ( $success ) {
2019 // Item was successfully copied and needs to be removed again
2020 // Extract ($dstZone, $dstRel) from the batch
2021 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2022 }
2023 }
2024 $this->file->repo->cleanupBatch( $cleanupBatch );
2025 }
2026 }
2027
2028 # ------------------------------------------------------------------------------
2029
2030 /**
2031 * Helper class for file movement
2032 * @ingroup FileRepo
2033 */
2034 class LocalFileMoveBatch {
2035 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
2036
2037 function __construct( File $file, Title $target ) {
2038 $this->file = $file;
2039 $this->target = $target;
2040 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2041 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2042 $this->oldName = $this->file->getName();
2043 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2044 $this->oldRel = $this->oldHash . $this->oldName;
2045 $this->newRel = $this->newHash . $this->newName;
2046 $this->db = $file->repo->getMasterDb();
2047 }
2048
2049 /**
2050 * Add the current image to the batch
2051 */
2052 function addCurrent() {
2053 $this->cur = array( $this->oldRel, $this->newRel );
2054 }
2055
2056 /**
2057 * Add the old versions of the image to the batch
2058 */
2059 function addOlds() {
2060 $archiveBase = 'archive';
2061 $this->olds = array();
2062 $this->oldCount = 0;
2063
2064 $result = $this->db->select( 'oldimage',
2065 array( 'oi_archive_name', 'oi_deleted' ),
2066 array( 'oi_name' => $this->oldName ),
2067 __METHOD__
2068 );
2069
2070 foreach ( $result as $row ) {
2071 $oldName = $row->oi_archive_name;
2072 $bits = explode( '!', $oldName, 2 );
2073
2074 if ( count( $bits ) != 2 ) {
2075 wfDebug( "Old file name missing !: '$oldName' \n" );
2076 continue;
2077 }
2078
2079 list( $timestamp, $filename ) = $bits;
2080
2081 if ( $this->oldName != $filename ) {
2082 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2083 continue;
2084 }
2085
2086 $this->oldCount++;
2087
2088 // Do we want to add those to oldCount?
2089 if ( $row->oi_deleted & File::DELETED_FILE ) {
2090 continue;
2091 }
2092
2093 $this->olds[] = array(
2094 "{$archiveBase}/{$this->oldHash}{$oldName}",
2095 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2096 );
2097 }
2098 }
2099
2100 /**
2101 * Perform the move.
2102 */
2103 function execute() {
2104 $repo = $this->file->repo;
2105 $status = $repo->newGood();
2106 $triplets = $this->getMoveTriplets();
2107
2108 $triplets = $this->removeNonexistentFiles( $triplets );
2109
2110 // Copy the files into their new location
2111 $statusMove = $repo->storeBatch( $triplets );
2112 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2113 if ( !$statusMove->isGood() ) {
2114 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2115 $this->cleanupTarget( $triplets );
2116 $statusMove->ok = false;
2117 return $statusMove;
2118 }
2119
2120 $this->db->begin();
2121 $statusDb = $this->doDBUpdates();
2122 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2123 if ( !$statusDb->isGood() ) {
2124 $this->db->rollback();
2125 // Something went wrong with the DB updates, so remove the target files
2126 $this->cleanupTarget( $triplets );
2127 $statusDb->ok = false;
2128 return $statusDb;
2129 }
2130 $this->db->commit();
2131
2132 // Everything went ok, remove the source files
2133 $this->cleanupSource( $triplets );
2134
2135 $status->merge( $statusDb );
2136 $status->merge( $statusMove );
2137
2138 return $status;
2139 }
2140
2141 /**
2142 * Do the database updates and return a new FileRepoStatus indicating how
2143 * many rows where updated.
2144 *
2145 * @return FileRepoStatus
2146 */
2147 function doDBUpdates() {
2148 $repo = $this->file->repo;
2149 $status = $repo->newGood();
2150 $dbw = $this->db;
2151
2152 // Update current image
2153 $dbw->update(
2154 'image',
2155 array( 'img_name' => $this->newName ),
2156 array( 'img_name' => $this->oldName ),
2157 __METHOD__
2158 );
2159
2160 if ( $dbw->affectedRows() ) {
2161 $status->successCount++;
2162 } else {
2163 $status->failCount++;
2164 $status->fatal( 'imageinvalidfilename' );
2165 return $status;
2166 }
2167
2168 // Update old images
2169 $dbw->update(
2170 'oldimage',
2171 array(
2172 'oi_name' => $this->newName,
2173 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2174 ),
2175 array( 'oi_name' => $this->oldName ),
2176 __METHOD__
2177 );
2178
2179 $affected = $dbw->affectedRows();
2180 $total = $this->oldCount;
2181 $status->successCount += $affected;
2182 $status->failCount += $total - $affected;
2183 if ( $status->failCount ) {
2184 $status->error( 'imageinvalidfilename' );
2185 }
2186
2187 return $status;
2188 }
2189
2190 /**
2191 * Generate triplets for FSRepo::storeBatch().
2192 */
2193 function getMoveTriplets() {
2194 $moves = array_merge( array( $this->cur ), $this->olds );
2195 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2196
2197 foreach ( $moves as $move ) {
2198 // $move: (oldRelativePath, newRelativePath)
2199 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2200 $triplets[] = array( $srcUrl, 'public', $move[1] );
2201 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2202 }
2203
2204 return $triplets;
2205 }
2206
2207 /**
2208 * Removes non-existent files from move batch.
2209 */
2210 function removeNonexistentFiles( $triplets ) {
2211 $files = array();
2212
2213 foreach ( $triplets as $file ) {
2214 $files[$file[0]] = $file[0];
2215 }
2216
2217 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
2218 $filteredTriplets = array();
2219
2220 foreach ( $triplets as $file ) {
2221 if ( $result[$file[0]] ) {
2222 $filteredTriplets[] = $file;
2223 } else {
2224 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2225 }
2226 }
2227
2228 return $filteredTriplets;
2229 }
2230
2231 /**
2232 * Cleanup a partially moved array of triplets by deleting the target
2233 * files. Called if something went wrong half way.
2234 */
2235 function cleanupTarget( $triplets ) {
2236 // Create dest pairs from the triplets
2237 $pairs = array();
2238 foreach ( $triplets as $triplet ) {
2239 $pairs[] = array( $triplet[1], $triplet[2] );
2240 }
2241
2242 $this->file->repo->cleanupBatch( $pairs );
2243 }
2244
2245 /**
2246 * Cleanup a fully moved array of triplets by deleting the source files.
2247 * Called at the end of the move process if everything else went ok.
2248 */
2249 function cleanupSource( $triplets ) {
2250 // Create source file names from the triplets
2251 $files = array();
2252 foreach ( $triplets as $triplet ) {
2253 $files[] = $triplet[0];
2254 }
2255
2256 $this->file->repo->cleanupBatch( $files );
2257 }
2258 }