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