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