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