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