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