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