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