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