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