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