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