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