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