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