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