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