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