Stop calling FileRepo->streamFile()
[lhc/web/wiklou.git] / includes / Revision.php
1 <?php
2 /**
3 * Representation of a page version.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Revision\MutableRevisionRecord;
24 use MediaWiki\Revision\RevisionAccessException;
25 use MediaWiki\Revision\RevisionFactory;
26 use MediaWiki\Revision\RevisionLookup;
27 use MediaWiki\Revision\RevisionRecord;
28 use MediaWiki\Revision\RevisionStore;
29 use MediaWiki\Revision\RevisionStoreRecord;
30 use MediaWiki\Revision\SlotRecord;
31 use MediaWiki\Storage\SqlBlobStore;
32 use Wikimedia\Assert\Assert;
33 use Wikimedia\Rdbms\IDatabase;
34 use MediaWiki\Linker\LinkTarget;
35 use MediaWiki\MediaWikiServices;
36
37 /**
38 * @deprecated since 1.31, use RevisionRecord, RevisionStore, and BlobStore instead.
39 */
40 class Revision implements IDBAccessObject {
41
42 /** @var RevisionRecord */
43 protected $mRecord;
44
45 // Revision deletion constants
46 const DELETED_TEXT = RevisionRecord::DELETED_TEXT;
47 const DELETED_COMMENT = RevisionRecord::DELETED_COMMENT;
48 const DELETED_USER = RevisionRecord::DELETED_USER;
49 const DELETED_RESTRICTED = RevisionRecord::DELETED_RESTRICTED;
50 const SUPPRESSED_USER = RevisionRecord::SUPPRESSED_USER;
51 const SUPPRESSED_ALL = RevisionRecord::SUPPRESSED_ALL;
52
53 // Audience options for accessors
54 const FOR_PUBLIC = RevisionRecord::FOR_PUBLIC;
55 const FOR_THIS_USER = RevisionRecord::FOR_THIS_USER;
56 const RAW = RevisionRecord::RAW;
57
58 const TEXT_CACHE_GROUP = SqlBlobStore::TEXT_CACHE_GROUP;
59
60 /**
61 * @return RevisionStore
62 */
63 protected static function getRevisionStore( $wiki = false ) {
64 if ( $wiki ) {
65 return MediaWikiServices::getInstance()->getRevisionStoreFactory()
66 ->getRevisionStore( $wiki );
67 } else {
68 return MediaWikiServices::getInstance()->getRevisionStore();
69 }
70 }
71
72 /**
73 * @return RevisionLookup
74 */
75 protected static function getRevisionLookup() {
76 return MediaWikiServices::getInstance()->getRevisionLookup();
77 }
78
79 /**
80 * @return RevisionFactory
81 */
82 protected static function getRevisionFactory() {
83 return MediaWikiServices::getInstance()->getRevisionFactory();
84 }
85
86 /**
87 * @param bool|string $wiki The ID of the target wiki database. Use false for the local wiki.
88 *
89 * @return SqlBlobStore
90 */
91 protected static function getBlobStore( $wiki = false ) {
92 $store = MediaWikiServices::getInstance()
93 ->getBlobStoreFactory()
94 ->newSqlBlobStore( $wiki );
95
96 if ( !$store instanceof SqlBlobStore ) {
97 throw new RuntimeException(
98 'The backwards compatibility code in Revision currently requires the BlobStore '
99 . 'service to be an SqlBlobStore instance, but it is a ' . get_class( $store )
100 );
101 }
102
103 return $store;
104 }
105
106 /**
107 * Load a page revision from a given revision ID number.
108 * Returns null if no such revision can be found.
109 *
110 * $flags include:
111 * Revision::READ_LATEST : Select the data from the master
112 * Revision::READ_LOCKING : Select & lock the data from the master
113 *
114 * @param int $id
115 * @param int $flags (optional)
116 * @return Revision|null
117 */
118 public static function newFromId( $id, $flags = 0 ) {
119 $rec = self::getRevisionLookup()->getRevisionById( $id, $flags );
120 return $rec ? new Revision( $rec, $flags ) : null;
121 }
122
123 /**
124 * Load either the current, or a specified, revision
125 * that's attached to a given link target. If not attached
126 * to that link target, will return null.
127 *
128 * $flags include:
129 * Revision::READ_LATEST : Select the data from the master
130 * Revision::READ_LOCKING : Select & lock the data from the master
131 *
132 * @param LinkTarget $linkTarget
133 * @param int $id (optional)
134 * @param int $flags Bitfield (optional)
135 * @return Revision|null
136 */
137 public static function newFromTitle( LinkTarget $linkTarget, $id = 0, $flags = 0 ) {
138 $rec = self::getRevisionLookup()->getRevisionByTitle( $linkTarget, $id, $flags );
139 return $rec ? new Revision( $rec, $flags ) : null;
140 }
141
142 /**
143 * Load either the current, or a specified, revision
144 * that's attached to a given page ID.
145 * Returns null if no such revision can be found.
146 *
147 * $flags include:
148 * Revision::READ_LATEST : Select the data from the master (since 1.20)
149 * Revision::READ_LOCKING : Select & lock the data from the master
150 *
151 * @param int $pageId
152 * @param int $revId (optional)
153 * @param int $flags Bitfield (optional)
154 * @return Revision|null
155 */
156 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
157 $rec = self::getRevisionLookup()->getRevisionByPageId( $pageId, $revId, $flags );
158 return $rec ? new Revision( $rec, $flags ) : null;
159 }
160
161 /**
162 * Make a fake revision object from an archive table row. This is queried
163 * for permissions or even inserted (as in Special:Undelete)
164 *
165 * @param object $row
166 * @param array $overrides
167 *
168 * @throws MWException
169 * @return Revision
170 */
171 public static function newFromArchiveRow( $row, $overrides = [] ) {
172 /**
173 * MCR Migration: https://phabricator.wikimedia.org/T183564
174 * This method used to overwrite attributes, then passed to Revision::__construct
175 * RevisionStore::newRevisionFromArchiveRow instead overrides row field names
176 * So do a conversion here.
177 */
178 if ( array_key_exists( 'page', $overrides ) ) {
179 $overrides['page_id'] = $overrides['page'];
180 unset( $overrides['page'] );
181 }
182
183 /**
184 * We require a Title for both the Revision object and the RevisionRecord.
185 * Below is duplicated logic from RevisionStore::newRevisionFromArchiveRow
186 * to fetch a title in order pass it into the Revision object.
187 */
188 $title = null;
189 if ( isset( $overrides['title'] ) ) {
190 if ( !( $overrides['title'] instanceof Title ) ) {
191 throw new MWException( 'title field override must contain a Title object.' );
192 }
193
194 $title = $overrides['title'];
195 }
196 if ( $title !== null ) {
197 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
198 $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
199 } else {
200 throw new InvalidArgumentException(
201 'A Title or ar_namespace and ar_title must be given'
202 );
203 }
204 }
205
206 $rec = self::getRevisionFactory()->newRevisionFromArchiveRow( $row, 0, $title, $overrides );
207 return new Revision( $rec, self::READ_NORMAL, $title );
208 }
209
210 /**
211 * @since 1.19
212 *
213 * MCR migration note: replaced by RevisionStore::newRevisionFromRow(). Note that
214 * newFromRow() also accepts arrays, while newRevisionFromRow() does not. Instead,
215 * a MutableRevisionRecord should be constructed directly.
216 * RevisionStore::newMutableRevisionFromArray() can be used as a temporary replacement,
217 * but should be avoided.
218 *
219 * @param object|array $row
220 * @return Revision
221 */
222 public static function newFromRow( $row ) {
223 if ( is_array( $row ) ) {
224 $rec = self::getRevisionFactory()->newMutableRevisionFromArray( $row );
225 } else {
226 $rec = self::getRevisionFactory()->newRevisionFromRow( $row );
227 }
228
229 return new Revision( $rec );
230 }
231
232 /**
233 * Load a page revision from a given revision ID number.
234 * Returns null if no such revision can be found.
235 *
236 * @deprecated since 1.31, use RevisionStore::getRevisionById() instead.
237 *
238 * @param IDatabase $db
239 * @param int $id
240 * @return Revision|null
241 */
242 public static function loadFromId( $db, $id ) {
243 wfDeprecated( __METHOD__, '1.31' ); // no known callers
244 $rec = self::getRevisionStore()->loadRevisionFromId( $db, $id );
245 return $rec ? new Revision( $rec ) : null;
246 }
247
248 /**
249 * Load either the current, or a specified, revision
250 * that's attached to a given page. If not attached
251 * to that page, will return null.
252 *
253 * @deprecated since 1.31, use RevisionStore::getRevisionByPageId() instead.
254 *
255 * @param IDatabase $db
256 * @param int $pageid
257 * @param int $id
258 * @return Revision|null
259 */
260 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
261 $rec = self::getRevisionStore()->loadRevisionFromPageId( $db, $pageid, $id );
262 return $rec ? new Revision( $rec ) : null;
263 }
264
265 /**
266 * Load either the current, or a specified, revision
267 * that's attached to a given page. If not attached
268 * to that page, will return null.
269 *
270 * @deprecated since 1.31, use RevisionStore::getRevisionByTitle() instead.
271 *
272 * @param IDatabase $db
273 * @param Title $title
274 * @param int $id
275 * @return Revision|null
276 */
277 public static function loadFromTitle( $db, $title, $id = 0 ) {
278 $rec = self::getRevisionStore()->loadRevisionFromTitle( $db, $title, $id );
279 return $rec ? new Revision( $rec ) : null;
280 }
281
282 /**
283 * Load the revision for the given title with the given timestamp.
284 * WARNING: Timestamps may in some circumstances not be unique,
285 * so this isn't the best key to use.
286 *
287 * @deprecated since 1.31, use RevisionStore::getRevisionByTimestamp()
288 * or RevisionStore::loadRevisionFromTimestamp() instead.
289 *
290 * @param IDatabase $db
291 * @param Title $title
292 * @param string $timestamp
293 * @return Revision|null
294 */
295 public static function loadFromTimestamp( $db, $title, $timestamp ) {
296 $rec = self::getRevisionStore()->loadRevisionFromTimestamp( $db, $title, $timestamp );
297 return $rec ? new Revision( $rec ) : null;
298 }
299
300 /**
301 * Return the value of a select() JOIN conds array for the user table.
302 * This will get user table rows for logged-in users.
303 * @since 1.19
304 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'user' ] ) instead.
305 * @return array
306 */
307 public static function userJoinCond() {
308 global $wgActorTableSchemaMigrationStage;
309
310 wfDeprecated( __METHOD__, '1.31' );
311 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
312 // If code is using this instead of self::getQueryInfo(), there's
313 // no way the join it's trying to do can work once the old fields
314 // aren't being used anymore.
315 throw new BadMethodCallException(
316 'Cannot use ' . __METHOD__
317 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
318 );
319 }
320
321 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
322 }
323
324 /**
325 * Return the value of a select() page conds array for the page table.
326 * This will assure that the revision(s) are not orphaned from live pages.
327 * @since 1.19
328 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'page' ] ) instead.
329 * @return array
330 */
331 public static function pageJoinCond() {
332 wfDeprecated( __METHOD__, '1.31' );
333 return [ 'JOIN', [ 'page_id = rev_page' ] ];
334 }
335
336 /**
337 * Return the list of revision fields that should be selected to create
338 * a new revision.
339 * @deprecated since 1.31, use RevisionStore::getQueryInfo() instead.
340 * @return array
341 */
342 public static function selectFields() {
343 global $wgContentHandlerUseDB, $wgActorTableSchemaMigrationStage;
344 global $wgMultiContentRevisionSchemaMigrationStage;
345
346 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
347 // If code is using this instead of self::getQueryInfo(), there's a
348 // decent chance it's going to try to directly access
349 // $row->rev_user or $row->rev_user_text and we can't give it
350 // useful values here once those aren't being used anymore.
351 throw new BadMethodCallException(
352 'Cannot use ' . __METHOD__
353 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
354 );
355 }
356
357 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
358 // If code is using this instead of self::getQueryInfo(), there's a
359 // decent chance it's going to try to directly access
360 // $row->rev_text_id or $row->rev_content_model and we can't give it
361 // useful values here once those aren't being written anymore,
362 // and may not exist at all.
363 throw new BadMethodCallException(
364 'Cannot use ' . __METHOD__ . ' when $wgMultiContentRevisionSchemaMigrationStage '
365 . 'does not have SCHEMA_COMPAT_WRITE_OLD set.'
366 );
367 }
368
369 wfDeprecated( __METHOD__, '1.31' );
370
371 $fields = [
372 'rev_id',
373 'rev_page',
374 'rev_text_id',
375 'rev_timestamp',
376 'rev_user_text',
377 'rev_user',
378 'rev_actor' => 'NULL',
379 'rev_minor_edit',
380 'rev_deleted',
381 'rev_len',
382 'rev_parent_id',
383 'rev_sha1',
384 ];
385
386 $fields += CommentStore::getStore()->getFields( 'rev_comment' );
387
388 if ( $wgContentHandlerUseDB ) {
389 $fields[] = 'rev_content_format';
390 $fields[] = 'rev_content_model';
391 }
392
393 return $fields;
394 }
395
396 /**
397 * Return the list of revision fields that should be selected to create
398 * a new revision from an archive row.
399 * @deprecated since 1.31, use RevisionStore::getArchiveQueryInfo() instead.
400 * @return array
401 */
402 public static function selectArchiveFields() {
403 global $wgContentHandlerUseDB, $wgActorTableSchemaMigrationStage;
404 global $wgMultiContentRevisionSchemaMigrationStage;
405
406 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
407 // If code is using this instead of self::getQueryInfo(), there's a
408 // decent chance it's going to try to directly access
409 // $row->ar_user or $row->ar_user_text and we can't give it
410 // useful values here once those aren't being used anymore.
411 throw new BadMethodCallException(
412 'Cannot use ' . __METHOD__
413 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
414 );
415 }
416
417 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
418 // If code is using this instead of self::getQueryInfo(), there's a
419 // decent chance it's going to try to directly access
420 // $row->ar_text_id or $row->ar_content_model and we can't give it
421 // useful values here once those aren't being written anymore,
422 // and may not exist at all.
423 throw new BadMethodCallException(
424 'Cannot use ' . __METHOD__ . ' when $wgMultiContentRevisionSchemaMigrationStage '
425 . 'does not have SCHEMA_COMPAT_WRITE_OLD set.'
426 );
427 }
428
429 wfDeprecated( __METHOD__, '1.31' );
430
431 $fields = [
432 'ar_id',
433 'ar_page_id',
434 'ar_rev_id',
435 'ar_text_id',
436 'ar_timestamp',
437 'ar_user_text',
438 'ar_user',
439 'ar_actor' => 'NULL',
440 'ar_minor_edit',
441 'ar_deleted',
442 'ar_len',
443 'ar_parent_id',
444 'ar_sha1',
445 ];
446
447 $fields += CommentStore::getStore()->getFields( 'ar_comment' );
448
449 if ( $wgContentHandlerUseDB ) {
450 $fields[] = 'ar_content_format';
451 $fields[] = 'ar_content_model';
452 }
453 return $fields;
454 }
455
456 /**
457 * Return the list of text fields that should be selected to read the
458 * revision text
459 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'text' ] ) instead.
460 * @return array
461 */
462 public static function selectTextFields() {
463 wfDeprecated( __METHOD__, '1.31' );
464 return [
465 'old_text',
466 'old_flags'
467 ];
468 }
469
470 /**
471 * Return the list of page fields that should be selected from page table
472 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'page' ] ) instead.
473 * @return array
474 */
475 public static function selectPageFields() {
476 wfDeprecated( __METHOD__, '1.31' );
477 return [
478 'page_namespace',
479 'page_title',
480 'page_id',
481 'page_latest',
482 'page_is_redirect',
483 'page_len',
484 ];
485 }
486
487 /**
488 * Return the list of user fields that should be selected from user table
489 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'user' ] ) instead.
490 * @return array
491 */
492 public static function selectUserFields() {
493 wfDeprecated( __METHOD__, '1.31' );
494 return [ 'user_name' ];
495 }
496
497 /**
498 * Return the tables, fields, and join conditions to be selected to create
499 * a new revision object.
500 * @since 1.31
501 * @deprecated since 1.31, use RevisionStore::getQueryInfo() instead.
502 * @param array $options Any combination of the following strings
503 * - 'page': Join with the page table, and select fields to identify the page
504 * - 'user': Join with the user table, and select the user name
505 * - 'text': Join with the text table, and select fields to load page text
506 * @return array With three keys:
507 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
508 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
509 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
510 */
511 public static function getQueryInfo( $options = [] ) {
512 return self::getRevisionStore()->getQueryInfo( $options );
513 }
514
515 /**
516 * Return the tables, fields, and join conditions to be selected to create
517 * a new archived revision object.
518 * @since 1.31
519 * @deprecated since 1.31, use RevisionStore::getArchiveQueryInfo() instead.
520 * @return array With three keys:
521 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
522 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
523 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
524 */
525 public static function getArchiveQueryInfo() {
526 return self::getRevisionStore()->getArchiveQueryInfo();
527 }
528
529 /**
530 * Do a batched query to get the parent revision lengths
531 *
532 * @deprecated in 1.31, use RevisionStore::getRevisionSizes instead.
533 *
534 * @param IDatabase $db
535 * @param array $revIds
536 * @return array
537 */
538 public static function getParentLengths( $db, array $revIds ) {
539 return self::getRevisionStore()->listRevisionSizes( $db, $revIds );
540 }
541
542 /**
543 * @param object|array|RevisionRecord $row Either a database row or an array
544 * @param int $queryFlags
545 * @param Title|null $title
546 *
547 * @private
548 */
549 function __construct( $row, $queryFlags = 0, Title $title = null ) {
550 global $wgUser;
551
552 if ( $row instanceof RevisionRecord ) {
553 $this->mRecord = $row;
554 } elseif ( is_array( $row ) ) {
555 // If no user is specified, fall back to using the global user object, to stay
556 // compatible with pre-1.31 behavior.
557 if ( !isset( $row['user'] ) && !isset( $row['user_text'] ) ) {
558 $row['user'] = $wgUser;
559 }
560
561 $this->mRecord = self::getRevisionFactory()->newMutableRevisionFromArray(
562 $row,
563 $queryFlags,
564 $this->ensureTitle( $row, $queryFlags, $title )
565 );
566 } elseif ( is_object( $row ) ) {
567 $this->mRecord = self::getRevisionFactory()->newRevisionFromRow(
568 $row,
569 $queryFlags,
570 $this->ensureTitle( $row, $queryFlags, $title )
571 );
572 } else {
573 throw new InvalidArgumentException(
574 '$row must be a row object, an associative array, or a RevisionRecord'
575 );
576 }
577
578 Assert::postcondition( $this->mRecord !== null, 'Failed to construct a RevisionRecord' );
579 }
580
581 /**
582 * Make sure we have *some* Title object for use by the constructor.
583 * For B/C, the constructor shouldn't fail even for a bad page ID or bad revision ID.
584 *
585 * @param array|object $row
586 * @param int $queryFlags
587 * @param Title|null $title
588 *
589 * @return Title $title if not null, or a Title constructed from information in $row.
590 */
591 private function ensureTitle( $row, $queryFlags, $title = null ) {
592 if ( $title ) {
593 return $title;
594 }
595
596 if ( is_array( $row ) ) {
597 if ( isset( $row['title'] ) ) {
598 if ( !( $row['title'] instanceof Title ) ) {
599 throw new MWException( 'title field must contain a Title object.' );
600 }
601
602 return $row['title'];
603 }
604
605 $pageId = $row['page'] ?? 0;
606 $revId = $row['id'] ?? 0;
607 } else {
608 $pageId = $row->rev_page ?? 0;
609 $revId = $row->rev_id ?? 0;
610 }
611
612 try {
613 $title = self::getRevisionStore()->getTitle( $pageId, $revId, $queryFlags );
614 } catch ( RevisionAccessException $ex ) {
615 // construct a dummy title!
616 wfLogWarning( __METHOD__ . ': ' . $ex->getMessage() );
617
618 // NOTE: this Title will only be used inside RevisionRecord
619 $title = Title::makeTitleSafe( NS_SPECIAL, "Badtitle/ID=$pageId" );
620 $title->resetArticleID( $pageId );
621 }
622
623 return $title;
624 }
625
626 /**
627 * @return RevisionRecord
628 */
629 public function getRevisionRecord() {
630 return $this->mRecord;
631 }
632
633 /**
634 * Get revision ID
635 *
636 * @return int|null
637 */
638 public function getId() {
639 return $this->mRecord->getId();
640 }
641
642 /**
643 * Set the revision ID
644 *
645 * This should only be used for proposed revisions that turn out to be null edits.
646 *
647 * @note Only supported on Revisions that were constructed based on associative arrays,
648 * since they are mutable.
649 *
650 * @since 1.19
651 * @param int|string $id
652 * @throws MWException
653 */
654 public function setId( $id ) {
655 if ( $this->mRecord instanceof MutableRevisionRecord ) {
656 $this->mRecord->setId( intval( $id ) );
657 } else {
658 throw new MWException( __METHOD__ . ' is not supported on this instance' );
659 }
660 }
661
662 /**
663 * Set the user ID/name
664 *
665 * This should only be used for proposed revisions that turn out to be null edits
666 *
667 * @note Only supported on Revisions that were constructed based on associative arrays,
668 * since they are mutable.
669 *
670 * @since 1.28
671 * @deprecated since 1.31, please reuse old Revision object
672 * @param int $id User ID
673 * @param string $name User name
674 * @throws MWException
675 */
676 public function setUserIdAndName( $id, $name ) {
677 if ( $this->mRecord instanceof MutableRevisionRecord ) {
678 $user = User::newFromAnyId( intval( $id ), $name, null );
679 $this->mRecord->setUser( $user );
680 } else {
681 throw new MWException( __METHOD__ . ' is not supported on this instance' );
682 }
683 }
684
685 /**
686 * @return SlotRecord
687 */
688 private function getMainSlotRaw() {
689 return $this->mRecord->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
690 }
691
692 /**
693 * Get the ID of the row of the text table that contains the content of the
694 * revision's main slot, if that content is stored in the text table.
695 *
696 * If the content is stored elsewhere, this returns null.
697 *
698 * @deprecated since 1.31, use RevisionRecord()->getSlot()->getContentAddress() to
699 * get that actual address that can be used with BlobStore::getBlob(); or use
700 * RevisionRecord::hasSameContent() to check if two revisions have the same content.
701 *
702 * @return int|null
703 */
704 public function getTextId() {
705 $slot = $this->getMainSlotRaw();
706 return $slot->hasAddress()
707 ? self::getBlobStore()->getTextIdFromAddress( $slot->getAddress() )
708 : null;
709 }
710
711 /**
712 * Get parent revision ID (the original previous page revision)
713 *
714 * @return int|null The ID of the parent revision. 0 indicates that there is no
715 * parent revision. Null indicates that the parent revision is not known.
716 */
717 public function getParentId() {
718 return $this->mRecord->getParentId();
719 }
720
721 /**
722 * Returns the length of the text in this revision, or null if unknown.
723 *
724 * @return int|null
725 */
726 public function getSize() {
727 try {
728 return $this->mRecord->getSize();
729 } catch ( RevisionAccessException $ex ) {
730 return null;
731 }
732 }
733
734 /**
735 * Returns the base36 sha1 of the content in this revision, or null if unknown.
736 *
737 * @return string|null
738 */
739 public function getSha1() {
740 try {
741 return $this->mRecord->getSha1();
742 } catch ( RevisionAccessException $ex ) {
743 return null;
744 }
745 }
746
747 /**
748 * Returns the title of the page associated with this entry.
749 * Since 1.31, this will never return null.
750 *
751 * Will do a query, when title is not set and id is given.
752 *
753 * @return Title
754 */
755 public function getTitle() {
756 $linkTarget = $this->mRecord->getPageAsLinkTarget();
757 return Title::newFromLinkTarget( $linkTarget );
758 }
759
760 /**
761 * Set the title of the revision
762 *
763 * @deprecated since 1.31, this is now a noop. Pass the Title to the constructor instead.
764 *
765 * @param Title $title
766 */
767 public function setTitle( $title ) {
768 if ( !$title->equals( $this->getTitle() ) ) {
769 throw new InvalidArgumentException(
770 $title->getPrefixedText()
771 . ' is not the same as '
772 . $this->mRecord->getPageAsLinkTarget()->__toString()
773 );
774 }
775 }
776
777 /**
778 * Get the page ID
779 *
780 * @return int|null
781 */
782 public function getPage() {
783 return $this->mRecord->getPageId();
784 }
785
786 /**
787 * Fetch revision's user id if it's available to the specified audience.
788 * If the specified audience does not have access to it, zero will be
789 * returned.
790 *
791 * @param int $audience One of:
792 * Revision::FOR_PUBLIC to be displayed to all users
793 * Revision::FOR_THIS_USER to be displayed to the given user
794 * Revision::RAW get the ID regardless of permissions
795 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
796 * to the $audience parameter
797 * @return int
798 */
799 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
800 global $wgUser;
801
802 if ( $audience === self::FOR_THIS_USER && !$user ) {
803 $user = $wgUser;
804 }
805
806 $user = $this->mRecord->getUser( $audience, $user );
807 return $user ? $user->getId() : 0;
808 }
809
810 /**
811 * Fetch revision's username if it's available to the specified audience.
812 * If the specified audience does not have access to the username, an
813 * empty string will be returned.
814 *
815 * @param int $audience One of:
816 * Revision::FOR_PUBLIC to be displayed to all users
817 * Revision::FOR_THIS_USER to be displayed to the given user
818 * Revision::RAW get the text regardless of permissions
819 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
820 * to the $audience parameter
821 * @return string
822 */
823 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
824 global $wgUser;
825
826 if ( $audience === self::FOR_THIS_USER && !$user ) {
827 $user = $wgUser;
828 }
829
830 $user = $this->mRecord->getUser( $audience, $user );
831 return $user ? $user->getName() : '';
832 }
833
834 /**
835 * @param int $audience One of:
836 * Revision::FOR_PUBLIC to be displayed to all users
837 * Revision::FOR_THIS_USER to be displayed to the given user
838 * Revision::RAW get the text regardless of permissions
839 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
840 * to the $audience parameter
841 *
842 * @return string|null Returns null if the specified audience does not have access to the
843 * comment.
844 */
845 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
846 global $wgUser;
847
848 if ( $audience === self::FOR_THIS_USER && !$user ) {
849 $user = $wgUser;
850 }
851
852 $comment = $this->mRecord->getComment( $audience, $user );
853 return $comment === null ? null : $comment->text;
854 }
855
856 /**
857 * @return bool
858 */
859 public function isMinor() {
860 return $this->mRecord->isMinor();
861 }
862
863 /**
864 * @return int Rcid of the unpatrolled row, zero if there isn't one
865 */
866 public function isUnpatrolled() {
867 return self::getRevisionStore()->getRcIdIfUnpatrolled( $this->mRecord );
868 }
869
870 /**
871 * Get the RC object belonging to the current revision, if there's one
872 *
873 * @param int $flags (optional) $flags include:
874 * Revision::READ_LATEST : Select the data from the master
875 *
876 * @since 1.22
877 * @return RecentChange|null
878 */
879 public function getRecentChange( $flags = 0 ) {
880 return self::getRevisionStore()->getRecentChange( $this->mRecord, $flags );
881 }
882
883 /**
884 * @param int $field One of DELETED_* bitfield constants
885 *
886 * @return bool
887 */
888 public function isDeleted( $field ) {
889 return $this->mRecord->isDeleted( $field );
890 }
891
892 /**
893 * Get the deletion bitfield of the revision
894 *
895 * @return int
896 */
897 public function getVisibility() {
898 return $this->mRecord->getVisibility();
899 }
900
901 /**
902 * Fetch revision content if it's available to the specified audience.
903 * If the specified audience does not have the ability to view this
904 * revision, or the content could not be loaded, null will be returned.
905 *
906 * @param int $audience One of:
907 * Revision::FOR_PUBLIC to be displayed to all users
908 * Revision::FOR_THIS_USER to be displayed to $user
909 * Revision::RAW get the text regardless of permissions
910 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
911 * to the $audience parameter
912 * @since 1.21
913 * @return Content|null
914 */
915 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
916 global $wgUser;
917
918 if ( $audience === self::FOR_THIS_USER && !$user ) {
919 $user = $wgUser;
920 }
921
922 try {
923 return $this->mRecord->getContent( SlotRecord::MAIN, $audience, $user );
924 }
925 catch ( RevisionAccessException $e ) {
926 return null;
927 }
928 }
929
930 /**
931 * Get original serialized data (without checking view restrictions)
932 *
933 * @since 1.21
934 * @deprecated since 1.31, use BlobStore::getBlob instead.
935 *
936 * @return string
937 */
938 public function getSerializedData() {
939 $slot = $this->getMainSlotRaw();
940 return $slot->getContent()->serialize();
941 }
942
943 /**
944 * Returns the content model for the main slot of this revision.
945 *
946 * If no content model was stored in the database, the default content model for the title is
947 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
948 * is used as a last resort.
949 *
950 * @todo drop this, with MCR, there no longer is a single model associated with a revision.
951 *
952 * @return string The content model id associated with this revision,
953 * see the CONTENT_MODEL_XXX constants.
954 */
955 public function getContentModel() {
956 return $this->getMainSlotRaw()->getModel();
957 }
958
959 /**
960 * Returns the content format for the main slot of this revision.
961 *
962 * If no content format was stored in the database, the default format for this
963 * revision's content model is returned.
964 *
965 * @todo drop this, the format is irrelevant to the revision!
966 *
967 * @return string The content format id associated with this revision,
968 * see the CONTENT_FORMAT_XXX constants.
969 */
970 public function getContentFormat() {
971 $format = $this->getMainSlotRaw()->getFormat();
972
973 if ( $format === null ) {
974 // if no format was stored along with the blob, fall back to default format
975 $format = $this->getContentHandler()->getDefaultFormat();
976 }
977
978 return $format;
979 }
980
981 /**
982 * Returns the content handler appropriate for this revision's content model.
983 *
984 * @throws MWException
985 * @return ContentHandler
986 */
987 public function getContentHandler() {
988 return ContentHandler::getForModelID( $this->getContentModel() );
989 }
990
991 /**
992 * @return string
993 */
994 public function getTimestamp() {
995 return $this->mRecord->getTimestamp();
996 }
997
998 /**
999 * @return bool
1000 */
1001 public function isCurrent() {
1002 return ( $this->mRecord instanceof RevisionStoreRecord ) && $this->mRecord->isCurrent();
1003 }
1004
1005 /**
1006 * Get previous revision for this title
1007 *
1008 * @return Revision|null
1009 */
1010 public function getPrevious() {
1011 $title = $this->getTitle();
1012 $rec = self::getRevisionLookup()->getPreviousRevision( $this->mRecord, $title );
1013 return $rec ? new Revision( $rec, self::READ_NORMAL, $title ) : null;
1014 }
1015
1016 /**
1017 * Get next revision for this title
1018 *
1019 * @return Revision|null
1020 */
1021 public function getNext() {
1022 $title = $this->getTitle();
1023 $rec = self::getRevisionLookup()->getNextRevision( $this->mRecord, $title );
1024 return $rec ? new Revision( $rec, self::READ_NORMAL, $title ) : null;
1025 }
1026
1027 /**
1028 * Get revision text associated with an old or archive row
1029 *
1030 * If the text field is not included, this uses RevisionStore to load the appropriate slot
1031 * and return its serialized content. This is the default backwards-compatibility behavior
1032 * when reading from the MCR aware database schema is enabled. For this to work, either
1033 * the revision ID or the page ID must be included in the row.
1034 *
1035 * When using the old text field, the flags field must also be set. Including the old_id
1036 * field will activate cache usage as long as the $wiki parameter is not set.
1037 *
1038 * @deprecated since 1.32, use RevisionStore::newRevisionFromRow instead.
1039 *
1040 * @param stdClass $row The text data. If a falsy value is passed instead, false is returned.
1041 * @param string $prefix Table prefix (default 'old_')
1042 * @param string|bool $wiki The name of the wiki to load the revision text from
1043 * (same as the wiki $row was loaded from) or false to indicate the local
1044 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1045 * identifier as understood by the LoadBalancer class.
1046 * @return string|false Text the text requested or false on failure
1047 */
1048 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1049 global $wgMultiContentRevisionSchemaMigrationStage;
1050
1051 if ( !$row ) {
1052 return false;
1053 }
1054
1055 $textField = $prefix . 'text';
1056 $flagsField = $prefix . 'flags';
1057
1058 if ( isset( $row->$textField ) ) {
1059 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1060 // The text field was read, but it's no longer being populated!
1061 // We could gloss over this by using the text when it's there and loading
1062 // if when it's not, but it seems preferable to complain loudly about a
1063 // query that is no longer guaranteed to work reliably.
1064 throw new LogicException(
1065 'Cannot use ' . __METHOD__ . ' with the ' . $textField . ' field when'
1066 . ' $wgMultiContentRevisionSchemaMigrationStage does not include'
1067 . ' SCHEMA_COMPAT_WRITE_OLD. The field may not be populated for all revisions!'
1068 );
1069 }
1070
1071 $text = $row->$textField;
1072 } else {
1073 // Missing text field, we are probably looking at the MCR-enabled DB schema.
1074
1075 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1076 // This method should no longer be used with the new schema. Ideally, we
1077 // would already trigger a deprecation warning when SCHEMA_COMPAT_READ_NEW is set.
1078 wfDeprecated( __METHOD__ . ' (MCR without SCHEMA_COMPAT_WRITE_OLD)', '1.32' );
1079 }
1080
1081 $store = self::getRevisionStore( $wiki );
1082 $rev = $prefix === 'ar_'
1083 ? $store->newRevisionFromArchiveRow( $row )
1084 : $store->newRevisionFromRow( $row );
1085
1086 $content = $rev->getContent( SlotRecord::MAIN );
1087 return $content ? $content->serialize() : false;
1088 }
1089
1090 if ( isset( $row->$flagsField ) ) {
1091 $flags = explode( ',', $row->$flagsField );
1092 } else {
1093 $flags = [];
1094 }
1095
1096 $cacheKey = isset( $row->old_id )
1097 ? SqlBlobStore::makeAddressFromTextId( $row->old_id )
1098 : null;
1099
1100 $revisionText = self::getBlobStore( $wiki )->expandBlob( $text, $flags, $cacheKey );
1101
1102 if ( $revisionText === false ) {
1103 if ( isset( $row->old_id ) ) {
1104 wfLogWarning( __METHOD__ . ": Bad data in text row {$row->old_id}! " );
1105 } else {
1106 wfLogWarning( __METHOD__ . ": Bad data in text row! " );
1107 }
1108 return false;
1109 }
1110
1111 return $revisionText;
1112 }
1113
1114 /**
1115 * If $wgCompressRevisions is enabled, we will compress data.
1116 * The input string is modified in place.
1117 * Return value is the flags field: contains 'gzip' if the
1118 * data is compressed, and 'utf-8' if we're saving in UTF-8
1119 * mode.
1120 *
1121 * @param mixed &$text Reference to a text
1122 * @return string
1123 */
1124 public static function compressRevisionText( &$text ) {
1125 return self::getBlobStore()->compressData( $text );
1126 }
1127
1128 /**
1129 * Re-converts revision text according to it's flags.
1130 *
1131 * @param mixed $text Reference to a text
1132 * @param array $flags Compression flags
1133 * @return string|bool Decompressed text, or false on failure
1134 */
1135 public static function decompressRevisionText( $text, $flags ) {
1136 if ( $text === false ) {
1137 // Text failed to be fetched; nothing to do
1138 return false;
1139 }
1140
1141 return self::getBlobStore()->decompressData( $text, $flags );
1142 }
1143
1144 /**
1145 * Insert a new revision into the database, returning the new revision ID
1146 * number on success and dies horribly on failure.
1147 *
1148 * @param IDatabase $dbw (master connection)
1149 * @throws MWException
1150 * @return int The revision ID
1151 */
1152 public function insertOn( $dbw ) {
1153 global $wgUser;
1154
1155 // Note that $this->mRecord->getId() will typically return null here, but not always,
1156 // e.g. not when restoring a revision.
1157
1158 if ( $this->mRecord->getUser( RevisionRecord::RAW ) === null ) {
1159 if ( $this->mRecord instanceof MutableRevisionRecord ) {
1160 $this->mRecord->setUser( $wgUser );
1161 } else {
1162 throw new MWException( 'Cannot insert revision with no associated user.' );
1163 }
1164 }
1165
1166 $rec = self::getRevisionStore()->insertRevisionOn( $this->mRecord, $dbw );
1167
1168 $this->mRecord = $rec;
1169 Assert::postcondition( $this->mRecord !== null, 'Failed to acquire a RevisionRecord' );
1170
1171 return $rec->getId();
1172 }
1173
1174 /**
1175 * Get the base 36 SHA-1 value for a string of text
1176 * @param string $text
1177 * @return string
1178 */
1179 public static function base36Sha1( $text ) {
1180 return SlotRecord::base36Sha1( $text );
1181 }
1182
1183 /**
1184 * Create a new null-revision for insertion into a page's
1185 * history. This will not re-save the text, but simply refer
1186 * to the text from the previous version.
1187 *
1188 * Such revisions can for instance identify page rename
1189 * operations and other such meta-modifications.
1190 *
1191 * @param IDatabase $dbw
1192 * @param int $pageId ID number of the page to read from
1193 * @param string $summary Revision's summary
1194 * @param bool $minor Whether the revision should be considered as minor
1195 * @param User|null $user User object to use or null for $wgUser
1196 * @return Revision|null Revision or null on error
1197 */
1198 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1199 global $wgUser;
1200 if ( !$user ) {
1201 $user = $wgUser;
1202 }
1203
1204 $comment = CommentStoreComment::newUnsavedComment( $summary, null );
1205
1206 $title = Title::newFromID( $pageId, Title::GAID_FOR_UPDATE );
1207 if ( $title === null ) {
1208 return null;
1209 }
1210
1211 $rec = self::getRevisionStore()->newNullRevision( $dbw, $title, $comment, $minor, $user );
1212
1213 return $rec ? new Revision( $rec ) : null;
1214 }
1215
1216 /**
1217 * Determine if the current user is allowed to view a particular
1218 * field of this revision, if it's marked as deleted.
1219 *
1220 * @param int $field One of self::DELETED_TEXT,
1221 * self::DELETED_COMMENT,
1222 * self::DELETED_USER
1223 * @param User|null $user User object to check, or null to use $wgUser
1224 * @return bool
1225 */
1226 public function userCan( $field, User $user = null ) {
1227 return self::userCanBitfield( $this->getVisibility(), $field, $user );
1228 }
1229
1230 /**
1231 * Determine if the current user is allowed to view a particular
1232 * field of this revision, if it's marked as deleted. This is used
1233 * by various classes to avoid duplication.
1234 *
1235 * @param int $bitfield Current field
1236 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1237 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1238 * self::DELETED_USER = File::DELETED_USER
1239 * @param User|null $user User object to check, or null to use $wgUser
1240 * @param Title|null $title A Title object to check for per-page restrictions on,
1241 * instead of just plain userrights
1242 * @return bool
1243 */
1244 public static function userCanBitfield( $bitfield, $field, User $user = null,
1245 Title $title = null
1246 ) {
1247 global $wgUser;
1248
1249 if ( !$user ) {
1250 $user = $wgUser;
1251 }
1252
1253 return RevisionRecord::userCanBitfield( $bitfield, $field, $user, $title );
1254 }
1255
1256 /**
1257 * Get rev_timestamp from rev_id, without loading the rest of the row
1258 *
1259 * @param Title $title
1260 * @param int $id
1261 * @param int $flags
1262 * @return string|bool False if not found
1263 */
1264 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1265 return self::getRevisionStore()->getTimestampFromId( $title, $id, $flags );
1266 }
1267
1268 /**
1269 * Get count of revisions per page...not very efficient
1270 *
1271 * @param IDatabase $db
1272 * @param int $id Page id
1273 * @return int
1274 */
1275 static function countByPageId( $db, $id ) {
1276 return self::getRevisionStore()->countRevisionsByPageId( $db, $id );
1277 }
1278
1279 /**
1280 * Get count of revisions per page...not very efficient
1281 *
1282 * @param IDatabase $db
1283 * @param Title $title
1284 * @return int
1285 */
1286 static function countByTitle( $db, $title ) {
1287 return self::getRevisionStore()->countRevisionsByTitle( $db, $title );
1288 }
1289
1290 /**
1291 * Check if no edits were made by other users since
1292 * the time a user started editing the page. Limit to
1293 * 50 revisions for the sake of performance.
1294 *
1295 * @since 1.20
1296 * @deprecated since 1.24
1297 *
1298 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1299 * Database object or a database identifier usable with wfGetDB.
1300 * @param int $pageId The ID of the page in question
1301 * @param int $userId The ID of the user in question
1302 * @param string $since Look at edits since this time
1303 *
1304 * @return bool True if the given user was the only one to edit since the given timestamp
1305 */
1306 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1307 if ( is_int( $db ) ) {
1308 $db = wfGetDB( $db );
1309 }
1310
1311 return self::getRevisionStore()->userWasLastToEdit( $db, $pageId, $userId, $since );
1312 }
1313
1314 /**
1315 * Load a revision based on a known page ID and current revision ID from the DB
1316 *
1317 * This method allows for the use of caching, though accessing anything that normally
1318 * requires permission checks (aside from the text) will trigger a small DB lookup.
1319 * The title will also be loaded if $pageIdOrTitle is an integer ID.
1320 *
1321 * @param IDatabase $db ignored!
1322 * @param int|Title $pageIdOrTitle Page ID or Title object
1323 * @param int $revId Known current revision of this page. Determined automatically if not given.
1324 * @return Revision|bool Returns false if missing
1325 * @since 1.28
1326 */
1327 public static function newKnownCurrent( IDatabase $db, $pageIdOrTitle, $revId = 0 ) {
1328 $title = $pageIdOrTitle instanceof Title
1329 ? $pageIdOrTitle
1330 : Title::newFromID( $pageIdOrTitle );
1331
1332 if ( !$title ) {
1333 return false;
1334 }
1335
1336 $record = self::getRevisionLookup()->getKnownCurrentRevision( $title, $revId );
1337 return $record ? new Revision( $record ) : false;
1338 }
1339 }