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