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