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