Merge "tests related to API block action and its gettoken"
[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() );
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 ) ) {
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',
1448 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1449 }
1450
1451 /**
1452 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1453 * the transaction and thereby releases the image lock.
1454 */
1455 function unlock() {
1456 if ( $this->locked ) {
1457 --$this->locked;
1458 if ( !$this->locked ) {
1459 $dbw = $this->repo->getMasterDB();
1460 $dbw->commit( __METHOD__ );
1461 }
1462 }
1463 }
1464
1465 /**
1466 * Roll back the DB transaction and mark the image unlocked
1467 */
1468 function unlockAndRollback() {
1469 $this->locked = false;
1470 $dbw = $this->repo->getMasterDB();
1471 $dbw->rollback( __METHOD__ );
1472 }
1473
1474 /**
1475 * @return Status
1476 */
1477 protected function readOnlyFatalStatus() {
1478 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1479 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1480 }
1481 } // LocalFile class
1482
1483 # ------------------------------------------------------------------------------
1484
1485 /**
1486 * Helper class for file deletion
1487 * @ingroup FileAbstraction
1488 */
1489 class LocalFileDeleteBatch {
1490
1491 /**
1492 * @var LocalFile
1493 */
1494 var $file;
1495
1496 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1497 var $status;
1498
1499 function __construct( File $file, $reason = '', $suppress = false ) {
1500 $this->file = $file;
1501 $this->reason = $reason;
1502 $this->suppress = $suppress;
1503 $this->status = $file->repo->newGood();
1504 }
1505
1506 function addCurrent() {
1507 $this->srcRels['.'] = $this->file->getRel();
1508 }
1509
1510 function addOld( $oldName ) {
1511 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1512 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1513 }
1514
1515 function getOldRels() {
1516 if ( !isset( $this->srcRels['.'] ) ) {
1517 $oldRels =& $this->srcRels;
1518 $deleteCurrent = false;
1519 } else {
1520 $oldRels = $this->srcRels;
1521 unset( $oldRels['.'] );
1522 $deleteCurrent = true;
1523 }
1524
1525 return array( $oldRels, $deleteCurrent );
1526 }
1527
1528 protected function getHashes() {
1529 $hashes = array();
1530 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1531
1532 if ( $deleteCurrent ) {
1533 $hashes['.'] = $this->file->getSha1();
1534 }
1535
1536 if ( count( $oldRels ) ) {
1537 $dbw = $this->file->repo->getMasterDB();
1538 $res = $dbw->select(
1539 'oldimage',
1540 array( 'oi_archive_name', 'oi_sha1' ),
1541 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1542 __METHOD__
1543 );
1544
1545 foreach ( $res as $row ) {
1546 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1547 // Get the hash from the file
1548 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1549 $props = $this->file->repo->getFileProps( $oldUrl );
1550
1551 if ( $props['fileExists'] ) {
1552 // Upgrade the oldimage row
1553 $dbw->update( 'oldimage',
1554 array( 'oi_sha1' => $props['sha1'] ),
1555 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1556 __METHOD__ );
1557 $hashes[$row->oi_archive_name] = $props['sha1'];
1558 } else {
1559 $hashes[$row->oi_archive_name] = false;
1560 }
1561 } else {
1562 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1563 }
1564 }
1565 }
1566
1567 $missing = array_diff_key( $this->srcRels, $hashes );
1568
1569 foreach ( $missing as $name => $rel ) {
1570 $this->status->error( 'filedelete-old-unregistered', $name );
1571 }
1572
1573 foreach ( $hashes as $name => $hash ) {
1574 if ( !$hash ) {
1575 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1576 unset( $hashes[$name] );
1577 }
1578 }
1579
1580 return $hashes;
1581 }
1582
1583 function doDBInserts() {
1584 global $wgUser;
1585
1586 $dbw = $this->file->repo->getMasterDB();
1587 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1588 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1589 $encReason = $dbw->addQuotes( $this->reason );
1590 $encGroup = $dbw->addQuotes( 'deleted' );
1591 $ext = $this->file->getExtension();
1592 $dotExt = $ext === '' ? '' : ".$ext";
1593 $encExt = $dbw->addQuotes( $dotExt );
1594 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1595
1596 // Bitfields to further suppress the content
1597 if ( $this->suppress ) {
1598 $bitfield = 0;
1599 // This should be 15...
1600 $bitfield |= Revision::DELETED_TEXT;
1601 $bitfield |= Revision::DELETED_COMMENT;
1602 $bitfield |= Revision::DELETED_USER;
1603 $bitfield |= Revision::DELETED_RESTRICTED;
1604 } else {
1605 $bitfield = 'oi_deleted';
1606 }
1607
1608 if ( $deleteCurrent ) {
1609 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1610 $where = array( 'img_name' => $this->file->getName() );
1611 $dbw->insertSelect( 'filearchive', 'image',
1612 array(
1613 'fa_storage_group' => $encGroup,
1614 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1615 'fa_deleted_user' => $encUserId,
1616 'fa_deleted_timestamp' => $encTimestamp,
1617 'fa_deleted_reason' => $encReason,
1618 'fa_deleted' => $this->suppress ? $bitfield : 0,
1619
1620 'fa_name' => 'img_name',
1621 'fa_archive_name' => 'NULL',
1622 'fa_size' => 'img_size',
1623 'fa_width' => 'img_width',
1624 'fa_height' => 'img_height',
1625 'fa_metadata' => 'img_metadata',
1626 'fa_bits' => 'img_bits',
1627 'fa_media_type' => 'img_media_type',
1628 'fa_major_mime' => 'img_major_mime',
1629 'fa_minor_mime' => 'img_minor_mime',
1630 'fa_description' => 'img_description',
1631 'fa_user' => 'img_user',
1632 'fa_user_text' => 'img_user_text',
1633 'fa_timestamp' => 'img_timestamp'
1634 ), $where, __METHOD__ );
1635 }
1636
1637 if ( count( $oldRels ) ) {
1638 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1639 $where = array(
1640 'oi_name' => $this->file->getName(),
1641 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1642 $dbw->insertSelect( 'filearchive', 'oldimage',
1643 array(
1644 'fa_storage_group' => $encGroup,
1645 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1646 'fa_deleted_user' => $encUserId,
1647 'fa_deleted_timestamp' => $encTimestamp,
1648 'fa_deleted_reason' => $encReason,
1649 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1650
1651 'fa_name' => 'oi_name',
1652 'fa_archive_name' => 'oi_archive_name',
1653 'fa_size' => 'oi_size',
1654 'fa_width' => 'oi_width',
1655 'fa_height' => 'oi_height',
1656 'fa_metadata' => 'oi_metadata',
1657 'fa_bits' => 'oi_bits',
1658 'fa_media_type' => 'oi_media_type',
1659 'fa_major_mime' => 'oi_major_mime',
1660 'fa_minor_mime' => 'oi_minor_mime',
1661 'fa_description' => 'oi_description',
1662 'fa_user' => 'oi_user',
1663 'fa_user_text' => 'oi_user_text',
1664 'fa_timestamp' => 'oi_timestamp',
1665 'fa_deleted' => $bitfield
1666 ), $where, __METHOD__ );
1667 }
1668 }
1669
1670 function doDBDeletes() {
1671 $dbw = $this->file->repo->getMasterDB();
1672 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1673
1674 if ( count( $oldRels ) ) {
1675 $dbw->delete( 'oldimage',
1676 array(
1677 'oi_name' => $this->file->getName(),
1678 'oi_archive_name' => array_keys( $oldRels )
1679 ), __METHOD__ );
1680 }
1681
1682 if ( $deleteCurrent ) {
1683 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1684 }
1685 }
1686
1687 /**
1688 * Run the transaction
1689 * @return FileRepoStatus
1690 */
1691 function execute() {
1692 global $wgUseSquid;
1693 wfProfileIn( __METHOD__ );
1694
1695 $this->file->lock();
1696 // Leave private files alone
1697 $privateFiles = array();
1698 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1699 $dbw = $this->file->repo->getMasterDB();
1700
1701 if ( !empty( $oldRels ) ) {
1702 $res = $dbw->select( 'oldimage',
1703 array( 'oi_archive_name' ),
1704 array( 'oi_name' => $this->file->getName(),
1705 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1706 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1707 __METHOD__ );
1708
1709 foreach ( $res as $row ) {
1710 $privateFiles[$row->oi_archive_name] = 1;
1711 }
1712 }
1713 // Prepare deletion batch
1714 $hashes = $this->getHashes();
1715 $this->deletionBatch = array();
1716 $ext = $this->file->getExtension();
1717 $dotExt = $ext === '' ? '' : ".$ext";
1718
1719 foreach ( $this->srcRels as $name => $srcRel ) {
1720 // Skip files that have no hash (missing source).
1721 // Keep private files where they are.
1722 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1723 $hash = $hashes[$name];
1724 $key = $hash . $dotExt;
1725 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1726 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1727 }
1728 }
1729
1730 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1731 // We acquire this lock by running the inserts now, before the file operations.
1732 //
1733 // This potentially has poor lock contention characteristics -- an alternative
1734 // scheme would be to insert stub filearchive entries with no fa_name and commit
1735 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1736 $this->doDBInserts();
1737
1738 // Removes non-existent file from the batch, so we don't get errors.
1739 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1740
1741 // Execute the file deletion batch
1742 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1743
1744 if ( !$status->isGood() ) {
1745 $this->status->merge( $status );
1746 }
1747
1748 if ( !$this->status->isOK() ) {
1749 // Critical file deletion error
1750 // Roll back inserts, release lock and abort
1751 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1752 $this->file->unlockAndRollback();
1753 wfProfileOut( __METHOD__ );
1754 return $this->status;
1755 }
1756
1757 // Purge squid
1758 if ( $wgUseSquid ) {
1759 $urls = array();
1760
1761 foreach ( $this->srcRels as $srcRel ) {
1762 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1763 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1764 }
1765 SquidUpdate::purge( $urls );
1766 }
1767
1768 // Delete image/oldimage rows
1769 $this->doDBDeletes();
1770
1771 // Commit and return
1772 $this->file->unlock();
1773 wfProfileOut( __METHOD__ );
1774
1775 return $this->status;
1776 }
1777
1778 /**
1779 * Removes non-existent files from a deletion batch.
1780 * @return array
1781 */
1782 function removeNonexistentFiles( $batch ) {
1783 $files = $newBatch = array();
1784
1785 foreach ( $batch as $batchItem ) {
1786 list( $src, $dest ) = $batchItem;
1787 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1788 }
1789
1790 $result = $this->file->repo->fileExistsBatch( $files );
1791
1792 foreach ( $batch as $batchItem ) {
1793 if ( $result[$batchItem[0]] ) {
1794 $newBatch[] = $batchItem;
1795 }
1796 }
1797
1798 return $newBatch;
1799 }
1800 }
1801
1802 # ------------------------------------------------------------------------------
1803
1804 /**
1805 * Helper class for file undeletion
1806 * @ingroup FileAbstraction
1807 */
1808 class LocalFileRestoreBatch {
1809 /**
1810 * @var LocalFile
1811 */
1812 var $file;
1813
1814 var $cleanupBatch, $ids, $all, $unsuppress = false;
1815
1816 function __construct( File $file, $unsuppress = false ) {
1817 $this->file = $file;
1818 $this->cleanupBatch = $this->ids = array();
1819 $this->ids = array();
1820 $this->unsuppress = $unsuppress;
1821 }
1822
1823 /**
1824 * Add a file by ID
1825 */
1826 function addId( $fa_id ) {
1827 $this->ids[] = $fa_id;
1828 }
1829
1830 /**
1831 * Add a whole lot of files by ID
1832 */
1833 function addIds( $ids ) {
1834 $this->ids = array_merge( $this->ids, $ids );
1835 }
1836
1837 /**
1838 * Add all revisions of the file
1839 */
1840 function addAll() {
1841 $this->all = true;
1842 }
1843
1844 /**
1845 * Run the transaction, except the cleanup batch.
1846 * The cleanup batch should be run in a separate transaction, because it locks different
1847 * rows and there's no need to keep the image row locked while it's acquiring those locks
1848 * The caller may have its own transaction open.
1849 * So we save the batch and let the caller call cleanup()
1850 * @return FileRepoStatus
1851 */
1852 function execute() {
1853 global $wgLang;
1854
1855 if ( !$this->all && !$this->ids ) {
1856 // Do nothing
1857 return $this->file->repo->newGood();
1858 }
1859
1860 $exists = $this->file->lock();
1861 $dbw = $this->file->repo->getMasterDB();
1862 $status = $this->file->repo->newGood();
1863
1864 // Fetch all or selected archived revisions for the file,
1865 // sorted from the most recent to the oldest.
1866 $conditions = array( 'fa_name' => $this->file->getName() );
1867
1868 if ( !$this->all ) {
1869 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1870 }
1871
1872 $result = $dbw->select( 'filearchive', '*',
1873 $conditions,
1874 __METHOD__,
1875 array( 'ORDER BY' => 'fa_timestamp DESC' )
1876 );
1877
1878 $idsPresent = array();
1879 $storeBatch = array();
1880 $insertBatch = array();
1881 $insertCurrent = false;
1882 $deleteIds = array();
1883 $first = true;
1884 $archiveNames = array();
1885
1886 foreach ( $result as $row ) {
1887 $idsPresent[] = $row->fa_id;
1888
1889 if ( $row->fa_name != $this->file->getName() ) {
1890 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1891 $status->failCount++;
1892 continue;
1893 }
1894
1895 if ( $row->fa_storage_key == '' ) {
1896 // Revision was missing pre-deletion
1897 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1898 $status->failCount++;
1899 continue;
1900 }
1901
1902 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1903 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1904
1905 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1906
1907 # Fix leading zero
1908 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1909 $sha1 = substr( $sha1, 1 );
1910 }
1911
1912 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1913 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1914 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1915 || is_null( $row->fa_metadata ) ) {
1916 // Refresh our metadata
1917 // Required for a new current revision; nice for older ones too. :)
1918 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1919 } else {
1920 $props = array(
1921 'minor_mime' => $row->fa_minor_mime,
1922 'major_mime' => $row->fa_major_mime,
1923 'media_type' => $row->fa_media_type,
1924 'metadata' => $row->fa_metadata
1925 );
1926 }
1927
1928 if ( $first && !$exists ) {
1929 // This revision will be published as the new current version
1930 $destRel = $this->file->getRel();
1931 $insertCurrent = array(
1932 'img_name' => $row->fa_name,
1933 'img_size' => $row->fa_size,
1934 'img_width' => $row->fa_width,
1935 'img_height' => $row->fa_height,
1936 'img_metadata' => $props['metadata'],
1937 'img_bits' => $row->fa_bits,
1938 'img_media_type' => $props['media_type'],
1939 'img_major_mime' => $props['major_mime'],
1940 'img_minor_mime' => $props['minor_mime'],
1941 'img_description' => $row->fa_description,
1942 'img_user' => $row->fa_user,
1943 'img_user_text' => $row->fa_user_text,
1944 'img_timestamp' => $row->fa_timestamp,
1945 'img_sha1' => $sha1
1946 );
1947
1948 // The live (current) version cannot be hidden!
1949 if ( !$this->unsuppress && $row->fa_deleted ) {
1950 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1951 $this->cleanupBatch[] = $row->fa_storage_key;
1952 }
1953 } else {
1954 $archiveName = $row->fa_archive_name;
1955
1956 if ( $archiveName == '' ) {
1957 // This was originally a current version; we
1958 // have to devise a new archive name for it.
1959 // Format is <timestamp of archiving>!<name>
1960 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1961
1962 do {
1963 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1964 $timestamp++;
1965 } while ( isset( $archiveNames[$archiveName] ) );
1966 }
1967
1968 $archiveNames[$archiveName] = true;
1969 $destRel = $this->file->getArchiveRel( $archiveName );
1970 $insertBatch[] = array(
1971 'oi_name' => $row->fa_name,
1972 'oi_archive_name' => $archiveName,
1973 'oi_size' => $row->fa_size,
1974 'oi_width' => $row->fa_width,
1975 'oi_height' => $row->fa_height,
1976 'oi_bits' => $row->fa_bits,
1977 'oi_description' => $row->fa_description,
1978 'oi_user' => $row->fa_user,
1979 'oi_user_text' => $row->fa_user_text,
1980 'oi_timestamp' => $row->fa_timestamp,
1981 'oi_metadata' => $props['metadata'],
1982 'oi_media_type' => $props['media_type'],
1983 'oi_major_mime' => $props['major_mime'],
1984 'oi_minor_mime' => $props['minor_mime'],
1985 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1986 'oi_sha1' => $sha1 );
1987 }
1988
1989 $deleteIds[] = $row->fa_id;
1990
1991 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1992 // private files can stay where they are
1993 $status->successCount++;
1994 } else {
1995 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1996 $this->cleanupBatch[] = $row->fa_storage_key;
1997 }
1998
1999 $first = false;
2000 }
2001
2002 unset( $result );
2003
2004 // Add a warning to the status object for missing IDs
2005 $missingIds = array_diff( $this->ids, $idsPresent );
2006
2007 foreach ( $missingIds as $id ) {
2008 $status->error( 'undelete-missing-filearchive', $id );
2009 }
2010
2011 // Remove missing files from batch, so we don't get errors when undeleting them
2012 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2013
2014 // Run the store batch
2015 // Use the OVERWRITE_SAME flag to smooth over a common error
2016 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2017 $status->merge( $storeStatus );
2018
2019 if ( !$status->isGood() ) {
2020 // Even if some files could be copied, fail entirely as that is the
2021 // easiest thing to do without data loss
2022 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2023 $status->ok = false;
2024 $this->file->unlock();
2025
2026 return $status;
2027 }
2028
2029 // Run the DB updates
2030 // Because we have locked the image row, key conflicts should be rare.
2031 // If they do occur, we can roll back the transaction at this time with
2032 // no data loss, but leaving unregistered files scattered throughout the
2033 // public zone.
2034 // This is not ideal, which is why it's important to lock the image row.
2035 if ( $insertCurrent ) {
2036 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2037 }
2038
2039 if ( $insertBatch ) {
2040 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2041 }
2042
2043 if ( $deleteIds ) {
2044 $dbw->delete( 'filearchive',
2045 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2046 __METHOD__ );
2047 }
2048
2049 // If store batch is empty (all files are missing), deletion is to be considered successful
2050 if ( $status->successCount > 0 || !$storeBatch ) {
2051 if ( !$exists ) {
2052 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2053
2054 // Update site_stats
2055 $site_stats = $dbw->tableName( 'site_stats' );
2056 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2057
2058 $this->file->purgeEverything();
2059 } else {
2060 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2061 $this->file->purgeDescription();
2062 $this->file->purgeHistory();
2063 }
2064 }
2065
2066 $this->file->unlock();
2067
2068 return $status;
2069 }
2070
2071 /**
2072 * Removes non-existent files from a store batch.
2073 * @return array
2074 */
2075 function removeNonexistentFiles( $triplets ) {
2076 $files = $filteredTriplets = array();
2077 foreach ( $triplets as $file )
2078 $files[$file[0]] = $file[0];
2079
2080 $result = $this->file->repo->fileExistsBatch( $files );
2081
2082 foreach ( $triplets as $file ) {
2083 if ( $result[$file[0]] ) {
2084 $filteredTriplets[] = $file;
2085 }
2086 }
2087
2088 return $filteredTriplets;
2089 }
2090
2091 /**
2092 * Removes non-existent files from a cleanup batch.
2093 * @return array
2094 */
2095 function removeNonexistentFromCleanup( $batch ) {
2096 $files = $newBatch = array();
2097 $repo = $this->file->repo;
2098
2099 foreach ( $batch as $file ) {
2100 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2101 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2102 }
2103
2104 $result = $repo->fileExistsBatch( $files );
2105
2106 foreach ( $batch as $file ) {
2107 if ( $result[$file] ) {
2108 $newBatch[] = $file;
2109 }
2110 }
2111
2112 return $newBatch;
2113 }
2114
2115 /**
2116 * Delete unused files in the deleted zone.
2117 * This should be called from outside the transaction in which execute() was called.
2118 * @return FileRepoStatus|void
2119 */
2120 function cleanup() {
2121 if ( !$this->cleanupBatch ) {
2122 return $this->file->repo->newGood();
2123 }
2124
2125 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2126
2127 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2128
2129 return $status;
2130 }
2131
2132 /**
2133 * Cleanup a failed batch. The batch was only partially successful, so
2134 * rollback by removing all items that were succesfully copied.
2135 *
2136 * @param Status $storeStatus
2137 * @param array $storeBatch
2138 */
2139 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2140 $cleanupBatch = array();
2141
2142 foreach ( $storeStatus->success as $i => $success ) {
2143 // Check if this item of the batch was successfully copied
2144 if ( $success ) {
2145 // Item was successfully copied and needs to be removed again
2146 // Extract ($dstZone, $dstRel) from the batch
2147 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2148 }
2149 }
2150 $this->file->repo->cleanupBatch( $cleanupBatch );
2151 }
2152 }
2153
2154 # ------------------------------------------------------------------------------
2155
2156 /**
2157 * Helper class for file movement
2158 * @ingroup FileAbstraction
2159 */
2160 class LocalFileMoveBatch {
2161
2162 /**
2163 * @var File
2164 */
2165 var $file;
2166
2167 /**
2168 * @var Title
2169 */
2170 var $target;
2171
2172 var $cur, $olds, $oldCount, $archive, $db;
2173
2174 function __construct( File $file, Title $target ) {
2175 $this->file = $file;
2176 $this->target = $target;
2177 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2178 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2179 $this->oldName = $this->file->getName();
2180 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2181 $this->oldRel = $this->oldHash . $this->oldName;
2182 $this->newRel = $this->newHash . $this->newName;
2183 $this->db = $file->repo->getMasterDb();
2184 }
2185
2186 /**
2187 * Add the current image to the batch
2188 */
2189 function addCurrent() {
2190 $this->cur = array( $this->oldRel, $this->newRel );
2191 }
2192
2193 /**
2194 * Add the old versions of the image to the batch
2195 */
2196 function addOlds() {
2197 $archiveBase = 'archive';
2198 $this->olds = array();
2199 $this->oldCount = 0;
2200
2201 $result = $this->db->select( 'oldimage',
2202 array( 'oi_archive_name', 'oi_deleted' ),
2203 array( 'oi_name' => $this->oldName ),
2204 __METHOD__
2205 );
2206
2207 foreach ( $result as $row ) {
2208 $oldName = $row->oi_archive_name;
2209 $bits = explode( '!', $oldName, 2 );
2210
2211 if ( count( $bits ) != 2 ) {
2212 wfDebug( "Old file name missing !: '$oldName' \n" );
2213 continue;
2214 }
2215
2216 list( $timestamp, $filename ) = $bits;
2217
2218 if ( $this->oldName != $filename ) {
2219 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2220 continue;
2221 }
2222
2223 $this->oldCount++;
2224
2225 // Do we want to add those to oldCount?
2226 if ( $row->oi_deleted & File::DELETED_FILE ) {
2227 continue;
2228 }
2229
2230 $this->olds[] = array(
2231 "{$archiveBase}/{$this->oldHash}{$oldName}",
2232 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2233 );
2234 }
2235 }
2236
2237 /**
2238 * Perform the move.
2239 * @return FileRepoStatus
2240 */
2241 function execute() {
2242 $repo = $this->file->repo;
2243 $status = $repo->newGood();
2244 $triplets = $this->getMoveTriplets();
2245
2246 $triplets = $this->removeNonexistentFiles( $triplets );
2247
2248 // Copy the files into their new location
2249 $statusMove = $repo->storeBatch( $triplets );
2250 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2251 if ( !$statusMove->isGood() ) {
2252 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2253 $this->cleanupTarget( $triplets );
2254 $statusMove->ok = false;
2255 return $statusMove;
2256 }
2257
2258 $this->db->begin( __METHOD__ );
2259 $statusDb = $this->doDBUpdates();
2260 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2261 if ( !$statusDb->isGood() ) {
2262 $this->db->rollback( __METHOD__ );
2263 // Something went wrong with the DB updates, so remove the target files
2264 $this->cleanupTarget( $triplets );
2265 $statusDb->ok = false;
2266 return $statusDb;
2267 }
2268 $this->db->commit( __METHOD__ );
2269
2270 // Everything went ok, remove the source files
2271 $this->cleanupSource( $triplets );
2272
2273 $status->merge( $statusDb );
2274 $status->merge( $statusMove );
2275
2276 return $status;
2277 }
2278
2279 /**
2280 * Do the database updates and return a new FileRepoStatus indicating how
2281 * many rows where updated.
2282 *
2283 * @return FileRepoStatus
2284 */
2285 function doDBUpdates() {
2286 $repo = $this->file->repo;
2287 $status = $repo->newGood();
2288 $dbw = $this->db;
2289
2290 // Update current image
2291 $dbw->update(
2292 'image',
2293 array( 'img_name' => $this->newName ),
2294 array( 'img_name' => $this->oldName ),
2295 __METHOD__
2296 );
2297
2298 if ( $dbw->affectedRows() ) {
2299 $status->successCount++;
2300 } else {
2301 $status->failCount++;
2302 $status->fatal( 'imageinvalidfilename' );
2303 return $status;
2304 }
2305
2306 // Update old images
2307 $dbw->update(
2308 'oldimage',
2309 array(
2310 'oi_name' => $this->newName,
2311 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2312 ),
2313 array( 'oi_name' => $this->oldName ),
2314 __METHOD__
2315 );
2316
2317 $affected = $dbw->affectedRows();
2318 $total = $this->oldCount;
2319 $status->successCount += $affected;
2320 $status->failCount += $total - $affected;
2321 if ( $status->failCount ) {
2322 $status->error( 'imageinvalidfilename' );
2323 }
2324
2325 return $status;
2326 }
2327
2328 /**
2329 * Generate triplets for FileRepo::storeBatch().
2330 * @return array
2331 */
2332 function getMoveTriplets() {
2333 $moves = array_merge( array( $this->cur ), $this->olds );
2334 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2335
2336 foreach ( $moves as $move ) {
2337 // $move: (oldRelativePath, newRelativePath)
2338 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2339 $triplets[] = array( $srcUrl, 'public', $move[1] );
2340 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2341 }
2342
2343 return $triplets;
2344 }
2345
2346 /**
2347 * Removes non-existent files from move batch.
2348 * @return array
2349 */
2350 function removeNonexistentFiles( $triplets ) {
2351 $files = array();
2352
2353 foreach ( $triplets as $file ) {
2354 $files[$file[0]] = $file[0];
2355 }
2356
2357 $result = $this->file->repo->fileExistsBatch( $files );
2358 $filteredTriplets = array();
2359
2360 foreach ( $triplets as $file ) {
2361 if ( $result[$file[0]] ) {
2362 $filteredTriplets[] = $file;
2363 } else {
2364 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2365 }
2366 }
2367
2368 return $filteredTriplets;
2369 }
2370
2371 /**
2372 * Cleanup a partially moved array of triplets by deleting the target
2373 * files. Called if something went wrong half way.
2374 */
2375 function cleanupTarget( $triplets ) {
2376 // Create dest pairs from the triplets
2377 $pairs = array();
2378 foreach ( $triplets as $triplet ) {
2379 $pairs[] = array( $triplet[1], $triplet[2] );
2380 }
2381
2382 $this->file->repo->cleanupBatch( $pairs );
2383 }
2384
2385 /**
2386 * Cleanup a fully moved array of triplets by deleting the source files.
2387 * Called at the end of the move process if everything else went ok.
2388 */
2389 function cleanupSource( $triplets ) {
2390 // Create source file names from the triplets
2391 $files = array();
2392 foreach ( $triplets as $triplet ) {
2393 $files[] = $triplet[0];
2394 }
2395
2396 $this->file->repo->cleanupBatch( $files );
2397 }
2398 }