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