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