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