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