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