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