Merge "Add tags for undo edits"
[lhc/web/wiklou.git] / includes / page / WikiPage.php
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
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\Edit\PreparedEdit;
24 use \MediaWiki\Logger\LoggerFactory;
25 use \MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27 use Wikimedia\Rdbms\IDatabase;
28 use Wikimedia\Rdbms\DBError;
29 use Wikimedia\Rdbms\DBUnexpectedError;
30
31 /**
32 * Class representing a MediaWiki article and history.
33 *
34 * Some fields are public only for backwards-compatibility. Use accessors.
35 * In the past, this class was part of Article.php and everything was public.
36 */
37 class WikiPage implements Page, IDBAccessObject {
38 // Constants for $mDataLoadedFrom and related
39
40 /**
41 * @var Title
42 */
43 public $mTitle = null;
44
45 /**@{{
46 * @protected
47 */
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 /**@}}*/
52
53 /** @var PreparedEdit Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
55
56 /**
57 * @var int
58 */
59 protected $mId = null;
60
61 /**
62 * @var int One of the READ_* constants
63 */
64 protected $mDataLoadedFrom = self::READ_NONE;
65
66 /**
67 * @var Title
68 */
69 protected $mRedirectTarget = null;
70
71 /**
72 * @var Revision
73 */
74 protected $mLastRevision = null;
75
76 /**
77 * @var string Timestamp of the current revision or empty string if not loaded
78 */
79 protected $mTimestamp = '';
80
81 /**
82 * @var string
83 */
84 protected $mTouched = '19700101000000';
85
86 /**
87 * @var string
88 */
89 protected $mLinksUpdated = '19700101000000';
90
91 /**
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
94 */
95 public function __construct( Title $title ) {
96 $this->mTitle = $title;
97 }
98
99 /**
100 * Makes sure that the mTitle object is cloned
101 * to the newly cloned WikiPage.
102 */
103 public function __clone() {
104 $this->mTitle = clone $this->mTitle;
105 }
106
107 /**
108 * Create a WikiPage object of the appropriate class for the given title.
109 *
110 * @param Title $title
111 *
112 * @throws MWException
113 * @return WikiPage|WikiCategoryPage|WikiFilePage
114 */
115 public static function factory( Title $title ) {
116 $ns = $title->getNamespace();
117
118 if ( $ns == NS_MEDIA ) {
119 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
120 } elseif ( $ns < 0 ) {
121 throw new MWException( "Invalid or virtual namespace $ns given." );
122 }
123
124 $page = null;
125 if ( !Hooks::run( 'WikiPageFactory', [ $title, &$page ] ) ) {
126 return $page;
127 }
128
129 switch ( $ns ) {
130 case NS_FILE:
131 $page = new WikiFilePage( $title );
132 break;
133 case NS_CATEGORY:
134 $page = new WikiCategoryPage( $title );
135 break;
136 default:
137 $page = new WikiPage( $title );
138 }
139
140 return $page;
141 }
142
143 /**
144 * Constructor from a page id
145 *
146 * @param int $id Article ID to load
147 * @param string|int $from One of the following values:
148 * - "fromdb" or WikiPage::READ_NORMAL to select from a replica DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
150 *
151 * @return WikiPage|null
152 */
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 // page ids are never 0 or negative, see T63166
155 if ( $id < 1 ) {
156 return null;
157 }
158
159 $from = self::convertSelectType( $from );
160 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_REPLICA );
161 $pageQuery = self::getQueryInfo();
162 $row = $db->selectRow(
163 $pageQuery['tables'], $pageQuery['fields'], [ 'page_id' => $id ], __METHOD__,
164 [], $pageQuery['joins']
165 );
166 if ( !$row ) {
167 return null;
168 }
169 return self::newFromRow( $row, $from );
170 }
171
172 /**
173 * Constructor from a database row
174 *
175 * @since 1.20
176 * @param object $row Database row containing at least fields returned by selectFields().
177 * @param string|int $from Source of $data:
178 * - "fromdb" or WikiPage::READ_NORMAL: from a replica DB
179 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
180 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
181 * @return WikiPage
182 */
183 public static function newFromRow( $row, $from = 'fromdb' ) {
184 $page = self::factory( Title::newFromRow( $row ) );
185 $page->loadFromRow( $row, $from );
186 return $page;
187 }
188
189 /**
190 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
191 *
192 * @param object|string|int $type
193 * @return mixed
194 */
195 private static function convertSelectType( $type ) {
196 switch ( $type ) {
197 case 'fromdb':
198 return self::READ_NORMAL;
199 case 'fromdbmaster':
200 return self::READ_LATEST;
201 case 'forupdate':
202 return self::READ_LOCKING;
203 default:
204 // It may already be an integer or whatever else
205 return $type;
206 }
207 }
208
209 /**
210 * @todo Move this UI stuff somewhere else
211 *
212 * @see ContentHandler::getActionOverrides
213 * @return array
214 */
215 public function getActionOverrides() {
216 return $this->getContentHandler()->getActionOverrides();
217 }
218
219 /**
220 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
221 *
222 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
223 *
224 * @return ContentHandler
225 *
226 * @since 1.21
227 */
228 public function getContentHandler() {
229 return ContentHandler::getForModelID( $this->getContentModel() );
230 }
231
232 /**
233 * Get the title object of the article
234 * @return Title Title object of this page
235 */
236 public function getTitle() {
237 return $this->mTitle;
238 }
239
240 /**
241 * Clear the object
242 * @return void
243 */
244 public function clear() {
245 $this->mDataLoaded = false;
246 $this->mDataLoadedFrom = self::READ_NONE;
247
248 $this->clearCacheFields();
249 }
250
251 /**
252 * Clear the object cache fields
253 * @return void
254 */
255 protected function clearCacheFields() {
256 $this->mId = null;
257 $this->mRedirectTarget = null; // Title object if set
258 $this->mLastRevision = null; // Latest revision
259 $this->mTouched = '19700101000000';
260 $this->mLinksUpdated = '19700101000000';
261 $this->mTimestamp = '';
262 $this->mIsRedirect = false;
263 $this->mLatest = false;
264 // T59026: do not clear mPreparedEdit since prepareTextForEdit() already checks
265 // the requested rev ID and content against the cached one for equality. For most
266 // content types, the output should not change during the lifetime of this cache.
267 // Clearing it can cause extra parses on edit for no reason.
268 }
269
270 /**
271 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
272 * @return void
273 * @since 1.23
274 */
275 public function clearPreparedEdit() {
276 $this->mPreparedEdit = false;
277 }
278
279 /**
280 * Return the list of revision fields that should be selected to create
281 * a new page.
282 *
283 * @deprecated since 1.31, use self::getQueryInfo() instead.
284 * @return array
285 */
286 public static function selectFields() {
287 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
288
289 wfDeprecated( __METHOD__, '1.31' );
290
291 $fields = [
292 'page_id',
293 'page_namespace',
294 'page_title',
295 'page_restrictions',
296 'page_is_redirect',
297 'page_is_new',
298 'page_random',
299 'page_touched',
300 'page_links_updated',
301 'page_latest',
302 'page_len',
303 ];
304
305 if ( $wgContentHandlerUseDB ) {
306 $fields[] = 'page_content_model';
307 }
308
309 if ( $wgPageLanguageUseDB ) {
310 $fields[] = 'page_lang';
311 }
312
313 return $fields;
314 }
315
316 /**
317 * Return the tables, fields, and join conditions to be selected to create
318 * a new page object.
319 * @since 1.31
320 * @return array With three keys:
321 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
322 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
323 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
324 */
325 public static function getQueryInfo() {
326 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
327
328 $ret = [
329 'tables' => [ 'page' ],
330 'fields' => [
331 'page_id',
332 'page_namespace',
333 'page_title',
334 'page_restrictions',
335 'page_is_redirect',
336 'page_is_new',
337 'page_random',
338 'page_touched',
339 'page_links_updated',
340 'page_latest',
341 'page_len',
342 ],
343 'joins' => [],
344 ];
345
346 if ( $wgContentHandlerUseDB ) {
347 $ret['fields'][] = 'page_content_model';
348 }
349
350 if ( $wgPageLanguageUseDB ) {
351 $ret['fields'][] = 'page_lang';
352 }
353
354 return $ret;
355 }
356
357 /**
358 * Fetch a page record with the given conditions
359 * @param IDatabase $dbr
360 * @param array $conditions
361 * @param array $options
362 * @return object|bool Database result resource, or false on failure
363 */
364 protected function pageData( $dbr, $conditions, $options = [] ) {
365 $pageQuery = self::getQueryInfo();
366
367 // Avoid PHP 7.1 warning of passing $this by reference
368 $wikiPage = $this;
369
370 Hooks::run( 'ArticlePageDataBefore', [
371 &$wikiPage, &$pageQuery['fields'], &$pageQuery['tables'], &$pageQuery['joins']
372 ] );
373
374 $row = $dbr->selectRow(
375 $pageQuery['tables'],
376 $pageQuery['fields'],
377 $conditions,
378 __METHOD__,
379 $options,
380 $pageQuery['joins']
381 );
382
383 Hooks::run( 'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
384
385 return $row;
386 }
387
388 /**
389 * Fetch a page record matching the Title object's namespace and title
390 * using a sanitized title string
391 *
392 * @param IDatabase $dbr
393 * @param Title $title
394 * @param array $options
395 * @return object|bool Database result resource, or false on failure
396 */
397 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
398 return $this->pageData( $dbr, [
399 'page_namespace' => $title->getNamespace(),
400 'page_title' => $title->getDBkey() ], $options );
401 }
402
403 /**
404 * Fetch a page record matching the requested ID
405 *
406 * @param IDatabase $dbr
407 * @param int $id
408 * @param array $options
409 * @return object|bool Database result resource, or false on failure
410 */
411 public function pageDataFromId( $dbr, $id, $options = [] ) {
412 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
413 }
414
415 /**
416 * Load the object from a given source by title
417 *
418 * @param object|string|int $from One of the following:
419 * - A DB query result object.
420 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
421 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
422 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
423 * using SELECT FOR UPDATE.
424 *
425 * @return void
426 */
427 public function loadPageData( $from = 'fromdb' ) {
428 $from = self::convertSelectType( $from );
429 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
430 // We already have the data from the correct location, no need to load it twice.
431 return;
432 }
433
434 if ( is_int( $from ) ) {
435 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
436 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
437 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
438
439 if ( !$data
440 && $index == DB_REPLICA
441 && $loadBalancer->getServerCount() > 1
442 && $loadBalancer->hasOrMadeRecentMasterChanges()
443 ) {
444 $from = self::READ_LATEST;
445 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
446 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
447 }
448 } else {
449 // No idea from where the caller got this data, assume replica DB.
450 $data = $from;
451 $from = self::READ_NORMAL;
452 }
453
454 $this->loadFromRow( $data, $from );
455 }
456
457 /**
458 * Load the object from a database row
459 *
460 * @since 1.20
461 * @param object|bool $data DB row containing fields returned by selectFields() or false
462 * @param string|int $from One of the following:
463 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
464 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
465 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
466 * the master DB using SELECT FOR UPDATE
467 */
468 public function loadFromRow( $data, $from ) {
469 $lc = LinkCache::singleton();
470 $lc->clearLink( $this->mTitle );
471
472 if ( $data ) {
473 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
474
475 $this->mTitle->loadFromRow( $data );
476
477 // Old-fashioned restrictions
478 $this->mTitle->loadRestrictions( $data->page_restrictions );
479
480 $this->mId = intval( $data->page_id );
481 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
482 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
483 $this->mIsRedirect = intval( $data->page_is_redirect );
484 $this->mLatest = intval( $data->page_latest );
485 // T39225: $latest may no longer match the cached latest Revision object.
486 // Double-check the ID of any cached latest Revision object for consistency.
487 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
488 $this->mLastRevision = null;
489 $this->mTimestamp = '';
490 }
491 } else {
492 $lc->addBadLinkObj( $this->mTitle );
493
494 $this->mTitle->loadFromRow( false );
495
496 $this->clearCacheFields();
497
498 $this->mId = 0;
499 }
500
501 $this->mDataLoaded = true;
502 $this->mDataLoadedFrom = self::convertSelectType( $from );
503 }
504
505 /**
506 * @return int Page ID
507 */
508 public function getId() {
509 if ( !$this->mDataLoaded ) {
510 $this->loadPageData();
511 }
512 return $this->mId;
513 }
514
515 /**
516 * @return bool Whether or not the page exists in the database
517 */
518 public function exists() {
519 if ( !$this->mDataLoaded ) {
520 $this->loadPageData();
521 }
522 return $this->mId > 0;
523 }
524
525 /**
526 * Check if this page is something we're going to be showing
527 * some sort of sensible content for. If we return false, page
528 * views (plain action=view) will return an HTTP 404 response,
529 * so spiders and robots can know they're following a bad link.
530 *
531 * @return bool
532 */
533 public function hasViewableContent() {
534 return $this->mTitle->isKnown();
535 }
536
537 /**
538 * Tests if the article content represents a redirect
539 *
540 * @return bool
541 */
542 public function isRedirect() {
543 if ( !$this->mDataLoaded ) {
544 $this->loadPageData();
545 }
546
547 return (bool)$this->mIsRedirect;
548 }
549
550 /**
551 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
552 *
553 * Will use the revisions actual content model if the page exists,
554 * and the page's default if the page doesn't exist yet.
555 *
556 * @return string
557 *
558 * @since 1.21
559 */
560 public function getContentModel() {
561 if ( $this->exists() ) {
562 $cache = ObjectCache::getMainWANInstance();
563
564 return $cache->getWithSetCallback(
565 $cache->makeKey( 'page-content-model', $this->getLatest() ),
566 $cache::TTL_MONTH,
567 function () {
568 $rev = $this->getRevision();
569 if ( $rev ) {
570 // Look at the revision's actual content model
571 return $rev->getContentModel();
572 } else {
573 $title = $this->mTitle->getPrefixedDBkey();
574 wfWarn( "Page $title exists but has no (visible) revisions!" );
575 return $this->mTitle->getContentModel();
576 }
577 }
578 );
579 }
580
581 // use the default model for this page
582 return $this->mTitle->getContentModel();
583 }
584
585 /**
586 * Loads page_touched and returns a value indicating if it should be used
587 * @return bool True if this page exists and is not a redirect
588 */
589 public function checkTouched() {
590 if ( !$this->mDataLoaded ) {
591 $this->loadPageData();
592 }
593 return ( $this->mId && !$this->mIsRedirect );
594 }
595
596 /**
597 * Get the page_touched field
598 * @return string Containing GMT timestamp
599 */
600 public function getTouched() {
601 if ( !$this->mDataLoaded ) {
602 $this->loadPageData();
603 }
604 return $this->mTouched;
605 }
606
607 /**
608 * Get the page_links_updated field
609 * @return string|null Containing GMT timestamp
610 */
611 public function getLinksTimestamp() {
612 if ( !$this->mDataLoaded ) {
613 $this->loadPageData();
614 }
615 return $this->mLinksUpdated;
616 }
617
618 /**
619 * Get the page_latest field
620 * @return int The rev_id of current revision
621 */
622 public function getLatest() {
623 if ( !$this->mDataLoaded ) {
624 $this->loadPageData();
625 }
626 return (int)$this->mLatest;
627 }
628
629 /**
630 * Get the Revision object of the oldest revision
631 * @return Revision|null
632 */
633 public function getOldestRevision() {
634 // Try using the replica DB first, then try the master
635 $rev = $this->mTitle->getFirstRevision();
636 if ( !$rev ) {
637 $rev = $this->mTitle->getFirstRevision( Title::GAID_FOR_UPDATE );
638 }
639 return $rev;
640 }
641
642 /**
643 * Loads everything except the text
644 * This isn't necessary for all uses, so it's only done if needed.
645 */
646 protected function loadLastEdit() {
647 if ( $this->mLastRevision !== null ) {
648 return; // already loaded
649 }
650
651 $latest = $this->getLatest();
652 if ( !$latest ) {
653 return; // page doesn't exist or is missing page_latest info
654 }
655
656 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
657 // T39225: if session S1 loads the page row FOR UPDATE, the result always
658 // includes the latest changes committed. This is true even within REPEATABLE-READ
659 // transactions, where S1 normally only sees changes committed before the first S1
660 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
661 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
662 // happened after the first S1 SELECT.
663 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
664 $flags = Revision::READ_LOCKING;
665 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
666 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
667 // Bug T93976: if page_latest was loaded from the master, fetch the
668 // revision from there as well, as it may not exist yet on a replica DB.
669 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
670 $flags = Revision::READ_LATEST;
671 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
672 } else {
673 $dbr = wfGetDB( DB_REPLICA );
674 $revision = Revision::newKnownCurrent( $dbr, $this->getId(), $latest );
675 }
676
677 if ( $revision ) { // sanity
678 $this->setLastEdit( $revision );
679 }
680 }
681
682 /**
683 * Set the latest revision
684 * @param Revision $revision
685 */
686 protected function setLastEdit( Revision $revision ) {
687 $this->mLastRevision = $revision;
688 $this->mTimestamp = $revision->getTimestamp();
689 }
690
691 /**
692 * Get the latest revision
693 * @return Revision|null
694 */
695 public function getRevision() {
696 $this->loadLastEdit();
697 if ( $this->mLastRevision ) {
698 return $this->mLastRevision;
699 }
700 return null;
701 }
702
703 /**
704 * Get the content of the current revision. No side-effects...
705 *
706 * @param int $audience One of:
707 * Revision::FOR_PUBLIC to be displayed to all users
708 * Revision::FOR_THIS_USER to be displayed to $wgUser
709 * Revision::RAW get the text regardless of permissions
710 * @param User $user User object to check for, only if FOR_THIS_USER is passed
711 * to the $audience parameter
712 * @return Content|null The content of the current revision
713 *
714 * @since 1.21
715 */
716 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
717 $this->loadLastEdit();
718 if ( $this->mLastRevision ) {
719 return $this->mLastRevision->getContent( $audience, $user );
720 }
721 return null;
722 }
723
724 /**
725 * @return string MW timestamp of last article revision
726 */
727 public function getTimestamp() {
728 // Check if the field has been filled by WikiPage::setTimestamp()
729 if ( !$this->mTimestamp ) {
730 $this->loadLastEdit();
731 }
732
733 return wfTimestamp( TS_MW, $this->mTimestamp );
734 }
735
736 /**
737 * Set the page timestamp (use only to avoid DB queries)
738 * @param string $ts MW timestamp of last article revision
739 * @return void
740 */
741 public function setTimestamp( $ts ) {
742 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
743 }
744
745 /**
746 * @param int $audience One of:
747 * Revision::FOR_PUBLIC to be displayed to all users
748 * Revision::FOR_THIS_USER to be displayed to the given user
749 * Revision::RAW get the text regardless of permissions
750 * @param User $user User object to check for, only if FOR_THIS_USER is passed
751 * to the $audience parameter
752 * @return int User ID for the user that made the last article revision
753 */
754 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
755 $this->loadLastEdit();
756 if ( $this->mLastRevision ) {
757 return $this->mLastRevision->getUser( $audience, $user );
758 } else {
759 return -1;
760 }
761 }
762
763 /**
764 * Get the User object of the user who created the page
765 * @param int $audience One of:
766 * Revision::FOR_PUBLIC to be displayed to all users
767 * Revision::FOR_THIS_USER to be displayed to the given user
768 * Revision::RAW get the text regardless of permissions
769 * @param User $user User object to check for, only if FOR_THIS_USER is passed
770 * to the $audience parameter
771 * @return User|null
772 */
773 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
774 $revision = $this->getOldestRevision();
775 if ( $revision ) {
776 $userName = $revision->getUserText( $audience, $user );
777 return User::newFromName( $userName, false );
778 } else {
779 return null;
780 }
781 }
782
783 /**
784 * @param int $audience One of:
785 * Revision::FOR_PUBLIC to be displayed to all users
786 * Revision::FOR_THIS_USER to be displayed to the given user
787 * Revision::RAW get the text regardless of permissions
788 * @param User $user User object to check for, only if FOR_THIS_USER is passed
789 * to the $audience parameter
790 * @return string Username of the user that made the last article revision
791 */
792 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
793 $this->loadLastEdit();
794 if ( $this->mLastRevision ) {
795 return $this->mLastRevision->getUserText( $audience, $user );
796 } else {
797 return '';
798 }
799 }
800
801 /**
802 * @param int $audience One of:
803 * Revision::FOR_PUBLIC to be displayed to all users
804 * Revision::FOR_THIS_USER to be displayed to the given user
805 * Revision::RAW get the text regardless of permissions
806 * @param User $user User object to check for, only if FOR_THIS_USER is passed
807 * to the $audience parameter
808 * @return string Comment stored for the last article revision
809 */
810 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
811 $this->loadLastEdit();
812 if ( $this->mLastRevision ) {
813 return $this->mLastRevision->getComment( $audience, $user );
814 } else {
815 return '';
816 }
817 }
818
819 /**
820 * Returns true if last revision was marked as "minor edit"
821 *
822 * @return bool Minor edit indicator for the last article revision.
823 */
824 public function getMinorEdit() {
825 $this->loadLastEdit();
826 if ( $this->mLastRevision ) {
827 return $this->mLastRevision->isMinor();
828 } else {
829 return false;
830 }
831 }
832
833 /**
834 * Determine whether a page would be suitable for being counted as an
835 * article in the site_stats table based on the title & its content
836 *
837 * @param PreparedEdit|bool $editInfo (false): object returned by prepareTextForEdit(),
838 * if false, the current database state will be used
839 * @return bool
840 */
841 public function isCountable( $editInfo = false ) {
842 global $wgArticleCountMethod;
843
844 if ( !$this->mTitle->isContentPage() ) {
845 return false;
846 }
847
848 if ( $editInfo ) {
849 $content = $editInfo->pstContent;
850 } else {
851 $content = $this->getContent();
852 }
853
854 if ( !$content || $content->isRedirect() ) {
855 return false;
856 }
857
858 $hasLinks = null;
859
860 if ( $wgArticleCountMethod === 'link' ) {
861 // nasty special case to avoid re-parsing to detect links
862
863 if ( $editInfo ) {
864 // ParserOutput::getLinks() is a 2D array of page links, so
865 // to be really correct we would need to recurse in the array
866 // but the main array should only have items in it if there are
867 // links.
868 $hasLinks = (bool)count( $editInfo->output->getLinks() );
869 } else {
870 $hasLinks = (bool)wfGetDB( DB_REPLICA )->selectField( 'pagelinks', 1,
871 [ 'pl_from' => $this->getId() ], __METHOD__ );
872 }
873 }
874
875 return $content->isCountable( $hasLinks );
876 }
877
878 /**
879 * If this page is a redirect, get its target
880 *
881 * The target will be fetched from the redirect table if possible.
882 * If this page doesn't have an entry there, call insertRedirect()
883 * @return Title|null Title object, or null if this page is not a redirect
884 */
885 public function getRedirectTarget() {
886 if ( !$this->mTitle->isRedirect() ) {
887 return null;
888 }
889
890 if ( $this->mRedirectTarget !== null ) {
891 return $this->mRedirectTarget;
892 }
893
894 // Query the redirect table
895 $dbr = wfGetDB( DB_REPLICA );
896 $row = $dbr->selectRow( 'redirect',
897 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
898 [ 'rd_from' => $this->getId() ],
899 __METHOD__
900 );
901
902 // rd_fragment and rd_interwiki were added later, populate them if empty
903 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
904 $this->mRedirectTarget = Title::makeTitle(
905 $row->rd_namespace, $row->rd_title,
906 $row->rd_fragment, $row->rd_interwiki
907 );
908 return $this->mRedirectTarget;
909 }
910
911 // This page doesn't have an entry in the redirect table
912 $this->mRedirectTarget = $this->insertRedirect();
913 return $this->mRedirectTarget;
914 }
915
916 /**
917 * Insert an entry for this page into the redirect table if the content is a redirect
918 *
919 * The database update will be deferred via DeferredUpdates
920 *
921 * Don't call this function directly unless you know what you're doing.
922 * @return Title|null Title object or null if not a redirect
923 */
924 public function insertRedirect() {
925 $content = $this->getContent();
926 $retval = $content ? $content->getUltimateRedirectTarget() : null;
927 if ( !$retval ) {
928 return null;
929 }
930
931 // Update the DB post-send if the page has not cached since now
932 $latest = $this->getLatest();
933 DeferredUpdates::addCallableUpdate(
934 function () use ( $retval, $latest ) {
935 $this->insertRedirectEntry( $retval, $latest );
936 },
937 DeferredUpdates::POSTSEND,
938 wfGetDB( DB_MASTER )
939 );
940
941 return $retval;
942 }
943
944 /**
945 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
946 * @param Title $rt Redirect target
947 * @param int|null $oldLatest Prior page_latest for check and set
948 */
949 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
950 $dbw = wfGetDB( DB_MASTER );
951 $dbw->startAtomic( __METHOD__ );
952
953 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
954 $dbw->upsert(
955 'redirect',
956 [
957 'rd_from' => $this->getId(),
958 'rd_namespace' => $rt->getNamespace(),
959 'rd_title' => $rt->getDBkey(),
960 'rd_fragment' => $rt->getFragment(),
961 'rd_interwiki' => $rt->getInterwiki(),
962 ],
963 [ 'rd_from' ],
964 [
965 'rd_namespace' => $rt->getNamespace(),
966 'rd_title' => $rt->getDBkey(),
967 'rd_fragment' => $rt->getFragment(),
968 'rd_interwiki' => $rt->getInterwiki(),
969 ],
970 __METHOD__
971 );
972 }
973
974 $dbw->endAtomic( __METHOD__ );
975 }
976
977 /**
978 * Get the Title object or URL this page redirects to
979 *
980 * @return bool|Title|string False, Title of in-wiki target, or string with URL
981 */
982 public function followRedirect() {
983 return $this->getRedirectURL( $this->getRedirectTarget() );
984 }
985
986 /**
987 * Get the Title object or URL to use for a redirect. We use Title
988 * objects for same-wiki, non-special redirects and URLs for everything
989 * else.
990 * @param Title $rt Redirect target
991 * @return bool|Title|string False, Title object of local target, or string with URL
992 */
993 public function getRedirectURL( $rt ) {
994 if ( !$rt ) {
995 return false;
996 }
997
998 if ( $rt->isExternal() ) {
999 if ( $rt->isLocal() ) {
1000 // Offsite wikis need an HTTP redirect.
1001 // This can be hard to reverse and may produce loops,
1002 // so they may be disabled in the site configuration.
1003 $source = $this->mTitle->getFullURL( 'redirect=no' );
1004 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1005 } else {
1006 // External pages without "local" bit set are not valid
1007 // redirect targets
1008 return false;
1009 }
1010 }
1011
1012 if ( $rt->isSpecialPage() ) {
1013 // Gotta handle redirects to special pages differently:
1014 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1015 // Some pages are not valid targets.
1016 if ( $rt->isValidRedirectTarget() ) {
1017 return $rt->getFullURL();
1018 } else {
1019 return false;
1020 }
1021 }
1022
1023 return $rt;
1024 }
1025
1026 /**
1027 * Get a list of users who have edited this article, not including the user who made
1028 * the most recent revision, which you can get from $article->getUser() if you want it
1029 * @return UserArrayFromResult
1030 */
1031 public function getContributors() {
1032 // @todo FIXME: This is expensive; cache this info somewhere.
1033
1034 $dbr = wfGetDB( DB_REPLICA );
1035
1036 $tables = [ 'revision', 'user' ];
1037
1038 $fields = [
1039 'user_id' => 'rev_user',
1040 'user_name' => 'rev_user_text',
1041 'user_real_name' => 'MIN(user_real_name)',
1042 'timestamp' => 'MAX(rev_timestamp)',
1043 ];
1044
1045 $conds = [ 'rev_page' => $this->getId() ];
1046
1047 // The user who made the top revision gets credited as "this page was last edited by
1048 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1049 $user = $this->getUser();
1050 if ( $user ) {
1051 $conds[] = "rev_user != $user";
1052 } else {
1053 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1054 }
1055
1056 // Username hidden?
1057 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1058
1059 $jconds = [
1060 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1061 ];
1062
1063 $options = [
1064 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1065 'ORDER BY' => 'timestamp DESC',
1066 ];
1067
1068 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1069 return new UserArrayFromResult( $res );
1070 }
1071
1072 /**
1073 * Should the parser cache be used?
1074 *
1075 * @param ParserOptions $parserOptions ParserOptions to check
1076 * @param int $oldId
1077 * @return bool
1078 */
1079 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1080 return $parserOptions->getStubThreshold() == 0
1081 && $this->exists()
1082 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1083 && $this->getContentHandler()->isParserCacheSupported();
1084 }
1085
1086 /**
1087 * Get a ParserOutput for the given ParserOptions and revision ID.
1088 *
1089 * The parser cache will be used if possible. Cache misses that result
1090 * in parser runs are debounced with PoolCounter.
1091 *
1092 * @since 1.19
1093 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1094 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1095 * get the current revision (default value)
1096 * @param bool $forceParse Force reindexing, regardless of cache settings
1097 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1098 */
1099 public function getParserOutput(
1100 ParserOptions $parserOptions, $oldid = null, $forceParse = false
1101 ) {
1102 $useParserCache =
1103 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1104
1105 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1106 throw new InvalidArgumentException(
1107 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1108 );
1109 }
1110
1111 wfDebug( __METHOD__ .
1112 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1113 if ( $parserOptions->getStubThreshold() ) {
1114 wfIncrStats( 'pcache.miss.stub' );
1115 }
1116
1117 if ( $useParserCache ) {
1118 $parserOutput = MediaWikiServices::getInstance()->getParserCache()
1119 ->get( $this, $parserOptions );
1120 if ( $parserOutput !== false ) {
1121 return $parserOutput;
1122 }
1123 }
1124
1125 if ( $oldid === null || $oldid === 0 ) {
1126 $oldid = $this->getLatest();
1127 }
1128
1129 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1130 $pool->execute();
1131
1132 return $pool->getParserOutput();
1133 }
1134
1135 /**
1136 * Do standard deferred updates after page view (existing or missing page)
1137 * @param User $user The relevant user
1138 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1139 */
1140 public function doViewUpdates( User $user, $oldid = 0 ) {
1141 if ( wfReadOnly() ) {
1142 return;
1143 }
1144
1145 Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1146 // Update newtalk / watchlist notification status
1147 try {
1148 $user->clearNotification( $this->mTitle, $oldid );
1149 } catch ( DBError $e ) {
1150 // Avoid outage if the master is not reachable
1151 MWExceptionHandler::logException( $e );
1152 }
1153 }
1154
1155 /**
1156 * Perform the actions of a page purging
1157 * @return bool
1158 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1159 * controlled how much purging was done.
1160 */
1161 public function doPurge() {
1162 // Avoid PHP 7.1 warning of passing $this by reference
1163 $wikiPage = $this;
1164
1165 if ( !Hooks::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1166 return false;
1167 }
1168
1169 $this->mTitle->invalidateCache();
1170
1171 // Clear file cache
1172 HTMLFileCache::clearFileCache( $this->getTitle() );
1173 // Send purge after above page_touched update was committed
1174 DeferredUpdates::addUpdate(
1175 new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1176 DeferredUpdates::PRESEND
1177 );
1178
1179 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1180 $messageCache = MessageCache::singleton();
1181 $messageCache->updateMessageOverride( $this->mTitle, $this->getContent() );
1182 }
1183
1184 return true;
1185 }
1186
1187 /**
1188 * Insert a new empty page record for this article.
1189 * This *must* be followed up by creating a revision
1190 * and running $this->updateRevisionOn( ... );
1191 * or else the record will be left in a funky state.
1192 * Best if all done inside a transaction.
1193 *
1194 * @param IDatabase $dbw
1195 * @param int|null $pageId Custom page ID that will be used for the insert statement
1196 *
1197 * @return bool|int The newly created page_id key; false if the row was not
1198 * inserted, e.g. because the title already existed or because the specified
1199 * page ID is already in use.
1200 */
1201 public function insertOn( $dbw, $pageId = null ) {
1202 $pageIdForInsert = $pageId ? [ 'page_id' => $pageId ] : [];
1203 $dbw->insert(
1204 'page',
1205 [
1206 'page_namespace' => $this->mTitle->getNamespace(),
1207 'page_title' => $this->mTitle->getDBkey(),
1208 'page_restrictions' => '',
1209 'page_is_redirect' => 0, // Will set this shortly...
1210 'page_is_new' => 1,
1211 'page_random' => wfRandom(),
1212 'page_touched' => $dbw->timestamp(),
1213 'page_latest' => 0, // Fill this in shortly...
1214 'page_len' => 0, // Fill this in shortly...
1215 ] + $pageIdForInsert,
1216 __METHOD__,
1217 'IGNORE'
1218 );
1219
1220 if ( $dbw->affectedRows() > 0 ) {
1221 $newid = $pageId ? (int)$pageId : $dbw->insertId();
1222 $this->mId = $newid;
1223 $this->mTitle->resetArticleID( $newid );
1224
1225 return $newid;
1226 } else {
1227 return false; // nothing changed
1228 }
1229 }
1230
1231 /**
1232 * Update the page record to point to a newly saved revision.
1233 *
1234 * @param IDatabase $dbw
1235 * @param Revision $revision For ID number, and text used to set
1236 * length and redirect status fields
1237 * @param int $lastRevision If given, will not overwrite the page field
1238 * when different from the currently set value.
1239 * Giving 0 indicates the new page flag should be set on.
1240 * @param bool $lastRevIsRedirect If given, will optimize adding and
1241 * removing rows in redirect table.
1242 * @return bool Success; false if the page row was missing or page_latest changed
1243 */
1244 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1245 $lastRevIsRedirect = null
1246 ) {
1247 global $wgContentHandlerUseDB;
1248
1249 // Assertion to try to catch T92046
1250 if ( (int)$revision->getId() === 0 ) {
1251 throw new InvalidArgumentException(
1252 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1253 );
1254 }
1255
1256 $content = $revision->getContent();
1257 $len = $content ? $content->getSize() : 0;
1258 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1259
1260 $conditions = [ 'page_id' => $this->getId() ];
1261
1262 if ( !is_null( $lastRevision ) ) {
1263 // An extra check against threads stepping on each other
1264 $conditions['page_latest'] = $lastRevision;
1265 }
1266
1267 $row = [ /* SET */
1268 'page_latest' => $revision->getId(),
1269 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1270 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1271 'page_is_redirect' => $rt !== null ? 1 : 0,
1272 'page_len' => $len,
1273 ];
1274
1275 if ( $wgContentHandlerUseDB ) {
1276 $row['page_content_model'] = $revision->getContentModel();
1277 }
1278
1279 $dbw->update( 'page',
1280 $row,
1281 $conditions,
1282 __METHOD__ );
1283
1284 $result = $dbw->affectedRows() > 0;
1285 if ( $result ) {
1286 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1287 $this->setLastEdit( $revision );
1288 $this->mLatest = $revision->getId();
1289 $this->mIsRedirect = (bool)$rt;
1290 // Update the LinkCache.
1291 LinkCache::singleton()->addGoodLinkObj(
1292 $this->getId(),
1293 $this->mTitle,
1294 $len,
1295 $this->mIsRedirect,
1296 $this->mLatest,
1297 $revision->getContentModel()
1298 );
1299 }
1300
1301 return $result;
1302 }
1303
1304 /**
1305 * Add row to the redirect table if this is a redirect, remove otherwise.
1306 *
1307 * @param IDatabase $dbw
1308 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1309 * or NULL if this is not a redirect
1310 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1311 * removing rows in redirect table.
1312 * @return bool True on success, false on failure
1313 * @private
1314 */
1315 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1316 // Always update redirects (target link might have changed)
1317 // Update/Insert if we don't know if the last revision was a redirect or not
1318 // Delete if changing from redirect to non-redirect
1319 $isRedirect = !is_null( $redirectTitle );
1320
1321 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1322 return true;
1323 }
1324
1325 if ( $isRedirect ) {
1326 $this->insertRedirectEntry( $redirectTitle );
1327 } else {
1328 // This is not a redirect, remove row from redirect table
1329 $where = [ 'rd_from' => $this->getId() ];
1330 $dbw->delete( 'redirect', $where, __METHOD__ );
1331 }
1332
1333 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1334 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1335 }
1336
1337 return ( $dbw->affectedRows() != 0 );
1338 }
1339
1340 /**
1341 * If the given revision is newer than the currently set page_latest,
1342 * update the page record. Otherwise, do nothing.
1343 *
1344 * @deprecated since 1.24, use updateRevisionOn instead
1345 *
1346 * @param IDatabase $dbw
1347 * @param Revision $revision
1348 * @return bool
1349 */
1350 public function updateIfNewerOn( $dbw, $revision ) {
1351 $row = $dbw->selectRow(
1352 [ 'revision', 'page' ],
1353 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1354 [
1355 'page_id' => $this->getId(),
1356 'page_latest=rev_id' ],
1357 __METHOD__ );
1358
1359 if ( $row ) {
1360 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1361 return false;
1362 }
1363 $prev = $row->rev_id;
1364 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1365 } else {
1366 // No or missing previous revision; mark the page as new
1367 $prev = 0;
1368 $lastRevIsRedirect = null;
1369 }
1370
1371 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1372
1373 return $ret;
1374 }
1375
1376 /**
1377 * Get the content that needs to be saved in order to undo all revisions
1378 * between $undo and $undoafter. Revisions must belong to the same page,
1379 * must exist and must not be deleted
1380 * @param Revision $undo
1381 * @param Revision $undoafter Must be an earlier revision than $undo
1382 * @return Content|bool Content on success, false on failure
1383 * @since 1.21
1384 * Before we had the Content object, this was done in getUndoText
1385 */
1386 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1387 $handler = $undo->getContentHandler();
1388 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1389 }
1390
1391 /**
1392 * Returns true if this page's content model supports sections.
1393 *
1394 * @return bool
1395 *
1396 * @todo The skin should check this and not offer section functionality if
1397 * sections are not supported.
1398 * @todo The EditPage should check this and not offer section functionality
1399 * if sections are not supported.
1400 */
1401 public function supportsSections() {
1402 return $this->getContentHandler()->supportsSections();
1403 }
1404
1405 /**
1406 * @param string|int|null|bool $sectionId Section identifier as a number or string
1407 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1408 * or 'new' for a new section.
1409 * @param Content $sectionContent New content of the section.
1410 * @param string $sectionTitle New section's subject, only if $section is "new".
1411 * @param string $edittime Revision timestamp or null to use the current revision.
1412 *
1413 * @throws MWException
1414 * @return Content|null New complete article content, or null if error.
1415 *
1416 * @since 1.21
1417 * @deprecated since 1.24, use replaceSectionAtRev instead
1418 */
1419 public function replaceSectionContent(
1420 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1421 ) {
1422 $baseRevId = null;
1423 if ( $edittime && $sectionId !== 'new' ) {
1424 $dbr = wfGetDB( DB_REPLICA );
1425 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1426 // Try the master if this thread may have just added it.
1427 // This could be abstracted into a Revision method, but we don't want
1428 // to encourage loading of revisions by timestamp.
1429 if ( !$rev
1430 && wfGetLB()->getServerCount() > 1
1431 && wfGetLB()->hasOrMadeRecentMasterChanges()
1432 ) {
1433 $dbw = wfGetDB( DB_MASTER );
1434 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1435 }
1436 if ( $rev ) {
1437 $baseRevId = $rev->getId();
1438 }
1439 }
1440
1441 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1442 }
1443
1444 /**
1445 * @param string|int|null|bool $sectionId Section identifier as a number or string
1446 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1447 * or 'new' for a new section.
1448 * @param Content $sectionContent New content of the section.
1449 * @param string $sectionTitle New section's subject, only if $section is "new".
1450 * @param int|null $baseRevId
1451 *
1452 * @throws MWException
1453 * @return Content|null New complete article content, or null if error.
1454 *
1455 * @since 1.24
1456 */
1457 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1458 $sectionTitle = '', $baseRevId = null
1459 ) {
1460 if ( strval( $sectionId ) === '' ) {
1461 // Whole-page edit; let the whole text through
1462 $newContent = $sectionContent;
1463 } else {
1464 if ( !$this->supportsSections() ) {
1465 throw new MWException( "sections not supported for content model " .
1466 $this->getContentHandler()->getModelID() );
1467 }
1468
1469 // T32711: always use current version when adding a new section
1470 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1471 $oldContent = $this->getContent();
1472 } else {
1473 $rev = Revision::newFromId( $baseRevId );
1474 if ( !$rev ) {
1475 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1476 $this->getId() . "; section: $sectionId)\n" );
1477 return null;
1478 }
1479
1480 $oldContent = $rev->getContent();
1481 }
1482
1483 if ( !$oldContent ) {
1484 wfDebug( __METHOD__ . ": no page text\n" );
1485 return null;
1486 }
1487
1488 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1489 }
1490
1491 return $newContent;
1492 }
1493
1494 /**
1495 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1496 * @param int $flags
1497 * @return int Updated $flags
1498 */
1499 public function checkFlags( $flags ) {
1500 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1501 if ( $this->exists() ) {
1502 $flags |= EDIT_UPDATE;
1503 } else {
1504 $flags |= EDIT_NEW;
1505 }
1506 }
1507
1508 return $flags;
1509 }
1510
1511 /**
1512 * Change an existing article or create a new article. Updates RC and all necessary caches,
1513 * optionally via the deferred update array.
1514 *
1515 * @param Content $content New content
1516 * @param string $summary Edit summary
1517 * @param int $flags Bitfield:
1518 * EDIT_NEW
1519 * Article is known or assumed to be non-existent, create a new one
1520 * EDIT_UPDATE
1521 * Article is known or assumed to be pre-existing, update it
1522 * EDIT_MINOR
1523 * Mark this edit minor, if the user is allowed to do so
1524 * EDIT_SUPPRESS_RC
1525 * Do not log the change in recentchanges
1526 * EDIT_FORCE_BOT
1527 * Mark the edit a "bot" edit regardless of user rights
1528 * EDIT_AUTOSUMMARY
1529 * Fill in blank summaries with generated text where possible
1530 * EDIT_INTERNAL
1531 * Signal that the page retrieve/save cycle happened entirely in this request.
1532 *
1533 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1534 * article will be detected. If EDIT_UPDATE is specified and the article
1535 * doesn't exist, the function will return an edit-gone-missing error. If
1536 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1537 * error will be returned. These two conditions are also possible with
1538 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1539 *
1540 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1541 * This is not the parent revision ID, rather the revision ID for older
1542 * content used as the source for a rollback, for example.
1543 * @param User $user The user doing the edit
1544 * @param string $serialFormat Format for storing the content in the
1545 * database.
1546 * @param array|null $tags Change tags to apply to this edit
1547 * Callers are responsible for permission checks
1548 * (with ChangeTags::canAddTagsAccompanyingChange)
1549 * @param Int $undidRevId Id of revision that was undone or 0
1550 *
1551 * @throws MWException
1552 * @return Status Possible errors:
1553 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1554 * set the fatal flag of $status.
1555 * edit-gone-missing: In update mode, but the article didn't exist.
1556 * edit-conflict: In update mode, the article changed unexpectedly.
1557 * edit-no-change: Warning that the text was the same as before.
1558 * edit-already-exists: In creation mode, but the article already exists.
1559 *
1560 * Extensions may define additional errors.
1561 *
1562 * $return->value will contain an associative array with members as follows:
1563 * new: Boolean indicating if the function attempted to create a new article.
1564 * revision: The revision object for the inserted revision, or null.
1565 *
1566 * @since 1.21
1567 * @throws MWException
1568 */
1569 public function doEditContent(
1570 Content $content, $summary, $flags = 0, $baseRevId = false,
1571 User $user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1572 ) {
1573 global $wgUser, $wgUseAutomaticEditSummaries;
1574
1575 // Old default parameter for $tags was null
1576 if ( $tags === null ) {
1577 $tags = [];
1578 }
1579
1580 // Low-level sanity check
1581 if ( $this->mTitle->getText() === '' ) {
1582 throw new MWException( 'Something is trying to edit an article with an empty title' );
1583 }
1584 // Make sure the given content type is allowed for this page
1585 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1586 return Status::newFatal( 'content-not-allowed-here',
1587 ContentHandler::getLocalizedName( $content->getModel() ),
1588 $this->mTitle->getPrefixedText()
1589 );
1590 }
1591
1592 // Load the data from the master database if needed.
1593 // The caller may already loaded it from the master or even loaded it using
1594 // SELECT FOR UPDATE, so do not override that using clear().
1595 $this->loadPageData( 'fromdbmaster' );
1596
1597 $user = $user ?: $wgUser;
1598 $flags = $this->checkFlags( $flags );
1599
1600 // Avoid PHP 7.1 warning of passing $this by reference
1601 $wikiPage = $this;
1602
1603 // Trigger pre-save hook (using provided edit summary)
1604 $hookStatus = Status::newGood( [] );
1605 $hook_args = [ &$wikiPage, &$user, &$content, &$summary,
1606 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1607 // Check if the hook rejected the attempted save
1608 if ( !Hooks::run( 'PageContentSave', $hook_args ) ) {
1609 if ( $hookStatus->isOK() ) {
1610 // Hook returned false but didn't call fatal(); use generic message
1611 $hookStatus->fatal( 'edit-hook-aborted' );
1612 }
1613
1614 return $hookStatus;
1615 }
1616
1617 $old_revision = $this->getRevision(); // current revision
1618 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1619
1620 $handler = $content->getContentHandler();
1621 $tag = $handler->getChangeTag( $old_content, $content, $flags );
1622 // If there is no applicable tag, null is returned, so we need to check
1623 if ( $tag ) {
1624 $tags[] = $tag;
1625 }
1626
1627 // Check for undo tag
1628 if ( $undidRevId !== 0 && in_array( 'mw-undo', ChangeTags::getSoftwareTags() ) ) {
1629 $tags[] = 'mw-undo';
1630 }
1631
1632 // Provide autosummaries if summary is not provided and autosummaries are enabled
1633 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1634 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1635 }
1636
1637 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1638 if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1639 $useCache = false;
1640 } else {
1641 $useCache = true;
1642 }
1643
1644 // Get the pre-save transform content and final parser output
1645 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1646 $pstContent = $editInfo->pstContent; // Content object
1647 $meta = [
1648 'bot' => ( $flags & EDIT_FORCE_BOT ),
1649 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1650 'serialized' => $pstContent->serialize( $serialFormat ),
1651 'serialFormat' => $serialFormat,
1652 'baseRevId' => $baseRevId,
1653 'oldRevision' => $old_revision,
1654 'oldContent' => $old_content,
1655 'oldId' => $this->getLatest(),
1656 'oldIsRedirect' => $this->isRedirect(),
1657 'oldCountable' => $this->isCountable(),
1658 'tags' => ( $tags !== null ) ? (array)$tags : [],
1659 'undidRevId' => $undidRevId
1660 ];
1661
1662 // Actually create the revision and create/update the page
1663 if ( $flags & EDIT_UPDATE ) {
1664 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1665 } else {
1666 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1667 }
1668
1669 // Promote user to any groups they meet the criteria for
1670 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1671 $user->addAutopromoteOnceGroups( 'onEdit' );
1672 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1673 } );
1674
1675 return $status;
1676 }
1677
1678 /**
1679 * @param Content $content Pre-save transform content
1680 * @param int $flags
1681 * @param User $user
1682 * @param string $summary
1683 * @param array $meta
1684 * @return Status
1685 * @throws DBUnexpectedError
1686 * @throws Exception
1687 * @throws FatalError
1688 * @throws MWException
1689 */
1690 private function doModify(
1691 Content $content, $flags, User $user, $summary, array $meta
1692 ) {
1693 global $wgUseRCPatrol;
1694
1695 // Update article, but only if changed.
1696 $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1697
1698 // Convenience variables
1699 $now = wfTimestampNow();
1700 $oldid = $meta['oldId'];
1701 /** @var Content|null $oldContent */
1702 $oldContent = $meta['oldContent'];
1703 $newsize = $content->getSize();
1704
1705 if ( !$oldid ) {
1706 // Article gone missing
1707 $status->fatal( 'edit-gone-missing' );
1708
1709 return $status;
1710 } elseif ( !$oldContent ) {
1711 // Sanity check for T39225
1712 throw new MWException( "Could not find text for current revision {$oldid}." );
1713 }
1714
1715 $changed = !$content->equals( $oldContent );
1716
1717 $dbw = wfGetDB( DB_MASTER );
1718
1719 if ( $changed ) {
1720 // @TODO: pass content object?!
1721 $revision = new Revision( [
1722 'page' => $this->getId(),
1723 'title' => $this->mTitle, // for determining the default content model
1724 'comment' => $summary,
1725 'minor_edit' => $meta['minor'],
1726 'text' => $meta['serialized'],
1727 'len' => $newsize,
1728 'parent_id' => $oldid,
1729 'user' => $user->getId(),
1730 'user_text' => $user->getName(),
1731 'timestamp' => $now,
1732 'content_model' => $content->getModel(),
1733 'content_format' => $meta['serialFormat'],
1734 ] );
1735
1736 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1737 $status->merge( $prepStatus );
1738 if ( !$status->isOK() ) {
1739 return $status;
1740 }
1741
1742 $dbw->startAtomic( __METHOD__ );
1743 // Get the latest page_latest value while locking it.
1744 // Do a CAS style check to see if it's the same as when this method
1745 // started. If it changed then bail out before touching the DB.
1746 $latestNow = $this->lockAndGetLatest();
1747 if ( $latestNow != $oldid ) {
1748 $dbw->endAtomic( __METHOD__ );
1749 // Page updated or deleted in the mean time
1750 $status->fatal( 'edit-conflict' );
1751
1752 return $status;
1753 }
1754
1755 // At this point we are now comitted to returning an OK
1756 // status unless some DB query error or other exception comes up.
1757 // This way callers don't have to call rollback() if $status is bad
1758 // unless they actually try to catch exceptions (which is rare).
1759
1760 // Save the revision text
1761 $revisionId = $revision->insertOn( $dbw );
1762 // Update page_latest and friends to reflect the new revision
1763 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1764 throw new MWException( "Failed to update page row to use new revision." );
1765 }
1766
1767 Hooks::run( 'NewRevisionFromEditComplete',
1768 [ $this, $revision, $meta['baseRevId'], $user ] );
1769
1770 // Update recentchanges
1771 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1772 // Mark as patrolled if the user can do so
1773 $patrolled = $wgUseRCPatrol && !count(
1774 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1775 // Add RC row to the DB
1776 RecentChange::notifyEdit(
1777 $now,
1778 $this->mTitle,
1779 $revision->isMinor(),
1780 $user,
1781 $summary,
1782 $oldid,
1783 $this->getTimestamp(),
1784 $meta['bot'],
1785 '',
1786 $oldContent ? $oldContent->getSize() : 0,
1787 $newsize,
1788 $revisionId,
1789 $patrolled,
1790 $meta['tags']
1791 );
1792 }
1793
1794 $user->incEditCount();
1795
1796 $dbw->endAtomic( __METHOD__ );
1797 $this->mTimestamp = $now;
1798 } else {
1799 // T34948: revision ID must be set to page {{REVISIONID}} and
1800 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1801 // Since we don't insert a new revision into the database, the least
1802 // error-prone way is to reuse given old revision.
1803 $revision = $meta['oldRevision'];
1804 }
1805
1806 if ( $changed ) {
1807 // Return the new revision to the caller
1808 $status->value['revision'] = $revision;
1809 } else {
1810 $status->warning( 'edit-no-change' );
1811 // Update page_touched as updateRevisionOn() was not called.
1812 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1813 $this->mTitle->invalidateCache( $now );
1814 }
1815
1816 // Do secondary updates once the main changes have been committed...
1817 DeferredUpdates::addUpdate(
1818 new AtomicSectionUpdate(
1819 $dbw,
1820 __METHOD__,
1821 function () use (
1822 $revision, &$user, $content, $summary, &$flags,
1823 $changed, $meta, &$status
1824 ) {
1825 // Update links tables, site stats, etc.
1826 $this->doEditUpdates(
1827 $revision,
1828 $user,
1829 [
1830 'changed' => $changed,
1831 'oldcountable' => $meta['oldCountable'],
1832 'oldrevision' => $meta['oldRevision']
1833 ]
1834 );
1835 // Avoid PHP 7.1 warning of passing $this by reference
1836 $wikiPage = $this;
1837 // Trigger post-save hook
1838 $params = [ &$wikiPage, &$user, $content, $summary, $flags & EDIT_MINOR,
1839 null, null, &$flags, $revision, &$status, $meta['baseRevId'],
1840 $meta['undidRevId'] ];
1841 Hooks::run( 'PageContentSaveComplete', $params );
1842 }
1843 ),
1844 DeferredUpdates::PRESEND
1845 );
1846
1847 return $status;
1848 }
1849
1850 /**
1851 * @param Content $content Pre-save transform content
1852 * @param int $flags
1853 * @param User $user
1854 * @param string $summary
1855 * @param array $meta
1856 * @return Status
1857 * @throws DBUnexpectedError
1858 * @throws Exception
1859 * @throws FatalError
1860 * @throws MWException
1861 */
1862 private function doCreate(
1863 Content $content, $flags, User $user, $summary, array $meta
1864 ) {
1865 global $wgUseRCPatrol, $wgUseNPPatrol;
1866
1867 $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1868
1869 $now = wfTimestampNow();
1870 $newsize = $content->getSize();
1871 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1872 $status->merge( $prepStatus );
1873 if ( !$status->isOK() ) {
1874 return $status;
1875 }
1876
1877 $dbw = wfGetDB( DB_MASTER );
1878 $dbw->startAtomic( __METHOD__ );
1879
1880 // Add the page record unless one already exists for the title
1881 $newid = $this->insertOn( $dbw );
1882 if ( $newid === false ) {
1883 $dbw->endAtomic( __METHOD__ ); // nothing inserted
1884 $status->fatal( 'edit-already-exists' );
1885
1886 return $status; // nothing done
1887 }
1888
1889 // At this point we are now comitted to returning an OK
1890 // status unless some DB query error or other exception comes up.
1891 // This way callers don't have to call rollback() if $status is bad
1892 // unless they actually try to catch exceptions (which is rare).
1893
1894 // @TODO: pass content object?!
1895 $revision = new Revision( [
1896 'page' => $newid,
1897 'title' => $this->mTitle, // for determining the default content model
1898 'comment' => $summary,
1899 'minor_edit' => $meta['minor'],
1900 'text' => $meta['serialized'],
1901 'len' => $newsize,
1902 'user' => $user->getId(),
1903 'user_text' => $user->getName(),
1904 'timestamp' => $now,
1905 'content_model' => $content->getModel(),
1906 'content_format' => $meta['serialFormat'],
1907 ] );
1908
1909 // Save the revision text...
1910 $revisionId = $revision->insertOn( $dbw );
1911 // Update the page record with revision data
1912 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1913 throw new MWException( "Failed to update page row to use new revision." );
1914 }
1915
1916 Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1917
1918 // Update recentchanges
1919 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1920 // Mark as patrolled if the user can do so
1921 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1922 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1923 // Add RC row to the DB
1924 RecentChange::notifyNew(
1925 $now,
1926 $this->mTitle,
1927 $revision->isMinor(),
1928 $user,
1929 $summary,
1930 $meta['bot'],
1931 '',
1932 $newsize,
1933 $revisionId,
1934 $patrolled,
1935 $meta['tags']
1936 );
1937 }
1938
1939 $user->incEditCount();
1940
1941 $dbw->endAtomic( __METHOD__ );
1942 $this->mTimestamp = $now;
1943
1944 // Return the new revision to the caller
1945 $status->value['revision'] = $revision;
1946
1947 // Do secondary updates once the main changes have been committed...
1948 DeferredUpdates::addUpdate(
1949 new AtomicSectionUpdate(
1950 $dbw,
1951 __METHOD__,
1952 function () use (
1953 $revision, &$user, $content, $summary, &$flags, $meta, &$status
1954 ) {
1955 // Update links, etc.
1956 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1957 // Avoid PHP 7.1 warning of passing $this by reference
1958 $wikiPage = $this;
1959 // Trigger post-create hook
1960 $params = [ &$wikiPage, &$user, $content, $summary,
1961 $flags & EDIT_MINOR, null, null, &$flags, $revision ];
1962 Hooks::run( 'PageContentInsertComplete', $params );
1963 // Trigger post-save hook
1964 $params = array_merge( $params, [ &$status, $meta['baseRevId'], 0 ] );
1965 Hooks::run( 'PageContentSaveComplete', $params );
1966 }
1967 ),
1968 DeferredUpdates::PRESEND
1969 );
1970
1971 return $status;
1972 }
1973
1974 /**
1975 * Get parser options suitable for rendering the primary article wikitext
1976 *
1977 * @see ContentHandler::makeParserOptions
1978 *
1979 * @param IContextSource|User|string $context One of the following:
1980 * - IContextSource: Use the User and the Language of the provided
1981 * context
1982 * - User: Use the provided User object and $wgLang for the language,
1983 * so use an IContextSource object if possible.
1984 * - 'canonical': Canonical options (anonymous user with default
1985 * preferences and content language).
1986 * @return ParserOptions
1987 */
1988 public function makeParserOptions( $context ) {
1989 $options = $this->getContentHandler()->makeParserOptions( $context );
1990
1991 if ( $this->getTitle()->isConversionTable() ) {
1992 // @todo ConversionTable should become a separate content model, so
1993 // we don't need special cases like this one.
1994 $options->disableContentConversion();
1995 }
1996
1997 return $options;
1998 }
1999
2000 /**
2001 * Prepare content which is about to be saved.
2002 *
2003 * Prior to 1.30, this returned a stdClass object with the same class
2004 * members.
2005 *
2006 * @param Content $content
2007 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2008 * revision ID is also accepted, but this is deprecated.
2009 * @param User|null $user
2010 * @param string|null $serialFormat
2011 * @param bool $useCache Check shared prepared edit cache
2012 *
2013 * @return PreparedEdit
2014 *
2015 * @since 1.21
2016 */
2017 public function prepareContentForEdit(
2018 Content $content, $revision = null, User $user = null,
2019 $serialFormat = null, $useCache = true
2020 ) {
2021 global $wgContLang, $wgUser, $wgAjaxEditStash;
2022
2023 if ( is_object( $revision ) ) {
2024 $revid = $revision->getId();
2025 } else {
2026 $revid = $revision;
2027 // This code path is deprecated, and nothing is known to
2028 // use it, so performance here shouldn't be a worry.
2029 if ( $revid !== null ) {
2030 wfDeprecated( __METHOD__ . ' with $revision = revision ID', '1.25' );
2031 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2032 } else {
2033 $revision = null;
2034 }
2035 }
2036
2037 $user = is_null( $user ) ? $wgUser : $user;
2038 // XXX: check $user->getId() here???
2039
2040 // Use a sane default for $serialFormat, see T59026
2041 if ( $serialFormat === null ) {
2042 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2043 }
2044
2045 if ( $this->mPreparedEdit
2046 && isset( $this->mPreparedEdit->newContent )
2047 && $this->mPreparedEdit->newContent->equals( $content )
2048 && $this->mPreparedEdit->revid == $revid
2049 && $this->mPreparedEdit->format == $serialFormat
2050 // XXX: also check $user here?
2051 ) {
2052 // Already prepared
2053 return $this->mPreparedEdit;
2054 }
2055
2056 // The edit may have already been prepared via api.php?action=stashedit
2057 $cachedEdit = $useCache && $wgAjaxEditStash
2058 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2059 : false;
2060
2061 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2062 Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2063
2064 $edit = new PreparedEdit();
2065 if ( $cachedEdit ) {
2066 $edit->timestamp = $cachedEdit->timestamp;
2067 } else {
2068 $edit->timestamp = wfTimestampNow();
2069 }
2070 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2071 $edit->revid = $revid;
2072
2073 if ( $cachedEdit ) {
2074 $edit->pstContent = $cachedEdit->pstContent;
2075 } else {
2076 $edit->pstContent = $content
2077 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2078 : null;
2079 }
2080
2081 $edit->format = $serialFormat;
2082 $edit->popts = $this->makeParserOptions( 'canonical' );
2083 if ( $cachedEdit ) {
2084 $edit->output = $cachedEdit->output;
2085 } else {
2086 if ( $revision ) {
2087 // We get here if vary-revision is set. This means that this page references
2088 // itself (such as via self-transclusion). In this case, we need to make sure
2089 // that any such self-references refer to the newly-saved revision, and not
2090 // to the previous one, which could otherwise happen due to replica DB lag.
2091 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2092 $edit->popts->setCurrentRevisionCallback(
2093 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2094 if ( $title->equals( $revision->getTitle() ) ) {
2095 return $revision;
2096 } else {
2097 return call_user_func( $oldCallback, $title, $parser );
2098 }
2099 }
2100 );
2101 } else {
2102 // Try to avoid a second parse if {{REVISIONID}} is used
2103 $dbIndex = ( $this->mDataLoadedFrom & self::READ_LATEST ) === self::READ_LATEST
2104 ? DB_MASTER // use the best possible guess
2105 : DB_REPLICA; // T154554
2106
2107 $edit->popts->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
2108 return 1 + (int)wfGetDB( $dbIndex )->selectField(
2109 'revision',
2110 'MAX(rev_id)',
2111 [],
2112 __METHOD__
2113 );
2114 } );
2115 }
2116 $edit->output = $edit->pstContent
2117 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2118 : null;
2119 }
2120
2121 $edit->newContent = $content;
2122 $edit->oldContent = $this->getContent( Revision::RAW );
2123
2124 // NOTE: B/C for hooks! don't use these fields!
2125 $edit->newText = $edit->newContent
2126 ? ContentHandler::getContentText( $edit->newContent )
2127 : '';
2128 $edit->oldText = $edit->oldContent
2129 ? ContentHandler::getContentText( $edit->oldContent )
2130 : '';
2131 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2132
2133 if ( $edit->output ) {
2134 $edit->output->setCacheTime( wfTimestampNow() );
2135 }
2136
2137 // Process cache the result
2138 $this->mPreparedEdit = $edit;
2139
2140 return $edit;
2141 }
2142
2143 /**
2144 * Do standard deferred updates after page edit.
2145 * Update links tables, site stats, search index and message cache.
2146 * Purges pages that include this page if the text was changed here.
2147 * Every 100th edit, prune the recent changes table.
2148 *
2149 * @param Revision $revision
2150 * @param User $user User object that did the revision
2151 * @param array $options Array of options, following indexes are used:
2152 * - changed: bool, whether the revision changed the content (default true)
2153 * - created: bool, whether the revision created the page (default false)
2154 * - moved: bool, whether the page was moved (default false)
2155 * - restored: bool, whether the page was undeleted (default false)
2156 * - oldrevision: Revision object for the pre-update revision (default null)
2157 * - oldcountable: bool, null, or string 'no-change' (default null):
2158 * - bool: whether the page was counted as an article before that
2159 * revision, only used in changed is true and created is false
2160 * - null: if created is false, don't update the article count; if created
2161 * is true, do update the article count
2162 * - 'no-change': don't update the article count, ever
2163 */
2164 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2165 global $wgRCWatchCategoryMembership;
2166
2167 $options += [
2168 'changed' => true,
2169 'created' => false,
2170 'moved' => false,
2171 'restored' => false,
2172 'oldrevision' => null,
2173 'oldcountable' => null
2174 ];
2175 $content = $revision->getContent();
2176
2177 $logger = LoggerFactory::getInstance( 'SaveParse' );
2178
2179 // See if the parser output before $revision was inserted is still valid
2180 $editInfo = false;
2181 if ( !$this->mPreparedEdit ) {
2182 $logger->debug( __METHOD__ . ": No prepared edit...\n" );
2183 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2184 $logger->info( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2185 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision-id' )
2186 && $this->mPreparedEdit->output->getSpeculativeRevIdUsed() !== $revision->getId()
2187 ) {
2188 $logger->info( __METHOD__ . ": Prepared edit has vary-revision-id with wrong ID...\n" );
2189 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2190 $logger->info( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2191 } else {
2192 wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2193 $editInfo = $this->mPreparedEdit;
2194 }
2195
2196 if ( !$editInfo ) {
2197 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2198 // $text is usually already pre-save transformed once. Avoid using the edit stash
2199 // as any prepared content from there or in doEditContent() was already rejected.
2200 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2201 }
2202
2203 // Save it to the parser cache.
2204 // Make sure the cache time matches page_touched to avoid double parsing.
2205 MediaWikiServices::getInstance()->getParserCache()->save(
2206 $editInfo->output, $this, $editInfo->popts,
2207 $revision->getTimestamp(), $editInfo->revid
2208 );
2209
2210 // Update the links tables and other secondary data
2211 if ( $content ) {
2212 $recursive = $options['changed']; // T52785
2213 $updates = $content->getSecondaryDataUpdates(
2214 $this->getTitle(), null, $recursive, $editInfo->output
2215 );
2216 foreach ( $updates as $update ) {
2217 $update->setCause( 'edit-page', $user->getName() );
2218 if ( $update instanceof LinksUpdate ) {
2219 $update->setRevision( $revision );
2220 $update->setTriggeringUser( $user );
2221 }
2222 DeferredUpdates::addUpdate( $update );
2223 }
2224 if ( $wgRCWatchCategoryMembership
2225 && $this->getContentHandler()->supportsCategories() === true
2226 && ( $options['changed'] || $options['created'] )
2227 && !$options['restored']
2228 ) {
2229 // Note: jobs are pushed after deferred updates, so the job should be able to see
2230 // the recent change entry (also done via deferred updates) and carry over any
2231 // bot/deletion/IP flags, ect.
2232 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2233 $this->getTitle(),
2234 [
2235 'pageId' => $this->getId(),
2236 'revTimestamp' => $revision->getTimestamp()
2237 ]
2238 ) );
2239 }
2240 }
2241
2242 // Avoid PHP 7.1 warning of passing $this by reference
2243 $wikiPage = $this;
2244
2245 Hooks::run( 'ArticleEditUpdates', [ &$wikiPage, &$editInfo, $options['changed'] ] );
2246
2247 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2248 // Flush old entries from the `recentchanges` table
2249 if ( mt_rand( 0, 9 ) == 0 ) {
2250 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2251 }
2252 }
2253
2254 if ( !$this->exists() ) {
2255 return;
2256 }
2257
2258 $id = $this->getId();
2259 $title = $this->mTitle->getPrefixedDBkey();
2260 $shortTitle = $this->mTitle->getDBkey();
2261
2262 if ( $options['oldcountable'] === 'no-change' ||
2263 ( !$options['changed'] && !$options['moved'] )
2264 ) {
2265 $good = 0;
2266 } elseif ( $options['created'] ) {
2267 $good = (int)$this->isCountable( $editInfo );
2268 } elseif ( $options['oldcountable'] !== null ) {
2269 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2270 } else {
2271 $good = 0;
2272 }
2273 $edits = $options['changed'] ? 1 : 0;
2274 $total = $options['created'] ? 1 : 0;
2275
2276 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2277 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2278
2279 // If this is another user's talk page, update newtalk.
2280 // Don't do this if $options['changed'] = false (null-edits) nor if
2281 // it's a minor edit and the user doesn't want notifications for those.
2282 if ( $options['changed']
2283 && $this->mTitle->getNamespace() == NS_USER_TALK
2284 && $shortTitle != $user->getTitleKey()
2285 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2286 ) {
2287 $recipient = User::newFromName( $shortTitle, false );
2288 if ( !$recipient ) {
2289 wfDebug( __METHOD__ . ": invalid username\n" );
2290 } else {
2291 // Avoid PHP 7.1 warning of passing $this by reference
2292 $wikiPage = $this;
2293
2294 // Allow extensions to prevent user notification
2295 // when a new message is added to their talk page
2296 if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2297 if ( User::isIP( $shortTitle ) ) {
2298 // An anonymous user
2299 $recipient->setNewtalk( true, $revision );
2300 } elseif ( $recipient->isLoggedIn() ) {
2301 $recipient->setNewtalk( true, $revision );
2302 } else {
2303 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2304 }
2305 }
2306 }
2307 }
2308
2309 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2310 MessageCache::singleton()->updateMessageOverride( $this->mTitle, $content );
2311 }
2312
2313 if ( $options['created'] ) {
2314 self::onArticleCreate( $this->mTitle );
2315 } elseif ( $options['changed'] ) { // T52785
2316 self::onArticleEdit( $this->mTitle, $revision );
2317 }
2318
2319 ResourceLoaderWikiModule::invalidateModuleCache(
2320 $this->mTitle, $options['oldrevision'], $revision, wfWikiID()
2321 );
2322 }
2323
2324 /**
2325 * Update the article's restriction field, and leave a log entry.
2326 * This works for protection both existing and non-existing pages.
2327 *
2328 * @param array $limit Set of restriction keys
2329 * @param array $expiry Per restriction type expiration
2330 * @param int &$cascade Set to false if cascading protection isn't allowed.
2331 * @param string $reason
2332 * @param User $user The user updating the restrictions
2333 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2334 * ($user should be able to add the specified tags before this is called)
2335 * @return Status Status object; if action is taken, $status->value is the log_id of the
2336 * protection log entry.
2337 */
2338 public function doUpdateRestrictions( array $limit, array $expiry,
2339 &$cascade, $reason, User $user, $tags = null
2340 ) {
2341 global $wgCascadingRestrictionLevels;
2342
2343 if ( wfReadOnly() ) {
2344 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2345 }
2346
2347 $this->loadPageData( 'fromdbmaster' );
2348 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2349 $id = $this->getId();
2350
2351 if ( !$cascade ) {
2352 $cascade = false;
2353 }
2354
2355 // Take this opportunity to purge out expired restrictions
2356 Title::purgeExpiredRestrictions();
2357
2358 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2359 // we expect a single selection, but the schema allows otherwise.
2360 $isProtected = false;
2361 $protect = false;
2362 $changed = false;
2363
2364 $dbw = wfGetDB( DB_MASTER );
2365
2366 foreach ( $restrictionTypes as $action ) {
2367 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2368 $expiry[$action] = 'infinity';
2369 }
2370 if ( !isset( $limit[$action] ) ) {
2371 $limit[$action] = '';
2372 } elseif ( $limit[$action] != '' ) {
2373 $protect = true;
2374 }
2375
2376 // Get current restrictions on $action
2377 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2378 if ( $current != '' ) {
2379 $isProtected = true;
2380 }
2381
2382 if ( $limit[$action] != $current ) {
2383 $changed = true;
2384 } elseif ( $limit[$action] != '' ) {
2385 // Only check expiry change if the action is actually being
2386 // protected, since expiry does nothing on an not-protected
2387 // action.
2388 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2389 $changed = true;
2390 }
2391 }
2392 }
2393
2394 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2395 $changed = true;
2396 }
2397
2398 // If nothing has changed, do nothing
2399 if ( !$changed ) {
2400 return Status::newGood();
2401 }
2402
2403 if ( !$protect ) { // No protection at all means unprotection
2404 $revCommentMsg = 'unprotectedarticle-comment';
2405 $logAction = 'unprotect';
2406 } elseif ( $isProtected ) {
2407 $revCommentMsg = 'modifiedarticleprotection-comment';
2408 $logAction = 'modify';
2409 } else {
2410 $revCommentMsg = 'protectedarticle-comment';
2411 $logAction = 'protect';
2412 }
2413
2414 $logRelationsValues = [];
2415 $logRelationsField = null;
2416 $logParamsDetails = [];
2417
2418 // Null revision (used for change tag insertion)
2419 $nullRevision = null;
2420
2421 if ( $id ) { // Protection of existing page
2422 // Avoid PHP 7.1 warning of passing $this by reference
2423 $wikiPage = $this;
2424
2425 if ( !Hooks::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2426 return Status::newGood();
2427 }
2428
2429 // Only certain restrictions can cascade...
2430 $editrestriction = isset( $limit['edit'] )
2431 ? [ $limit['edit'] ]
2432 : $this->mTitle->getRestrictions( 'edit' );
2433 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2434 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2435 }
2436 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2437 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2438 }
2439
2440 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2441 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2442 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2443 }
2444 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2445 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2446 }
2447
2448 // The schema allows multiple restrictions
2449 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2450 $cascade = false;
2451 }
2452
2453 // insert null revision to identify the page protection change as edit summary
2454 $latest = $this->getLatest();
2455 $nullRevision = $this->insertProtectNullRevision(
2456 $revCommentMsg,
2457 $limit,
2458 $expiry,
2459 $cascade,
2460 $reason,
2461 $user
2462 );
2463
2464 if ( $nullRevision === null ) {
2465 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2466 }
2467
2468 $logRelationsField = 'pr_id';
2469
2470 // Update restrictions table
2471 foreach ( $limit as $action => $restrictions ) {
2472 $dbw->delete(
2473 'page_restrictions',
2474 [
2475 'pr_page' => $id,
2476 'pr_type' => $action
2477 ],
2478 __METHOD__
2479 );
2480 if ( $restrictions != '' ) {
2481 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2482 $dbw->insert(
2483 'page_restrictions',
2484 [
2485 'pr_page' => $id,
2486 'pr_type' => $action,
2487 'pr_level' => $restrictions,
2488 'pr_cascade' => $cascadeValue,
2489 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2490 ],
2491 __METHOD__
2492 );
2493 $logRelationsValues[] = $dbw->insertId();
2494 $logParamsDetails[] = [
2495 'type' => $action,
2496 'level' => $restrictions,
2497 'expiry' => $expiry[$action],
2498 'cascade' => (bool)$cascadeValue,
2499 ];
2500 }
2501 }
2502
2503 // Clear out legacy restriction fields
2504 $dbw->update(
2505 'page',
2506 [ 'page_restrictions' => '' ],
2507 [ 'page_id' => $id ],
2508 __METHOD__
2509 );
2510
2511 // Avoid PHP 7.1 warning of passing $this by reference
2512 $wikiPage = $this;
2513
2514 Hooks::run( 'NewRevisionFromEditComplete',
2515 [ $this, $nullRevision, $latest, $user ] );
2516 Hooks::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2517 } else { // Protection of non-existing page (also known as "title protection")
2518 // Cascade protection is meaningless in this case
2519 $cascade = false;
2520
2521 if ( $limit['create'] != '' ) {
2522 $commentFields = CommentStore::newKey( 'pt_reason' )->insert( $dbw, $reason );
2523 $dbw->replace( 'protected_titles',
2524 [ [ 'pt_namespace', 'pt_title' ] ],
2525 [
2526 'pt_namespace' => $this->mTitle->getNamespace(),
2527 'pt_title' => $this->mTitle->getDBkey(),
2528 'pt_create_perm' => $limit['create'],
2529 'pt_timestamp' => $dbw->timestamp(),
2530 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2531 'pt_user' => $user->getId(),
2532 ] + $commentFields, __METHOD__
2533 );
2534 $logParamsDetails[] = [
2535 'type' => 'create',
2536 'level' => $limit['create'],
2537 'expiry' => $expiry['create'],
2538 ];
2539 } else {
2540 $dbw->delete( 'protected_titles',
2541 [
2542 'pt_namespace' => $this->mTitle->getNamespace(),
2543 'pt_title' => $this->mTitle->getDBkey()
2544 ], __METHOD__
2545 );
2546 }
2547 }
2548
2549 $this->mTitle->flushRestrictions();
2550 InfoAction::invalidateCache( $this->mTitle );
2551
2552 if ( $logAction == 'unprotect' ) {
2553 $params = [];
2554 } else {
2555 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2556 $params = [
2557 '4::description' => $protectDescriptionLog, // parameter for IRC
2558 '5:bool:cascade' => $cascade,
2559 'details' => $logParamsDetails, // parameter for localize and api
2560 ];
2561 }
2562
2563 // Update the protection log
2564 $logEntry = new ManualLogEntry( 'protect', $logAction );
2565 $logEntry->setTarget( $this->mTitle );
2566 $logEntry->setComment( $reason );
2567 $logEntry->setPerformer( $user );
2568 $logEntry->setParameters( $params );
2569 if ( !is_null( $nullRevision ) ) {
2570 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2571 }
2572 $logEntry->setTags( $tags );
2573 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2574 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2575 }
2576 $logId = $logEntry->insert();
2577 $logEntry->publish( $logId );
2578
2579 return Status::newGood( $logId );
2580 }
2581
2582 /**
2583 * Insert a new null revision for this page.
2584 *
2585 * @param string $revCommentMsg Comment message key for the revision
2586 * @param array $limit Set of restriction keys
2587 * @param array $expiry Per restriction type expiration
2588 * @param int $cascade Set to false if cascading protection isn't allowed.
2589 * @param string $reason
2590 * @param User|null $user
2591 * @return Revision|null Null on error
2592 */
2593 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2594 array $expiry, $cascade, $reason, $user = null
2595 ) {
2596 $dbw = wfGetDB( DB_MASTER );
2597
2598 // Prepare a null revision to be added to the history
2599 $editComment = wfMessage(
2600 $revCommentMsg,
2601 $this->mTitle->getPrefixedText(),
2602 $user ? $user->getName() : ''
2603 )->inContentLanguage()->text();
2604 if ( $reason ) {
2605 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2606 }
2607 $protectDescription = $this->protectDescription( $limit, $expiry );
2608 if ( $protectDescription ) {
2609 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2610 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2611 ->inContentLanguage()->text();
2612 }
2613 if ( $cascade ) {
2614 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2615 $editComment .= wfMessage( 'brackets' )->params(
2616 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2617 )->inContentLanguage()->text();
2618 }
2619
2620 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2621 if ( $nullRev ) {
2622 $nullRev->insertOn( $dbw );
2623
2624 // Update page record and touch page
2625 $oldLatest = $nullRev->getParentId();
2626 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2627 }
2628
2629 return $nullRev;
2630 }
2631
2632 /**
2633 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2634 * @return string
2635 */
2636 protected function formatExpiry( $expiry ) {
2637 global $wgContLang;
2638
2639 if ( $expiry != 'infinity' ) {
2640 return wfMessage(
2641 'protect-expiring',
2642 $wgContLang->timeanddate( $expiry, false, false ),
2643 $wgContLang->date( $expiry, false, false ),
2644 $wgContLang->time( $expiry, false, false )
2645 )->inContentLanguage()->text();
2646 } else {
2647 return wfMessage( 'protect-expiry-indefinite' )
2648 ->inContentLanguage()->text();
2649 }
2650 }
2651
2652 /**
2653 * Builds the description to serve as comment for the edit.
2654 *
2655 * @param array $limit Set of restriction keys
2656 * @param array $expiry Per restriction type expiration
2657 * @return string
2658 */
2659 public function protectDescription( array $limit, array $expiry ) {
2660 $protectDescription = '';
2661
2662 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2663 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2664 # All possible message keys are listed here for easier grepping:
2665 # * restriction-create
2666 # * restriction-edit
2667 # * restriction-move
2668 # * restriction-upload
2669 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2670 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2671 # with '' filtered out. All possible message keys are listed below:
2672 # * protect-level-autoconfirmed
2673 # * protect-level-sysop
2674 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2675 ->inContentLanguage()->text();
2676
2677 $expiryText = $this->formatExpiry( $expiry[$action] );
2678
2679 if ( $protectDescription !== '' ) {
2680 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2681 }
2682 $protectDescription .= wfMessage( 'protect-summary-desc' )
2683 ->params( $actionText, $restrictionsText, $expiryText )
2684 ->inContentLanguage()->text();
2685 }
2686
2687 return $protectDescription;
2688 }
2689
2690 /**
2691 * Builds the description to serve as comment for the log entry.
2692 *
2693 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2694 * protect description text. Keep them in old format to avoid breaking compatibility.
2695 * TODO: Fix protection log to store structured description and format it on-the-fly.
2696 *
2697 * @param array $limit Set of restriction keys
2698 * @param array $expiry Per restriction type expiration
2699 * @return string
2700 */
2701 public function protectDescriptionLog( array $limit, array $expiry ) {
2702 global $wgContLang;
2703
2704 $protectDescriptionLog = '';
2705
2706 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2707 $expiryText = $this->formatExpiry( $expiry[$action] );
2708 $protectDescriptionLog .= $wgContLang->getDirMark() .
2709 "[$action=$restrictions] ($expiryText)";
2710 }
2711
2712 return trim( $protectDescriptionLog );
2713 }
2714
2715 /**
2716 * Take an array of page restrictions and flatten it to a string
2717 * suitable for insertion into the page_restrictions field.
2718 *
2719 * @param string[] $limit
2720 *
2721 * @throws MWException
2722 * @return string
2723 */
2724 protected static function flattenRestrictions( $limit ) {
2725 if ( !is_array( $limit ) ) {
2726 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2727 }
2728
2729 $bits = [];
2730 ksort( $limit );
2731
2732 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2733 $bits[] = "$action=$restrictions";
2734 }
2735
2736 return implode( ':', $bits );
2737 }
2738
2739 /**
2740 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2741 * backwards compatibility, if you care about error reporting you should use
2742 * doDeleteArticleReal() instead.
2743 *
2744 * Deletes the article with database consistency, writes logs, purges caches
2745 *
2746 * @param string $reason Delete reason for deletion log
2747 * @param bool $suppress Suppress all revisions and log the deletion in
2748 * the suppression log instead of the deletion log
2749 * @param int $u1 Unused
2750 * @param bool $u2 Unused
2751 * @param array|string &$error Array of errors to append to
2752 * @param User $user The deleting user
2753 * @return bool True if successful
2754 */
2755 public function doDeleteArticle(
2756 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2757 ) {
2758 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2759 return $status->isGood();
2760 }
2761
2762 /**
2763 * Back-end article deletion
2764 * Deletes the article with database consistency, writes logs, purges caches
2765 *
2766 * @since 1.19
2767 *
2768 * @param string $reason Delete reason for deletion log
2769 * @param bool $suppress Suppress all revisions and log the deletion in
2770 * the suppression log instead of the deletion log
2771 * @param int $u1 Unused
2772 * @param bool $u2 Unused
2773 * @param array|string &$error Array of errors to append to
2774 * @param User $user The deleting user
2775 * @param array $tags Tags to apply to the deletion action
2776 * @param string $logsubtype
2777 * @return Status Status object; if successful, $status->value is the log_id of the
2778 * deletion log entry. If the page couldn't be deleted because it wasn't
2779 * found, $status is a non-fatal 'cannotdelete' error
2780 */
2781 public function doDeleteArticleReal(
2782 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2783 $tags = [], $logsubtype = 'delete'
2784 ) {
2785 global $wgUser, $wgContentHandlerUseDB, $wgCommentTableSchemaMigrationStage;
2786
2787 wfDebug( __METHOD__ . "\n" );
2788
2789 $status = Status::newGood();
2790
2791 if ( $this->mTitle->getDBkey() === '' ) {
2792 $status->error( 'cannotdelete',
2793 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2794 return $status;
2795 }
2796
2797 // Avoid PHP 7.1 warning of passing $this by reference
2798 $wikiPage = $this;
2799
2800 $user = is_null( $user ) ? $wgUser : $user;
2801 if ( !Hooks::run( 'ArticleDelete',
2802 [ &$wikiPage, &$user, &$reason, &$error, &$status, $suppress ]
2803 ) ) {
2804 if ( $status->isOK() ) {
2805 // Hook aborted but didn't set a fatal status
2806 $status->fatal( 'delete-hook-aborted' );
2807 }
2808 return $status;
2809 }
2810
2811 $dbw = wfGetDB( DB_MASTER );
2812 $dbw->startAtomic( __METHOD__ );
2813
2814 $this->loadPageData( self::READ_LATEST );
2815 $id = $this->getId();
2816 // T98706: lock the page from various other updates but avoid using
2817 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2818 // the revisions queries (which also JOIN on user). Only lock the page
2819 // row and CAS check on page_latest to see if the trx snapshot matches.
2820 $lockedLatest = $this->lockAndGetLatest();
2821 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2822 $dbw->endAtomic( __METHOD__ );
2823 // Page not there or trx snapshot is stale
2824 $status->error( 'cannotdelete',
2825 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2826 return $status;
2827 }
2828
2829 // Given the lock above, we can be confident in the title and page ID values
2830 $namespace = $this->getTitle()->getNamespace();
2831 $dbKey = $this->getTitle()->getDBkey();
2832
2833 // At this point we are now comitted to returning an OK
2834 // status unless some DB query error or other exception comes up.
2835 // This way callers don't have to call rollback() if $status is bad
2836 // unless they actually try to catch exceptions (which is rare).
2837
2838 // we need to remember the old content so we can use it to generate all deletion updates.
2839 $revision = $this->getRevision();
2840 try {
2841 $content = $this->getContent( Revision::RAW );
2842 } catch ( Exception $ex ) {
2843 wfLogWarning( __METHOD__ . ': failed to load content during deletion! '
2844 . $ex->getMessage() );
2845
2846 $content = null;
2847 }
2848
2849 $revCommentStore = new CommentStore( 'rev_comment' );
2850 $arCommentStore = new CommentStore( 'ar_comment' );
2851
2852 $revQuery = Revision::getQueryInfo();
2853 $bitfield = false;
2854
2855 // Bitfields to further suppress the content
2856 if ( $suppress ) {
2857 $bitfield = Revision::SUPPRESSED_ALL;
2858 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2859 }
2860
2861 // For now, shunt the revision data into the archive table.
2862 // Text is *not* removed from the text table; bulk storage
2863 // is left intact to avoid breaking block-compression or
2864 // immutable storage schemes.
2865 // In the future, we may keep revisions and mark them with
2866 // the rev_deleted field, which is reserved for this purpose.
2867
2868 // Get all of the page revisions
2869 $res = $dbw->select(
2870 $revQuery['tables'],
2871 $revQuery['fields'],
2872 [ 'rev_page' => $id ],
2873 __METHOD__,
2874 'FOR UPDATE',
2875 $revQuery['joins']
2876 );
2877
2878 // Build their equivalent archive rows
2879 $rowsInsert = [];
2880 $revids = [];
2881
2882 /** @var int[] Revision IDs of edits that were made by IPs */
2883 $ipRevIds = [];
2884
2885 foreach ( $res as $row ) {
2886 $comment = $revCommentStore->getComment( $row );
2887 $rowInsert = [
2888 'ar_namespace' => $namespace,
2889 'ar_title' => $dbKey,
2890 'ar_user' => $row->rev_user,
2891 'ar_user_text' => $row->rev_user_text,
2892 'ar_timestamp' => $row->rev_timestamp,
2893 'ar_minor_edit' => $row->rev_minor_edit,
2894 'ar_rev_id' => $row->rev_id,
2895 'ar_parent_id' => $row->rev_parent_id,
2896 'ar_text_id' => $row->rev_text_id,
2897 'ar_text' => '',
2898 'ar_flags' => '',
2899 'ar_len' => $row->rev_len,
2900 'ar_page_id' => $id,
2901 'ar_deleted' => $suppress ? $bitfield : $row->rev_deleted,
2902 'ar_sha1' => $row->rev_sha1,
2903 ] + $arCommentStore->insert( $dbw, $comment );
2904 if ( $wgContentHandlerUseDB ) {
2905 $rowInsert['ar_content_model'] = $row->rev_content_model;
2906 $rowInsert['ar_content_format'] = $row->rev_content_format;
2907 }
2908 $rowsInsert[] = $rowInsert;
2909 $revids[] = $row->rev_id;
2910
2911 // Keep track of IP edits, so that the corresponding rows can
2912 // be deleted in the ip_changes table.
2913 if ( (int)$row->rev_user === 0 && IP::isValid( $row->rev_user_text ) ) {
2914 $ipRevIds[] = $row->rev_id;
2915 }
2916 }
2917 // Copy them into the archive table
2918 $dbw->insert( 'archive', $rowsInsert, __METHOD__ );
2919 // Save this so we can pass it to the ArticleDeleteComplete hook.
2920 $archivedRevisionCount = $dbw->affectedRows();
2921
2922 // Clone the title and wikiPage, so we have the information we need when
2923 // we log and run the ArticleDeleteComplete hook.
2924 $logTitle = clone $this->mTitle;
2925 $wikiPageBeforeDelete = clone $this;
2926
2927 // Now that it's safely backed up, delete it
2928 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2929 $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2930 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD ) {
2931 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__ );
2932 }
2933
2934 // Also delete records from ip_changes as applicable.
2935 if ( count( $ipRevIds ) > 0 ) {
2936 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__ );
2937 }
2938
2939 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2940 $logtype = $suppress ? 'suppress' : 'delete';
2941
2942 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2943 $logEntry->setPerformer( $user );
2944 $logEntry->setTarget( $logTitle );
2945 $logEntry->setComment( $reason );
2946 $logEntry->setTags( $tags );
2947 $logid = $logEntry->insert();
2948
2949 $dbw->onTransactionPreCommitOrIdle(
2950 function () use ( $dbw, $logEntry, $logid ) {
2951 // T58776: avoid deadlocks (especially from FileDeleteForm)
2952 $logEntry->publish( $logid );
2953 },
2954 __METHOD__
2955 );
2956
2957 $dbw->endAtomic( __METHOD__ );
2958
2959 $this->doDeleteUpdates( $id, $content, $revision, $user );
2960
2961 Hooks::run( 'ArticleDeleteComplete', [
2962 &$wikiPageBeforeDelete,
2963 &$user,
2964 $reason,
2965 $id,
2966 $content,
2967 $logEntry,
2968 $archivedRevisionCount
2969 ] );
2970 $status->value = $logid;
2971
2972 // Show log excerpt on 404 pages rather than just a link
2973 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
2974 $key =