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