Merge "Fix deletion handling of rev_deleted"
[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 use MediaWiki\Linker\LinkTarget;
23
24 /**
25 * @todo document
26 */
27 class Revision implements IDBAccessObject {
28 protected $mId;
29
30 /**
31 * @var int|null
32 */
33 protected $mPage;
34 protected $mUserText;
35 protected $mOrigUserText;
36 protected $mUser;
37 protected $mMinorEdit;
38 protected $mTimestamp;
39 protected $mDeleted;
40 protected $mSize;
41 protected $mSha1;
42 protected $mParentId;
43 protected $mComment;
44 protected $mText;
45 protected $mTextId;
46
47 /**
48 * @var stdClass|null
49 */
50 protected $mTextRow;
51
52 /**
53 * @var null|Title
54 */
55 protected $mTitle;
56 protected $mCurrent;
57 protected $mContentModel;
58 protected $mContentFormat;
59
60 /**
61 * @var Content|null|bool
62 */
63 protected $mContent;
64
65 /**
66 * @var null|ContentHandler
67 */
68 protected $mContentHandler;
69
70 /**
71 * @var int
72 */
73 protected $mQueryFlags = 0;
74
75 // Revision deletion constants
76 const DELETED_TEXT = 1;
77 const DELETED_COMMENT = 2;
78 const DELETED_USER = 4;
79 const DELETED_RESTRICTED = 8;
80 const SUPPRESSED_USER = 12; // convenience
81
82 // Audience options for accessors
83 const FOR_PUBLIC = 1;
84 const FOR_THIS_USER = 2;
85 const RAW = 3;
86
87 /**
88 * Load a page revision from a given revision ID number.
89 * Returns null if no such revision can be found.
90 *
91 * $flags include:
92 * Revision::READ_LATEST : Select the data from the master
93 * Revision::READ_LOCKING : Select & lock the data from the master
94 *
95 * @param int $id
96 * @param int $flags (optional)
97 * @return Revision|null
98 */
99 public static function newFromId( $id, $flags = 0 ) {
100 return self::newFromConds( [ 'rev_id' => intval( $id ) ], $flags );
101 }
102
103 /**
104 * Load either the current, or a specified, revision
105 * that's attached to a given link target. If not attached
106 * to that link target, will return null.
107 *
108 * $flags include:
109 * Revision::READ_LATEST : Select the data from the master
110 * Revision::READ_LOCKING : Select & lock the data from the master
111 *
112 * @param LinkTarget $linkTarget
113 * @param int $id (optional)
114 * @param int $flags Bitfield (optional)
115 * @return Revision|null
116 */
117 public static function newFromTitle( LinkTarget $linkTarget, $id = 0, $flags = 0 ) {
118 $conds = [
119 'page_namespace' => $linkTarget->getNamespace(),
120 'page_title' => $linkTarget->getDBkey()
121 ];
122 if ( $id ) {
123 // Use the specified ID
124 $conds['rev_id'] = $id;
125 return self::newFromConds( $conds, $flags );
126 } else {
127 // Use a join to get the latest revision
128 $conds[] = 'rev_id=page_latest';
129 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE );
130 return self::loadFromConds( $db, $conds, $flags );
131 }
132 }
133
134 /**
135 * Load either the current, or a specified, revision
136 * that's attached to a given page ID.
137 * Returns null if no such revision can be found.
138 *
139 * $flags include:
140 * Revision::READ_LATEST : Select the data from the master (since 1.20)
141 * Revision::READ_LOCKING : Select & lock the data from the master
142 *
143 * @param int $pageId
144 * @param int $revId (optional)
145 * @param int $flags Bitfield (optional)
146 * @return Revision|null
147 */
148 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
149 $conds = [ 'page_id' => $pageId ];
150 if ( $revId ) {
151 $conds['rev_id'] = $revId;
152 return self::newFromConds( $conds, $flags );
153 } else {
154 // Use a join to get the latest revision
155 $conds[] = 'rev_id = page_latest';
156 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE );
157 return self::loadFromConds( $db, $conds, $flags );
158 }
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 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
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 global $wgContentHandlerUseDB;
174
175 $attribs = $overrides + [
176 'page' => isset( $row->ar_page_id ) ? $row->ar_page_id : null,
177 'id' => isset( $row->ar_rev_id ) ? $row->ar_rev_id : null,
178 'comment' => $row->ar_comment,
179 'user' => $row->ar_user,
180 'user_text' => $row->ar_user_text,
181 'timestamp' => $row->ar_timestamp,
182 'minor_edit' => $row->ar_minor_edit,
183 'text_id' => isset( $row->ar_text_id ) ? $row->ar_text_id : null,
184 'deleted' => $row->ar_deleted,
185 'len' => $row->ar_len,
186 'sha1' => isset( $row->ar_sha1 ) ? $row->ar_sha1 : null,
187 'content_model' => isset( $row->ar_content_model ) ? $row->ar_content_model : null,
188 'content_format' => isset( $row->ar_content_format ) ? $row->ar_content_format : null,
189 ];
190
191 if ( !$wgContentHandlerUseDB ) {
192 unset( $attribs['content_model'] );
193 unset( $attribs['content_format'] );
194 }
195
196 if ( !isset( $attribs['title'] )
197 && isset( $row->ar_namespace )
198 && isset( $row->ar_title )
199 ) {
200 $attribs['title'] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
201 }
202
203 if ( isset( $row->ar_text ) && !$row->ar_text_id ) {
204 // Pre-1.5 ar_text row
205 $attribs['text'] = self::getRevisionText( $row, 'ar_' );
206 if ( $attribs['text'] === false ) {
207 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
208 }
209 }
210 return new self( $attribs );
211 }
212
213 /**
214 * @since 1.19
215 *
216 * @param object $row
217 * @return Revision
218 */
219 public static function newFromRow( $row ) {
220 return new self( $row );
221 }
222
223 /**
224 * Load a page revision from a given revision ID number.
225 * Returns null if no such revision can be found.
226 *
227 * @param IDatabase $db
228 * @param int $id
229 * @return Revision|null
230 */
231 public static function loadFromId( $db, $id ) {
232 return self::loadFromConds( $db, [ 'rev_id' => intval( $id ) ] );
233 }
234
235 /**
236 * Load either the current, or a specified, revision
237 * that's attached to a given page. If not attached
238 * to that page, will return null.
239 *
240 * @param IDatabase $db
241 * @param int $pageid
242 * @param int $id
243 * @return Revision|null
244 */
245 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
246 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
247 if ( $id ) {
248 $conds['rev_id'] = intval( $id );
249 } else {
250 $conds[] = 'rev_id=page_latest';
251 }
252 return self::loadFromConds( $db, $conds );
253 }
254
255 /**
256 * Load either the current, or a specified, revision
257 * that's attached to a given page. If not attached
258 * to that page, will return null.
259 *
260 * @param IDatabase $db
261 * @param Title $title
262 * @param int $id
263 * @return Revision|null
264 */
265 public static function loadFromTitle( $db, $title, $id = 0 ) {
266 if ( $id ) {
267 $matchId = intval( $id );
268 } else {
269 $matchId = 'page_latest';
270 }
271 return self::loadFromConds( $db,
272 [
273 "rev_id=$matchId",
274 'page_namespace' => $title->getNamespace(),
275 'page_title' => $title->getDBkey()
276 ]
277 );
278 }
279
280 /**
281 * Load the revision for the given title with the given timestamp.
282 * WARNING: Timestamps may in some circumstances not be unique,
283 * so this isn't the best key to use.
284 *
285 * @param IDatabase $db
286 * @param Title $title
287 * @param string $timestamp
288 * @return Revision|null
289 */
290 public static function loadFromTimestamp( $db, $title, $timestamp ) {
291 return self::loadFromConds( $db,
292 [
293 'rev_timestamp' => $db->timestamp( $timestamp ),
294 'page_namespace' => $title->getNamespace(),
295 'page_title' => $title->getDBkey()
296 ]
297 );
298 }
299
300 /**
301 * Given a set of conditions, fetch a revision
302 *
303 * This method is used then a revision ID is qualified and
304 * will incorporate some basic slave/master fallback logic
305 *
306 * @param array $conditions
307 * @param int $flags (optional)
308 * @return Revision|null
309 */
310 private static function newFromConds( $conditions, $flags = 0 ) {
311 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE );
312
313 $rev = self::loadFromConds( $db, $conditions, $flags );
314 // Make sure new pending/committed revision are visibile later on
315 // within web requests to certain avoid bugs like T93866 and T94407.
316 if ( !$rev
317 && !( $flags & self::READ_LATEST )
318 && wfGetLB()->getServerCount() > 1
319 && wfGetLB()->hasOrMadeRecentMasterChanges()
320 ) {
321 $flags = self::READ_LATEST;
322 $db = wfGetDB( DB_MASTER );
323 $rev = self::loadFromConds( $db, $conditions, $flags );
324 }
325
326 if ( $rev ) {
327 $rev->mQueryFlags = $flags;
328 }
329
330 return $rev;
331 }
332
333 /**
334 * Given a set of conditions, fetch a revision from
335 * the given database connection.
336 *
337 * @param IDatabase $db
338 * @param array $conditions
339 * @param int $flags (optional)
340 * @return Revision|null
341 */
342 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
343 $row = self::fetchFromConds( $db, $conditions, $flags );
344
345 return $row ? new Revision( $row ) : null;
346 }
347
348 /**
349 * Return a wrapper for a series of database rows to
350 * fetch all of a given page's revisions in turn.
351 * Each row can be fed to the constructor to get objects.
352 *
353 * @param LinkTarget $title
354 * @return ResultWrapper
355 * @deprecated Since 1.28
356 */
357 public static function fetchRevision( LinkTarget $title ) {
358 $row = self::fetchFromConds(
359 wfGetDB( DB_SLAVE ),
360 [
361 'rev_id=page_latest',
362 'page_namespace' => $title->getNamespace(),
363 'page_title' => $title->getDBkey()
364 ]
365 );
366
367 return new FakeResultWrapper( $row ? [ $row ] : [] );
368 }
369
370 /**
371 * Given a set of conditions, return a ResultWrapper
372 * which will return matching database rows with the
373 * fields necessary to build Revision objects.
374 *
375 * @param IDatabase $db
376 * @param array $conditions
377 * @param int $flags (optional)
378 * @return stdClass
379 */
380 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
381 $fields = array_merge(
382 self::selectFields(),
383 self::selectPageFields(),
384 self::selectUserFields()
385 );
386 $options = [];
387 if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) {
388 $options[] = 'FOR UPDATE';
389 }
390 return $db->selectRow(
391 [ 'revision', 'page', 'user' ],
392 $fields,
393 $conditions,
394 __METHOD__,
395 $options,
396 [ 'page' => self::pageJoinCond(), 'user' => self::userJoinCond() ]
397 );
398 }
399
400 /**
401 * Return the value of a select() JOIN conds array for the user table.
402 * This will get user table rows for logged-in users.
403 * @since 1.19
404 * @return array
405 */
406 public static function userJoinCond() {
407 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
408 }
409
410 /**
411 * Return the value of a select() page conds array for the page table.
412 * This will assure that the revision(s) are not orphaned from live pages.
413 * @since 1.19
414 * @return array
415 */
416 public static function pageJoinCond() {
417 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
418 }
419
420 /**
421 * Return the list of revision fields that should be selected to create
422 * a new revision.
423 * @return array
424 */
425 public static function selectFields() {
426 global $wgContentHandlerUseDB;
427
428 $fields = [
429 'rev_id',
430 'rev_page',
431 'rev_text_id',
432 'rev_timestamp',
433 'rev_comment',
434 'rev_user_text',
435 'rev_user',
436 'rev_minor_edit',
437 'rev_deleted',
438 'rev_len',
439 'rev_parent_id',
440 'rev_sha1',
441 ];
442
443 if ( $wgContentHandlerUseDB ) {
444 $fields[] = 'rev_content_format';
445 $fields[] = 'rev_content_model';
446 }
447
448 return $fields;
449 }
450
451 /**
452 * Return the list of revision fields that should be selected to create
453 * a new revision from an archive row.
454 * @return array
455 */
456 public static function selectArchiveFields() {
457 global $wgContentHandlerUseDB;
458 $fields = [
459 'ar_id',
460 'ar_page_id',
461 'ar_rev_id',
462 'ar_text',
463 'ar_text_id',
464 'ar_timestamp',
465 'ar_comment',
466 'ar_user_text',
467 'ar_user',
468 'ar_minor_edit',
469 'ar_deleted',
470 'ar_len',
471 'ar_parent_id',
472 'ar_sha1',
473 ];
474
475 if ( $wgContentHandlerUseDB ) {
476 $fields[] = 'ar_content_format';
477 $fields[] = 'ar_content_model';
478 }
479 return $fields;
480 }
481
482 /**
483 * Return the list of text fields that should be selected to read the
484 * revision text
485 * @return array
486 */
487 public static function selectTextFields() {
488 return [
489 'old_text',
490 'old_flags'
491 ];
492 }
493
494 /**
495 * Return the list of page fields that should be selected from page table
496 * @return array
497 */
498 public static function selectPageFields() {
499 return [
500 'page_namespace',
501 'page_title',
502 'page_id',
503 'page_latest',
504 'page_is_redirect',
505 'page_len',
506 ];
507 }
508
509 /**
510 * Return the list of user fields that should be selected from user table
511 * @return array
512 */
513 public static function selectUserFields() {
514 return [ 'user_name' ];
515 }
516
517 /**
518 * Do a batched query to get the parent revision lengths
519 * @param IDatabase $db
520 * @param array $revIds
521 * @return array
522 */
523 public static function getParentLengths( $db, array $revIds ) {
524 $revLens = [];
525 if ( !$revIds ) {
526 return $revLens; // empty
527 }
528 $res = $db->select( 'revision',
529 [ 'rev_id', 'rev_len' ],
530 [ 'rev_id' => $revIds ],
531 __METHOD__ );
532 foreach ( $res as $row ) {
533 $revLens[$row->rev_id] = $row->rev_len;
534 }
535 return $revLens;
536 }
537
538 /**
539 * Constructor
540 *
541 * @param object|array $row Either a database row or an array
542 * @throws MWException
543 * @access private
544 */
545 function __construct( $row ) {
546 if ( is_object( $row ) ) {
547 $this->mId = intval( $row->rev_id );
548 $this->mPage = intval( $row->rev_page );
549 $this->mTextId = intval( $row->rev_text_id );
550 $this->mComment = $row->rev_comment;
551 $this->mUser = intval( $row->rev_user );
552 $this->mMinorEdit = intval( $row->rev_minor_edit );
553 $this->mTimestamp = $row->rev_timestamp;
554 $this->mDeleted = intval( $row->rev_deleted );
555
556 if ( !isset( $row->rev_parent_id ) ) {
557 $this->mParentId = null;
558 } else {
559 $this->mParentId = intval( $row->rev_parent_id );
560 }
561
562 if ( !isset( $row->rev_len ) ) {
563 $this->mSize = null;
564 } else {
565 $this->mSize = intval( $row->rev_len );
566 }
567
568 if ( !isset( $row->rev_sha1 ) ) {
569 $this->mSha1 = null;
570 } else {
571 $this->mSha1 = $row->rev_sha1;
572 }
573
574 if ( isset( $row->page_latest ) ) {
575 $this->mCurrent = ( $row->rev_id == $row->page_latest );
576 $this->mTitle = Title::newFromRow( $row );
577 } else {
578 $this->mCurrent = false;
579 $this->mTitle = null;
580 }
581
582 if ( !isset( $row->rev_content_model ) ) {
583 $this->mContentModel = null; # determine on demand if needed
584 } else {
585 $this->mContentModel = strval( $row->rev_content_model );
586 }
587
588 if ( !isset( $row->rev_content_format ) ) {
589 $this->mContentFormat = null; # determine on demand if needed
590 } else {
591 $this->mContentFormat = strval( $row->rev_content_format );
592 }
593
594 // Lazy extraction...
595 $this->mText = null;
596 if ( isset( $row->old_text ) ) {
597 $this->mTextRow = $row;
598 } else {
599 // 'text' table row entry will be lazy-loaded
600 $this->mTextRow = null;
601 }
602
603 // Use user_name for users and rev_user_text for IPs...
604 $this->mUserText = null; // lazy load if left null
605 if ( $this->mUser == 0 ) {
606 $this->mUserText = $row->rev_user_text; // IP user
607 } elseif ( isset( $row->user_name ) ) {
608 $this->mUserText = $row->user_name; // logged-in user
609 }
610 $this->mOrigUserText = $row->rev_user_text;
611 } elseif ( is_array( $row ) ) {
612 // Build a new revision to be saved...
613 global $wgUser; // ugh
614
615 # if we have a content object, use it to set the model and type
616 if ( !empty( $row['content'] ) ) {
617 // @todo when is that set? test with external store setup! check out insertOn() [dk]
618 if ( !empty( $row['text_id'] ) ) {
619 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
620 "can't serialize content object" );
621 }
622
623 $row['content_model'] = $row['content']->getModel();
624 # note: mContentFormat is initializes later accordingly
625 # note: content is serialized later in this method!
626 # also set text to null?
627 }
628
629 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
630 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
631 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
632 $this->mUserText = isset( $row['user_text'] )
633 ? strval( $row['user_text'] ) : $wgUser->getName();
634 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
635 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
636 $this->mTimestamp = isset( $row['timestamp'] )
637 ? strval( $row['timestamp'] ) : wfTimestampNow();
638 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
639 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
640 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
641 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
642
643 $this->mContentModel = isset( $row['content_model'] )
644 ? strval( $row['content_model'] ) : null;
645 $this->mContentFormat = isset( $row['content_format'] )
646 ? strval( $row['content_format'] ) : null;
647
648 // Enforce spacing trimming on supplied text
649 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
650 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
651 $this->mTextRow = null;
652
653 $this->mTitle = isset( $row['title'] ) ? $row['title'] : null;
654
655 // if we have a Content object, override mText and mContentModel
656 if ( !empty( $row['content'] ) ) {
657 if ( !( $row['content'] instanceof Content ) ) {
658 throw new MWException( '`content` field must contain a Content object.' );
659 }
660
661 $handler = $this->getContentHandler();
662 $this->mContent = $row['content'];
663
664 $this->mContentModel = $this->mContent->getModel();
665 $this->mContentHandler = null;
666
667 $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() );
668 } elseif ( $this->mText !== null ) {
669 $handler = $this->getContentHandler();
670 $this->mContent = $handler->unserializeContent( $this->mText );
671 }
672
673 // If we have a Title object, make sure it is consistent with mPage.
674 if ( $this->mTitle && $this->mTitle->exists() ) {
675 if ( $this->mPage === null ) {
676 // if the page ID wasn't known, set it now
677 $this->mPage = $this->mTitle->getArticleID();
678 } elseif ( $this->mTitle->getArticleID() !== $this->mPage ) {
679 // Got different page IDs. This may be legit (e.g. during undeletion),
680 // but it seems worth mentioning it in the log.
681 wfDebug( "Page ID " . $this->mPage . " mismatches the ID " .
682 $this->mTitle->getArticleID() . " provided by the Title object." );
683 }
684 }
685
686 $this->mCurrent = false;
687
688 // If we still have no length, see it we have the text to figure it out
689 if ( !$this->mSize && $this->mContent !== null ) {
690 $this->mSize = $this->mContent->getSize();
691 }
692
693 // Same for sha1
694 if ( $this->mSha1 === null ) {
695 $this->mSha1 = $this->mText === null ? null : self::base36Sha1( $this->mText );
696 }
697
698 // force lazy init
699 $this->getContentModel();
700 $this->getContentFormat();
701 } else {
702 throw new MWException( 'Revision constructor passed invalid row format.' );
703 }
704 $this->mUnpatrolled = null;
705 }
706
707 /**
708 * Get revision ID
709 *
710 * @return int|null
711 */
712 public function getId() {
713 return $this->mId;
714 }
715
716 /**
717 * Set the revision ID
718 *
719 * This should only be used for proposed revisions that turn out to be null edits
720 *
721 * @since 1.19
722 * @param int $id
723 */
724 public function setId( $id ) {
725 $this->mId = (int)$id;
726 }
727
728 /**
729 * Set the user ID/name
730 *
731 * This should only be used for proposed revisions that turn out to be null edits
732 *
733 * @since 1.28
734 * @param integer $id User ID
735 * @param string $name User name
736 */
737 public function setUserIdAndName( $id, $name ) {
738 $this->mUser = (int)$id;
739 $this->mUserText = $name;
740 $this->mOrigUserText = $name;
741 }
742
743 /**
744 * Get text row ID
745 *
746 * @return int|null
747 */
748 public function getTextId() {
749 return $this->mTextId;
750 }
751
752 /**
753 * Get parent revision ID (the original previous page revision)
754 *
755 * @return int|null
756 */
757 public function getParentId() {
758 return $this->mParentId;
759 }
760
761 /**
762 * Returns the length of the text in this revision, or null if unknown.
763 *
764 * @return int|null
765 */
766 public function getSize() {
767 return $this->mSize;
768 }
769
770 /**
771 * Returns the base36 sha1 of the text in this revision, or null if unknown.
772 *
773 * @return string|null
774 */
775 public function getSha1() {
776 return $this->mSha1;
777 }
778
779 /**
780 * Returns the title of the page associated with this entry or null.
781 *
782 * Will do a query, when title is not set and id is given.
783 *
784 * @return Title|null
785 */
786 public function getTitle() {
787 if ( $this->mTitle !== null ) {
788 return $this->mTitle;
789 }
790 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
791 if ( $this->mId !== null ) {
792 $dbr = wfGetDB( DB_SLAVE );
793 $row = $dbr->selectRow(
794 [ 'page', 'revision' ],
795 self::selectPageFields(),
796 [ 'page_id=rev_page',
797 'rev_id' => $this->mId ],
798 __METHOD__ );
799 if ( $row ) {
800 $this->mTitle = Title::newFromRow( $row );
801 }
802 }
803
804 if ( !$this->mTitle && $this->mPage !== null && $this->mPage > 0 ) {
805 $this->mTitle = Title::newFromID( $this->mPage );
806 }
807
808 return $this->mTitle;
809 }
810
811 /**
812 * Set the title of the revision
813 *
814 * @param Title $title
815 */
816 public function setTitle( $title ) {
817 $this->mTitle = $title;
818 }
819
820 /**
821 * Get the page ID
822 *
823 * @return int|null
824 */
825 public function getPage() {
826 return $this->mPage;
827 }
828
829 /**
830 * Fetch revision's user id if it's available to the specified audience.
831 * If the specified audience does not have access to it, zero will be
832 * returned.
833 *
834 * @param int $audience One of:
835 * Revision::FOR_PUBLIC to be displayed to all users
836 * Revision::FOR_THIS_USER to be displayed to the given user
837 * Revision::RAW get the ID regardless of permissions
838 * @param User $user User object to check for, only if FOR_THIS_USER is passed
839 * to the $audience parameter
840 * @return int
841 */
842 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
843 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
844 return 0;
845 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
846 return 0;
847 } else {
848 return $this->mUser;
849 }
850 }
851
852 /**
853 * Fetch revision's user id without regard for the current user's permissions
854 *
855 * @return string
856 * @deprecated since 1.25, use getUser( Revision::RAW )
857 */
858 public function getRawUser() {
859 wfDeprecated( __METHOD__, '1.25' );
860 return $this->getUser( self::RAW );
861 }
862
863 /**
864 * Fetch revision's username if it's available to the specified audience.
865 * If the specified audience does not have access to the username, an
866 * empty string will be returned.
867 *
868 * @param int $audience One of:
869 * Revision::FOR_PUBLIC to be displayed to all users
870 * Revision::FOR_THIS_USER to be displayed to the given user
871 * Revision::RAW get the text regardless of permissions
872 * @param User $user User object to check for, only if FOR_THIS_USER is passed
873 * to the $audience parameter
874 * @return string
875 */
876 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
877 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
878 return '';
879 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
880 return '';
881 } else {
882 if ( $this->mUserText === null ) {
883 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
884 if ( $this->mUserText === false ) {
885 # This shouldn't happen, but it can if the wiki was recovered
886 # via importing revs and there is no user table entry yet.
887 $this->mUserText = $this->mOrigUserText;
888 }
889 }
890 return $this->mUserText;
891 }
892 }
893
894 /**
895 * Fetch revision's username without regard for view restrictions
896 *
897 * @return string
898 * @deprecated since 1.25, use getUserText( Revision::RAW )
899 */
900 public function getRawUserText() {
901 wfDeprecated( __METHOD__, '1.25' );
902 return $this->getUserText( self::RAW );
903 }
904
905 /**
906 * Fetch revision comment if it's available to the specified audience.
907 * If the specified audience does not have access to the comment, an
908 * empty string will be returned.
909 *
910 * @param int $audience One of:
911 * Revision::FOR_PUBLIC to be displayed to all users
912 * Revision::FOR_THIS_USER to be displayed to the given user
913 * Revision::RAW get the text regardless of permissions
914 * @param User $user User object to check for, only if FOR_THIS_USER is passed
915 * to the $audience parameter
916 * @return string
917 */
918 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
919 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
920 return '';
921 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
922 return '';
923 } else {
924 return $this->mComment;
925 }
926 }
927
928 /**
929 * Fetch revision comment without regard for the current user's permissions
930 *
931 * @return string
932 * @deprecated since 1.25, use getComment( Revision::RAW )
933 */
934 public function getRawComment() {
935 wfDeprecated( __METHOD__, '1.25' );
936 return $this->getComment( self::RAW );
937 }
938
939 /**
940 * @return bool
941 */
942 public function isMinor() {
943 return (bool)$this->mMinorEdit;
944 }
945
946 /**
947 * @return int Rcid of the unpatrolled row, zero if there isn't one
948 */
949 public function isUnpatrolled() {
950 if ( $this->mUnpatrolled !== null ) {
951 return $this->mUnpatrolled;
952 }
953 $rc = $this->getRecentChange();
954 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
955 $this->mUnpatrolled = $rc->getAttribute( 'rc_id' );
956 } else {
957 $this->mUnpatrolled = 0;
958 }
959 return $this->mUnpatrolled;
960 }
961
962 /**
963 * Get the RC object belonging to the current revision, if there's one
964 *
965 * @param int $flags (optional) $flags include:
966 * Revision::READ_LATEST : Select the data from the master
967 *
968 * @since 1.22
969 * @return RecentChange|null
970 */
971 public function getRecentChange( $flags = 0 ) {
972 $dbr = wfGetDB( DB_SLAVE );
973
974 list( $dbType, ) = DBAccessObjectUtils::getDBOptions( $flags );
975
976 return RecentChange::newFromConds(
977 [
978 'rc_user_text' => $this->getUserText( Revision::RAW ),
979 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
980 'rc_this_oldid' => $this->getId()
981 ],
982 __METHOD__,
983 $dbType
984 );
985 }
986
987 /**
988 * @param int $field One of DELETED_* bitfield constants
989 *
990 * @return bool
991 */
992 public function isDeleted( $field ) {
993 return ( $this->mDeleted & $field ) == $field;
994 }
995
996 /**
997 * Get the deletion bitfield of the revision
998 *
999 * @return int
1000 */
1001 public function getVisibility() {
1002 return (int)$this->mDeleted;
1003 }
1004
1005 /**
1006 * Fetch revision text if it's available to the specified audience.
1007 * If the specified audience does not have the ability to view this
1008 * revision, an empty string will be returned.
1009 *
1010 * @param int $audience One of:
1011 * Revision::FOR_PUBLIC to be displayed to all users
1012 * Revision::FOR_THIS_USER to be displayed to the given user
1013 * Revision::RAW get the text regardless of permissions
1014 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1015 * to the $audience parameter
1016 *
1017 * @deprecated since 1.21, use getContent() instead
1018 * @todo Replace usage in core
1019 * @return string
1020 */
1021 public function getText( $audience = self::FOR_PUBLIC, User $user = null ) {
1022 ContentHandler::deprecated( __METHOD__, '1.21' );
1023
1024 $content = $this->getContent( $audience, $user );
1025 return ContentHandler::getContentText( $content ); # returns the raw content text, if applicable
1026 }
1027
1028 /**
1029 * Fetch revision content if it's available to the specified audience.
1030 * If the specified audience does not have the ability to view this
1031 * revision, null will be returned.
1032 *
1033 * @param int $audience One of:
1034 * Revision::FOR_PUBLIC to be displayed to all users
1035 * Revision::FOR_THIS_USER to be displayed to $wgUser
1036 * Revision::RAW get the text regardless of permissions
1037 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1038 * to the $audience parameter
1039 * @since 1.21
1040 * @return Content|null
1041 */
1042 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
1043 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
1044 return null;
1045 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
1046 return null;
1047 } else {
1048 return $this->getContentInternal();
1049 }
1050 }
1051
1052 /**
1053 * Fetch original serialized data without regard for view restrictions
1054 *
1055 * @since 1.21
1056 * @return string
1057 */
1058 public function getSerializedData() {
1059 if ( $this->mText === null ) {
1060 $this->mText = $this->loadText();
1061 }
1062
1063 return $this->mText;
1064 }
1065
1066 /**
1067 * Gets the content object for the revision (or null on failure).
1068 *
1069 * Note that for mutable Content objects, each call to this method will return a
1070 * fresh clone.
1071 *
1072 * @since 1.21
1073 * @return Content|null The Revision's content, or null on failure.
1074 */
1075 protected function getContentInternal() {
1076 if ( $this->mContent === null ) {
1077 // Revision is immutable. Load on demand:
1078 if ( $this->mText === null ) {
1079 $this->mText = $this->loadText();
1080 }
1081
1082 if ( $this->mText !== null && $this->mText !== false ) {
1083 // Unserialize content
1084 $handler = $this->getContentHandler();
1085 $format = $this->getContentFormat();
1086
1087 $this->mContent = $handler->unserializeContent( $this->mText, $format );
1088 }
1089 }
1090
1091 // NOTE: copy() will return $this for immutable content objects
1092 return $this->mContent ? $this->mContent->copy() : null;
1093 }
1094
1095 /**
1096 * Returns the content model for this revision.
1097 *
1098 * If no content model was stored in the database, the default content model for the title is
1099 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1100 * is used as a last resort.
1101 *
1102 * @return string The content model id associated with this revision,
1103 * see the CONTENT_MODEL_XXX constants.
1104 **/
1105 public function getContentModel() {
1106 if ( !$this->mContentModel ) {
1107 $title = $this->getTitle();
1108 if ( $title ) {
1109 $this->mContentModel = ContentHandler::getDefaultModelFor( $title );
1110 } else {
1111 $this->mContentModel = CONTENT_MODEL_WIKITEXT;
1112 }
1113
1114 assert( !empty( $this->mContentModel ) );
1115 }
1116
1117 return $this->mContentModel;
1118 }
1119
1120 /**
1121 * Returns the content format for this revision.
1122 *
1123 * If no content format was stored in the database, the default format for this
1124 * revision's content model is returned.
1125 *
1126 * @return string The content format id associated with this revision,
1127 * see the CONTENT_FORMAT_XXX constants.
1128 **/
1129 public function getContentFormat() {
1130 if ( !$this->mContentFormat ) {
1131 $handler = $this->getContentHandler();
1132 $this->mContentFormat = $handler->getDefaultFormat();
1133
1134 assert( !empty( $this->mContentFormat ) );
1135 }
1136
1137 return $this->mContentFormat;
1138 }
1139
1140 /**
1141 * Returns the content handler appropriate for this revision's content model.
1142 *
1143 * @throws MWException
1144 * @return ContentHandler
1145 */
1146 public function getContentHandler() {
1147 if ( !$this->mContentHandler ) {
1148 $model = $this->getContentModel();
1149 $this->mContentHandler = ContentHandler::getForModelID( $model );
1150
1151 $format = $this->getContentFormat();
1152
1153 if ( !$this->mContentHandler->isSupportedFormat( $format ) ) {
1154 throw new MWException( "Oops, the content format $format is not supported for "
1155 . "this content model, $model" );
1156 }
1157 }
1158
1159 return $this->mContentHandler;
1160 }
1161
1162 /**
1163 * @return string
1164 */
1165 public function getTimestamp() {
1166 return wfTimestamp( TS_MW, $this->mTimestamp );
1167 }
1168
1169 /**
1170 * @return bool
1171 */
1172 public function isCurrent() {
1173 return $this->mCurrent;
1174 }
1175
1176 /**
1177 * Get previous revision for this title
1178 *
1179 * @return Revision|null
1180 */
1181 public function getPrevious() {
1182 if ( $this->getTitle() ) {
1183 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1184 if ( $prev ) {
1185 return self::newFromTitle( $this->getTitle(), $prev );
1186 }
1187 }
1188 return null;
1189 }
1190
1191 /**
1192 * Get next revision for this title
1193 *
1194 * @return Revision|null
1195 */
1196 public function getNext() {
1197 if ( $this->getTitle() ) {
1198 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1199 if ( $next ) {
1200 return self::newFromTitle( $this->getTitle(), $next );
1201 }
1202 }
1203 return null;
1204 }
1205
1206 /**
1207 * Get previous revision Id for this page_id
1208 * This is used to populate rev_parent_id on save
1209 *
1210 * @param IDatabase $db
1211 * @return int
1212 */
1213 private function getPreviousRevisionId( $db ) {
1214 if ( $this->mPage === null ) {
1215 return 0;
1216 }
1217 # Use page_latest if ID is not given
1218 if ( !$this->mId ) {
1219 $prevId = $db->selectField( 'page', 'page_latest',
1220 [ 'page_id' => $this->mPage ],
1221 __METHOD__ );
1222 } else {
1223 $prevId = $db->selectField( 'revision', 'rev_id',
1224 [ 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ],
1225 __METHOD__,
1226 [ 'ORDER BY' => 'rev_id DESC' ] );
1227 }
1228 return intval( $prevId );
1229 }
1230
1231 /**
1232 * Get revision text associated with an old or archive row
1233 * $row is usually an object from wfFetchRow(), both the flags and the text
1234 * field must be included.
1235 *
1236 * @param stdClass $row The text data
1237 * @param string $prefix Table prefix (default 'old_')
1238 * @param string|bool $wiki The name of the wiki to load the revision text from
1239 * (same as the the wiki $row was loaded from) or false to indicate the local
1240 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1241 * identifier as understood by the LoadBalancer class.
1242 * @return string Text the text requested or false on failure
1243 */
1244 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1245
1246 # Get data
1247 $textField = $prefix . 'text';
1248 $flagsField = $prefix . 'flags';
1249
1250 if ( isset( $row->$flagsField ) ) {
1251 $flags = explode( ',', $row->$flagsField );
1252 } else {
1253 $flags = [];
1254 }
1255
1256 if ( isset( $row->$textField ) ) {
1257 $text = $row->$textField;
1258 } else {
1259 return false;
1260 }
1261
1262 # Use external methods for external objects, text in table is URL-only then
1263 if ( in_array( 'external', $flags ) ) {
1264 $url = $text;
1265 $parts = explode( '://', $url, 2 );
1266 if ( count( $parts ) == 1 || $parts[1] == '' ) {
1267 return false;
1268 }
1269 $text = ExternalStore::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1270 }
1271
1272 // If the text was fetched without an error, convert it
1273 if ( $text !== false ) {
1274 $text = self::decompressRevisionText( $text, $flags );
1275 }
1276 return $text;
1277 }
1278
1279 /**
1280 * If $wgCompressRevisions is enabled, we will compress data.
1281 * The input string is modified in place.
1282 * Return value is the flags field: contains 'gzip' if the
1283 * data is compressed, and 'utf-8' if we're saving in UTF-8
1284 * mode.
1285 *
1286 * @param mixed $text Reference to a text
1287 * @return string
1288 */
1289 public static function compressRevisionText( &$text ) {
1290 global $wgCompressRevisions;
1291 $flags = [];
1292
1293 # Revisions not marked this way will be converted
1294 # on load if $wgLegacyCharset is set in the future.
1295 $flags[] = 'utf-8';
1296
1297 if ( $wgCompressRevisions ) {
1298 if ( function_exists( 'gzdeflate' ) ) {
1299 $deflated = gzdeflate( $text );
1300
1301 if ( $deflated === false ) {
1302 wfLogWarning( __METHOD__ . ': gzdeflate() failed' );
1303 } else {
1304 $text = $deflated;
1305 $flags[] = 'gzip';
1306 }
1307 } else {
1308 wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" );
1309 }
1310 }
1311 return implode( ',', $flags );
1312 }
1313
1314 /**
1315 * Re-converts revision text according to it's flags.
1316 *
1317 * @param mixed $text Reference to a text
1318 * @param array $flags Compression flags
1319 * @return string|bool Decompressed text, or false on failure
1320 */
1321 public static function decompressRevisionText( $text, $flags ) {
1322 if ( in_array( 'gzip', $flags ) ) {
1323 # Deal with optional compression of archived pages.
1324 # This can be done periodically via maintenance/compressOld.php, and
1325 # as pages are saved if $wgCompressRevisions is set.
1326 $text = gzinflate( $text );
1327
1328 if ( $text === false ) {
1329 wfLogWarning( __METHOD__ . ': gzinflate() failed' );
1330 return false;
1331 }
1332 }
1333
1334 if ( in_array( 'object', $flags ) ) {
1335 # Generic compressed storage
1336 $obj = unserialize( $text );
1337 if ( !is_object( $obj ) ) {
1338 // Invalid object
1339 return false;
1340 }
1341 $text = $obj->getText();
1342 }
1343
1344 global $wgLegacyEncoding;
1345 if ( $text !== false && $wgLegacyEncoding
1346 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1347 ) {
1348 # Old revisions kept around in a legacy encoding?
1349 # Upconvert on demand.
1350 # ("utf8" checked for compatibility with some broken
1351 # conversion scripts 2008-12-30)
1352 global $wgContLang;
1353 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1354 }
1355
1356 return $text;
1357 }
1358
1359 /**
1360 * Insert a new revision into the database, returning the new revision ID
1361 * number on success and dies horribly on failure.
1362 *
1363 * @param IDatabase $dbw (master connection)
1364 * @throws MWException
1365 * @return int
1366 */
1367 public function insertOn( $dbw ) {
1368 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1369
1370 // Not allowed to have rev_page equal to 0, false, etc.
1371 if ( !$this->mPage ) {
1372 $title = $this->getTitle();
1373 if ( $title instanceof Title ) {
1374 $titleText = ' for page ' . $title->getPrefixedText();
1375 } else {
1376 $titleText = '';
1377 }
1378 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1379 }
1380
1381 $this->checkContentModel();
1382
1383 $data = $this->mText;
1384 $flags = self::compressRevisionText( $data );
1385
1386 # Write to external storage if required
1387 if ( $wgDefaultExternalStore ) {
1388 // Store and get the URL
1389 $data = ExternalStore::insertToDefault( $data );
1390 if ( !$data ) {
1391 throw new MWException( "Unable to store text to external storage" );
1392 }
1393 if ( $flags ) {
1394 $flags .= ',';
1395 }
1396 $flags .= 'external';
1397 }
1398
1399 # Record the text (or external storage URL) to the text table
1400 if ( $this->mTextId === null ) {
1401 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1402 $dbw->insert( 'text',
1403 [
1404 'old_id' => $old_id,
1405 'old_text' => $data,
1406 'old_flags' => $flags,
1407 ], __METHOD__
1408 );
1409 $this->mTextId = $dbw->insertId();
1410 }
1411
1412 if ( $this->mComment === null ) {
1413 $this->mComment = "";
1414 }
1415
1416 # Record the edit in revisions
1417 $rev_id = $this->mId !== null
1418 ? $this->mId
1419 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1420 $row = [
1421 'rev_id' => $rev_id,
1422 'rev_page' => $this->mPage,
1423 'rev_text_id' => $this->mTextId,
1424 'rev_comment' => $this->mComment,
1425 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1426 'rev_user' => $this->mUser,
1427 'rev_user_text' => $this->mUserText,
1428 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1429 'rev_deleted' => $this->mDeleted,
1430 'rev_len' => $this->mSize,
1431 'rev_parent_id' => $this->mParentId === null
1432 ? $this->getPreviousRevisionId( $dbw )
1433 : $this->mParentId,
1434 'rev_sha1' => $this->mSha1 === null
1435 ? Revision::base36Sha1( $this->mText )
1436 : $this->mSha1,
1437 ];
1438
1439 if ( $wgContentHandlerUseDB ) {
1440 // NOTE: Store null for the default model and format, to save space.
1441 // XXX: Makes the DB sensitive to changed defaults.
1442 // Make this behavior optional? Only in miser mode?
1443
1444 $model = $this->getContentModel();
1445 $format = $this->getContentFormat();
1446
1447 $title = $this->getTitle();
1448
1449 if ( $title === null ) {
1450 throw new MWException( "Insufficient information to determine the title of the "
1451 . "revision's page!" );
1452 }
1453
1454 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1455 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
1456
1457 $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
1458 $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
1459 }
1460
1461 $dbw->insert( 'revision', $row, __METHOD__ );
1462
1463 $this->mId = $rev_id !== null ? $rev_id : $dbw->insertId();
1464
1465 // Assertion to try to catch T92046
1466 if ( (int)$this->mId === 0 ) {
1467 throw new UnexpectedValueException(
1468 'After insert, Revision mId is ' . var_export( $this->mId, 1 ) . ': ' .
1469 var_export( $row, 1 )
1470 );
1471 }
1472
1473 Hooks::run( 'RevisionInsertComplete', [ &$this, $data, $flags ] );
1474
1475 return $this->mId;
1476 }
1477
1478 protected function checkContentModel() {
1479 global $wgContentHandlerUseDB;
1480
1481 // Note: may return null for revisions that have not yet been inserted
1482 $title = $this->getTitle();
1483
1484 $model = $this->getContentModel();
1485 $format = $this->getContentFormat();
1486 $handler = $this->getContentHandler();
1487
1488 if ( !$handler->isSupportedFormat( $format ) ) {
1489 $t = $title->getPrefixedDBkey();
1490
1491 throw new MWException( "Can't use format $format with content model $model on $t" );
1492 }
1493
1494 if ( !$wgContentHandlerUseDB && $title ) {
1495 // if $wgContentHandlerUseDB is not set,
1496 // all revisions must use the default content model and format.
1497
1498 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1499 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
1500 $defaultFormat = $defaultHandler->getDefaultFormat();
1501
1502 if ( $this->getContentModel() != $defaultModel ) {
1503 $t = $title->getPrefixedDBkey();
1504
1505 throw new MWException( "Can't save non-default content model with "
1506 . "\$wgContentHandlerUseDB disabled: model is $model, "
1507 . "default for $t is $defaultModel" );
1508 }
1509
1510 if ( $this->getContentFormat() != $defaultFormat ) {
1511 $t = $title->getPrefixedDBkey();
1512
1513 throw new MWException( "Can't use non-default content format with "
1514 . "\$wgContentHandlerUseDB disabled: format is $format, "
1515 . "default for $t is $defaultFormat" );
1516 }
1517 }
1518
1519 $content = $this->getContent( Revision::RAW );
1520 $prefixedDBkey = $title->getPrefixedDBkey();
1521 $revId = $this->mId;
1522
1523 if ( !$content ) {
1524 throw new MWException(
1525 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1526 );
1527 }
1528 if ( !$content->isValid() ) {
1529 throw new MWException(
1530 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1531 );
1532 }
1533 }
1534
1535 /**
1536 * Get the base 36 SHA-1 value for a string of text
1537 * @param string $text
1538 * @return string
1539 */
1540 public static function base36Sha1( $text ) {
1541 return Wikimedia\base_convert( sha1( $text ), 16, 36, 31 );
1542 }
1543
1544 /**
1545 * Lazy-load the revision's text.
1546 * Currently hardcoded to the 'text' table storage engine.
1547 *
1548 * @return string|bool The revision's text, or false on failure
1549 */
1550 protected function loadText() {
1551 // Caching may be beneficial for massive use of external storage
1552 global $wgRevisionCacheExpiry;
1553 static $processCache = null;
1554
1555 if ( !$processCache ) {
1556 $processCache = new MapCacheLRU( 10 );
1557 }
1558
1559 $cache = ObjectCache::getMainWANInstance();
1560 $textId = $this->getTextId();
1561 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1562
1563 if ( $wgRevisionCacheExpiry ) {
1564 if ( $processCache->has( $key ) ) {
1565 return $processCache->get( $key );
1566 }
1567 $text = $cache->get( $key );
1568 if ( is_string( $text ) ) {
1569 $processCache->set( $key, $text );
1570 return $text;
1571 }
1572 }
1573
1574 // If we kept data for lazy extraction, use it now...
1575 if ( $this->mTextRow !== null ) {
1576 $row = $this->mTextRow;
1577 $this->mTextRow = null;
1578 } else {
1579 $row = null;
1580 }
1581
1582 if ( !$row ) {
1583 // Text data is immutable; check slaves first.
1584 $dbr = wfGetDB( DB_SLAVE );
1585 $row = $dbr->selectRow( 'text',
1586 [ 'old_text', 'old_flags' ],
1587 [ 'old_id' => $textId ],
1588 __METHOD__ );
1589 }
1590
1591 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1592 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1593 $forUpdate = ( $this->mQueryFlags & self::READ_LOCKING == self::READ_LOCKING );
1594 if ( !$row && ( $forUpdate || wfGetLB()->getServerCount() > 1 ) ) {
1595 $dbw = wfGetDB( DB_MASTER );
1596 $row = $dbw->selectRow( 'text',
1597 [ 'old_text', 'old_flags' ],
1598 [ 'old_id' => $textId ],
1599 __METHOD__,
1600 $forUpdate ? [ 'FOR UPDATE' ] : [] );
1601 }
1602
1603 if ( !$row ) {
1604 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1605 }
1606
1607 $text = self::getRevisionText( $row );
1608 if ( $row && $text === false ) {
1609 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1610 }
1611
1612 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1613 if ( $wgRevisionCacheExpiry && $text !== false ) {
1614 $processCache->set( $key, $text );
1615 $cache->set( $key, $text, $wgRevisionCacheExpiry );
1616 }
1617
1618 return $text;
1619 }
1620
1621 /**
1622 * Create a new null-revision for insertion into a page's
1623 * history. This will not re-save the text, but simply refer
1624 * to the text from the previous version.
1625 *
1626 * Such revisions can for instance identify page rename
1627 * operations and other such meta-modifications.
1628 *
1629 * @param IDatabase $dbw
1630 * @param int $pageId ID number of the page to read from
1631 * @param string $summary Revision's summary
1632 * @param bool $minor Whether the revision should be considered as minor
1633 * @param User|null $user User object to use or null for $wgUser
1634 * @return Revision|null Revision or null on error
1635 */
1636 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1637 global $wgContentHandlerUseDB, $wgContLang;
1638
1639 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1640 'rev_text_id', 'rev_len', 'rev_sha1' ];
1641
1642 if ( $wgContentHandlerUseDB ) {
1643 $fields[] = 'rev_content_model';
1644 $fields[] = 'rev_content_format';
1645 }
1646
1647 $current = $dbw->selectRow(
1648 [ 'page', 'revision' ],
1649 $fields,
1650 [
1651 'page_id' => $pageId,
1652 'page_latest=rev_id',
1653 ],
1654 __METHOD__,
1655 [ 'FOR UPDATE' ] // T51581
1656 );
1657
1658 if ( $current ) {
1659 if ( !$user ) {
1660 global $wgUser;
1661 $user = $wgUser;
1662 }
1663
1664 // Truncate for whole multibyte characters
1665 $summary = $wgContLang->truncate( $summary, 255 );
1666
1667 $row = [
1668 'page' => $pageId,
1669 'user_text' => $user->getName(),
1670 'user' => $user->getId(),
1671 'comment' => $summary,
1672 'minor_edit' => $minor,
1673 'text_id' => $current->rev_text_id,
1674 'parent_id' => $current->page_latest,
1675 'len' => $current->rev_len,
1676 'sha1' => $current->rev_sha1
1677 ];
1678
1679 if ( $wgContentHandlerUseDB ) {
1680 $row['content_model'] = $current->rev_content_model;
1681 $row['content_format'] = $current->rev_content_format;
1682 }
1683
1684 $row['title'] = Title::makeTitle( $current->page_namespace, $current->page_title );
1685
1686 $revision = new Revision( $row );
1687 } else {
1688 $revision = null;
1689 }
1690
1691 return $revision;
1692 }
1693
1694 /**
1695 * Determine if the current user is allowed to view a particular
1696 * field of this revision, if it's marked as deleted.
1697 *
1698 * @param int $field One of self::DELETED_TEXT,
1699 * self::DELETED_COMMENT,
1700 * self::DELETED_USER
1701 * @param User|null $user User object to check, or null to use $wgUser
1702 * @return bool
1703 */
1704 public function userCan( $field, User $user = null ) {
1705 return self::userCanBitfield( $this->mDeleted, $field, $user );
1706 }
1707
1708 /**
1709 * Determine if the current user is allowed to view a particular
1710 * field of this revision, if it's marked as deleted. This is used
1711 * by various classes to avoid duplication.
1712 *
1713 * @param int $bitfield Current field
1714 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1715 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1716 * self::DELETED_USER = File::DELETED_USER
1717 * @param User|null $user User object to check, or null to use $wgUser
1718 * @param Title|null $title A Title object to check for per-page restrictions on,
1719 * instead of just plain userrights
1720 * @return bool
1721 */
1722 public static function userCanBitfield( $bitfield, $field, User $user = null,
1723 Title $title = null
1724 ) {
1725 if ( $bitfield & $field ) { // aspect is deleted
1726 if ( $user === null ) {
1727 global $wgUser;
1728 $user = $wgUser;
1729 }
1730 if ( $bitfield & self::DELETED_RESTRICTED ) {
1731 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1732 } elseif ( $field & self::DELETED_TEXT ) {
1733 $permissions = [ 'deletedtext' ];
1734 } else {
1735 $permissions = [ 'deletedhistory' ];
1736 }
1737 $permissionlist = implode( ', ', $permissions );
1738 if ( $title === null ) {
1739 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1740 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1741 } else {
1742 $text = $title->getPrefixedText();
1743 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1744 foreach ( $permissions as $perm ) {
1745 if ( $title->userCan( $perm, $user ) ) {
1746 return true;
1747 }
1748 }
1749 return false;
1750 }
1751 } else {
1752 return true;
1753 }
1754 }
1755
1756 /**
1757 * Get rev_timestamp from rev_id, without loading the rest of the row
1758 *
1759 * @param Title $title
1760 * @param int $id
1761 * @return string|bool False if not found
1762 */
1763 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1764 $db = ( $flags & self::READ_LATEST )
1765 ? wfGetDB( DB_MASTER )
1766 : wfGetDB( DB_SLAVE );
1767 // Casting fix for databases that can't take '' for rev_id
1768 if ( $id == '' ) {
1769 $id = 0;
1770 }
1771 $conds = [ 'rev_id' => $id ];
1772 $conds['rev_page'] = $title->getArticleID();
1773 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1774
1775 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
1776 }
1777
1778 /**
1779 * Get count of revisions per page...not very efficient
1780 *
1781 * @param IDatabase $db
1782 * @param int $id Page id
1783 * @return int
1784 */
1785 static function countByPageId( $db, $id ) {
1786 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
1787 [ 'rev_page' => $id ], __METHOD__ );
1788 if ( $row ) {
1789 return $row->revCount;
1790 }
1791 return 0;
1792 }
1793
1794 /**
1795 * Get count of revisions per page...not very efficient
1796 *
1797 * @param IDatabase $db
1798 * @param Title $title
1799 * @return int
1800 */
1801 static function countByTitle( $db, $title ) {
1802 $id = $title->getArticleID();
1803 if ( $id ) {
1804 return self::countByPageId( $db, $id );
1805 }
1806 return 0;
1807 }
1808
1809 /**
1810 * Check if no edits were made by other users since
1811 * the time a user started editing the page. Limit to
1812 * 50 revisions for the sake of performance.
1813 *
1814 * @since 1.20
1815 * @deprecated since 1.24
1816 *
1817 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1818 * Database object or a database identifier usable with wfGetDB.
1819 * @param int $pageId The ID of the page in question
1820 * @param int $userId The ID of the user in question
1821 * @param string $since Look at edits since this time
1822 *
1823 * @return bool True if the given user was the only one to edit since the given timestamp
1824 */
1825 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1826 if ( !$userId ) {
1827 return false;
1828 }
1829
1830 if ( is_int( $db ) ) {
1831 $db = wfGetDB( $db );
1832 }
1833
1834 $res = $db->select( 'revision',
1835 'rev_user',
1836 [
1837 'rev_page' => $pageId,
1838 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1839 ],
1840 __METHOD__,
1841 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
1842 foreach ( $res as $row ) {
1843 if ( $row->rev_user != $userId ) {
1844 return false;
1845 }
1846 }
1847 return true;
1848 }
1849 }