Avoid usage of deprecated setTags() method, use addTags() instead
[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 * @return bool Success
1067 */
1068 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
1069 $dbw = wfGetDB( DB_MASTER );
1070 $dbw->startAtomic( __METHOD__ );
1071
1072 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
1073 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1074 $truncatedFragment = $contLang->truncateForDatabase( $rt->getFragment(), 255 );
1075 $dbw->upsert(
1076 'redirect',
1077 [
1078 'rd_from' => $this->getId(),
1079 'rd_namespace' => $rt->getNamespace(),
1080 'rd_title' => $rt->getDBkey(),
1081 'rd_fragment' => $truncatedFragment,
1082 'rd_interwiki' => $rt->getInterwiki(),
1083 ],
1084 [ 'rd_from' ],
1085 [
1086 'rd_namespace' => $rt->getNamespace(),
1087 'rd_title' => $rt->getDBkey(),
1088 'rd_fragment' => $truncatedFragment,
1089 'rd_interwiki' => $rt->getInterwiki(),
1090 ],
1091 __METHOD__
1092 );
1093 $success = true;
1094 } else {
1095 $success = false;
1096 }
1097
1098 $dbw->endAtomic( __METHOD__ );
1099
1100 return $success;
1101 }
1102
1103 /**
1104 * Get the Title object or URL this page redirects to
1105 *
1106 * @return bool|Title|string False, Title of in-wiki target, or string with URL
1107 */
1108 public function followRedirect() {
1109 return $this->getRedirectURL( $this->getRedirectTarget() );
1110 }
1111
1112 /**
1113 * Get the Title object or URL to use for a redirect. We use Title
1114 * objects for same-wiki, non-special redirects and URLs for everything
1115 * else.
1116 * @param Title $rt Redirect target
1117 * @return bool|Title|string False, Title object of local target, or string with URL
1118 */
1119 public function getRedirectURL( $rt ) {
1120 if ( !$rt ) {
1121 return false;
1122 }
1123
1124 if ( $rt->isExternal() ) {
1125 if ( $rt->isLocal() ) {
1126 // Offsite wikis need an HTTP redirect.
1127 // This can be hard to reverse and may produce loops,
1128 // so they may be disabled in the site configuration.
1129 $source = $this->mTitle->getFullURL( 'redirect=no' );
1130 return $rt->getFullURL( [ 'rdfrom' => $source ] );
1131 } else {
1132 // External pages without "local" bit set are not valid
1133 // redirect targets
1134 return false;
1135 }
1136 }
1137
1138 if ( $rt->isSpecialPage() ) {
1139 // Gotta handle redirects to special pages differently:
1140 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1141 // Some pages are not valid targets.
1142 if ( $rt->isValidRedirectTarget() ) {
1143 return $rt->getFullURL();
1144 } else {
1145 return false;
1146 }
1147 }
1148
1149 return $rt;
1150 }
1151
1152 /**
1153 * Get a list of users who have edited this article, not including the user who made
1154 * the most recent revision, which you can get from $article->getUser() if you want it
1155 * @return UserArrayFromResult
1156 */
1157 public function getContributors() {
1158 // @todo: This is expensive; cache this info somewhere.
1159
1160 $dbr = wfGetDB( DB_REPLICA );
1161
1162 $actorMigration = ActorMigration::newMigration();
1163 $actorQuery = $actorMigration->getJoin( 'rev_user' );
1164
1165 $tables = array_merge( [ 'revision' ], $actorQuery['tables'], [ 'user' ] );
1166
1167 $fields = [
1168 'user_id' => $actorQuery['fields']['rev_user'],
1169 'user_name' => $actorQuery['fields']['rev_user_text'],
1170 'actor_id' => $actorQuery['fields']['rev_actor'],
1171 'user_real_name' => 'MIN(user_real_name)',
1172 'timestamp' => 'MAX(rev_timestamp)',
1173 ];
1174
1175 $conds = [ 'rev_page' => $this->getId() ];
1176
1177 // The user who made the top revision gets credited as "this page was last edited by
1178 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1179 $user = $this->getUser()
1180 ? User::newFromId( $this->getUser() )
1181 : User::newFromName( $this->getUserText(), false );
1182 $conds[] = 'NOT(' . $actorMigration->getWhere( $dbr, 'rev_user', $user )['conds'] . ')';
1183
1184 // Username hidden?
1185 $conds[] = "{$dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER )} = 0";
1186
1187 $jconds = [
1188 'user' => [ 'LEFT JOIN', $actorQuery['fields']['rev_user'] . ' = user_id' ],
1189 ] + $actorQuery['joins'];
1190
1191 $options = [
1192 'GROUP BY' => [ $fields['user_id'], $fields['user_name'] ],
1193 'ORDER BY' => 'timestamp DESC',
1194 ];
1195
1196 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1197 return new UserArrayFromResult( $res );
1198 }
1199
1200 /**
1201 * Should the parser cache be used?
1202 *
1203 * @param ParserOptions $parserOptions ParserOptions to check
1204 * @param int $oldId
1205 * @return bool
1206 */
1207 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1208 return $parserOptions->getStubThreshold() == 0
1209 && $this->exists()
1210 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1211 && $this->getContentHandler()->isParserCacheSupported();
1212 }
1213
1214 /**
1215 * Get a ParserOutput for the given ParserOptions and revision ID.
1216 *
1217 * The parser cache will be used if possible. Cache misses that result
1218 * in parser runs are debounced with PoolCounter.
1219 *
1220 * XXX merge this with updateParserCache()?
1221 *
1222 * @since 1.19
1223 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1224 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1225 * get the current revision (default value)
1226 * @param bool $forceParse Force reindexing, regardless of cache settings
1227 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1228 */
1229 public function getParserOutput(
1230 ParserOptions $parserOptions, $oldid = null, $forceParse = false
1231 ) {
1232 $useParserCache =
1233 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1234
1235 if ( $useParserCache && !$parserOptions->isSafeToCache() ) {
1236 throw new InvalidArgumentException(
1237 'The supplied ParserOptions are not safe to cache. Fix the options or set $forceParse = true.'
1238 );
1239 }
1240
1241 wfDebug( __METHOD__ .
1242 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1243 if ( $parserOptions->getStubThreshold() ) {
1244 wfIncrStats( 'pcache.miss.stub' );
1245 }
1246
1247 if ( $useParserCache ) {
1248 $parserOutput = $this->getParserCache()
1249 ->get( $this, $parserOptions );
1250 if ( $parserOutput !== false ) {
1251 return $parserOutput;
1252 }
1253 }
1254
1255 if ( $oldid === null || $oldid === 0 ) {
1256 $oldid = $this->getLatest();
1257 }
1258
1259 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1260 $pool->execute();
1261
1262 return $pool->getParserOutput();
1263 }
1264
1265 /**
1266 * Do standard deferred updates after page view (existing or missing page)
1267 * @param User $user The relevant user
1268 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1269 */
1270 public function doViewUpdates( User $user, $oldid = 0 ) {
1271 if ( wfReadOnly() ) {
1272 return;
1273 }
1274
1275 // Update newtalk / watchlist notification status;
1276 // Avoid outage if the master is not reachable by using a deferred updated
1277 DeferredUpdates::addCallableUpdate(
1278 function () use ( $user, $oldid ) {
1279 Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1280
1281 $user->clearNotification( $this->mTitle, $oldid );
1282 },
1283 DeferredUpdates::PRESEND
1284 );
1285 }
1286
1287 /**
1288 * Perform the actions of a page purging
1289 * @return bool
1290 * @note In 1.28 (and only 1.28), this took a $flags parameter that
1291 * controlled how much purging was done.
1292 */
1293 public function doPurge() {
1294 // Avoid PHP 7.1 warning of passing $this by reference
1295 $wikiPage = $this;
1296
1297 if ( !Hooks::run( 'ArticlePurge', [ &$wikiPage ] ) ) {
1298 return false;
1299 }
1300
1301 $this->mTitle->invalidateCache();
1302
1303 // Clear file cache
1304 HTMLFileCache::clearFileCache( $this->getTitle() );
1305 // Send purge after above page_touched update was committed
1306 DeferredUpdates::addUpdate(
1307 new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1308 DeferredUpdates::PRESEND
1309 );
1310
1311 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1312 $messageCache = MessageCache::singleton();
1313 $messageCache->updateMessageOverride( $this->mTitle, $this->getContent() );
1314 }
1315
1316 return true;
1317 }
1318
1319 /**
1320 * Insert a new empty page record for this article.
1321 * This *must* be followed up by creating a revision
1322 * and running $this->updateRevisionOn( ... );
1323 * or else the record will be left in a funky state.
1324 * Best if all done inside a transaction.
1325 *
1326 * @todo Factor out into a PageStore service, to be used by PageUpdater.
1327 *
1328 * @param IDatabase $dbw
1329 * @param int|null $pageId Custom page ID that will be used for the insert statement
1330 *
1331 * @return bool|int The newly created page_id key; false if the row was not
1332 * inserted, e.g. because the title already existed or because the specified
1333 * page ID is already in use.
1334 */
1335 public function insertOn( $dbw, $pageId = null ) {
1336 $pageIdForInsert = $pageId ? [ 'page_id' => $pageId ] : [];
1337 $dbw->insert(
1338 'page',
1339 [
1340 'page_namespace' => $this->mTitle->getNamespace(),
1341 'page_title' => $this->mTitle->getDBkey(),
1342 'page_restrictions' => '',
1343 'page_is_redirect' => 0, // Will set this shortly...
1344 'page_is_new' => 1,
1345 'page_random' => wfRandom(),
1346 'page_touched' => $dbw->timestamp(),
1347 'page_latest' => 0, // Fill this in shortly...
1348 'page_len' => 0, // Fill this in shortly...
1349 ] + $pageIdForInsert,
1350 __METHOD__,
1351 [ 'IGNORE' ]
1352 );
1353
1354 if ( $dbw->affectedRows() > 0 ) {
1355 $newid = $pageId ? (int)$pageId : $dbw->insertId();
1356 $this->mId = $newid;
1357 $this->mTitle->resetArticleID( $newid );
1358
1359 return $newid;
1360 } else {
1361 return false; // nothing changed
1362 }
1363 }
1364
1365 /**
1366 * Update the page record to point to a newly saved revision.
1367 *
1368 * @todo Factor out into a PageStore service, or move into PageUpdater.
1369 *
1370 * @param IDatabase $dbw
1371 * @param Revision $revision For ID number, and text used to set
1372 * length and redirect status fields
1373 * @param int|null $lastRevision If given, will not overwrite the page field
1374 * when different from the currently set value.
1375 * Giving 0 indicates the new page flag should be set on.
1376 * @param bool|null $lastRevIsRedirect If given, will optimize adding and
1377 * removing rows in redirect table.
1378 * @return bool Success; false if the page row was missing or page_latest changed
1379 */
1380 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1381 $lastRevIsRedirect = null
1382 ) {
1383 global $wgContentHandlerUseDB;
1384
1385 // TODO: move into PageUpdater or PageStore
1386 // NOTE: when doing that, make sure cached fields get reset in doEditContent,
1387 // and in the compat stub!
1388
1389 // Assertion to try to catch T92046
1390 if ( (int)$revision->getId() === 0 ) {
1391 throw new InvalidArgumentException(
1392 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1393 );
1394 }
1395
1396 $content = $revision->getContent();
1397 $len = $content ? $content->getSize() : 0;
1398 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1399
1400 $conditions = [ 'page_id' => $this->getId() ];
1401
1402 if ( !is_null( $lastRevision ) ) {
1403 // An extra check against threads stepping on each other
1404 $conditions['page_latest'] = $lastRevision;
1405 }
1406
1407 $revId = $revision->getId();
1408 Assert::parameter( $revId > 0, '$revision->getId()', 'must be > 0' );
1409
1410 $row = [ /* SET */
1411 'page_latest' => $revId,
1412 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1413 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1414 'page_is_redirect' => $rt !== null ? 1 : 0,
1415 'page_len' => $len,
1416 ];
1417
1418 if ( $wgContentHandlerUseDB ) {
1419 $row['page_content_model'] = $revision->getContentModel();
1420 }
1421
1422 $dbw->update( 'page',
1423 $row,
1424 $conditions,
1425 __METHOD__ );
1426
1427 $result = $dbw->affectedRows() > 0;
1428 if ( $result ) {
1429 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1430 $this->setLastEdit( $revision );
1431 $this->mLatest = $revision->getId();
1432 $this->mIsRedirect = (bool)$rt;
1433 // Update the LinkCache.
1434 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1435 $linkCache->addGoodLinkObj(
1436 $this->getId(),
1437 $this->mTitle,
1438 $len,
1439 $this->mIsRedirect,
1440 $this->mLatest,
1441 $revision->getContentModel()
1442 );
1443 }
1444
1445 return $result;
1446 }
1447
1448 /**
1449 * Add row to the redirect table if this is a redirect, remove otherwise.
1450 *
1451 * @param IDatabase $dbw
1452 * @param Title|null $redirectTitle Title object pointing to the redirect target,
1453 * or NULL if this is not a redirect
1454 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1455 * removing rows in redirect table.
1456 * @return bool True on success, false on failure
1457 * @private
1458 */
1459 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1460 // Always update redirects (target link might have changed)
1461 // Update/Insert if we don't know if the last revision was a redirect or not
1462 // Delete if changing from redirect to non-redirect
1463 $isRedirect = !is_null( $redirectTitle );
1464
1465 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1466 return true;
1467 }
1468
1469 if ( $isRedirect ) {
1470 $success = $this->insertRedirectEntry( $redirectTitle );
1471 } else {
1472 // This is not a redirect, remove row from redirect table
1473 $where = [ 'rd_from' => $this->getId() ];
1474 $dbw->delete( 'redirect', $where, __METHOD__ );
1475 $success = true;
1476 }
1477
1478 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1479 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1480 }
1481
1482 return $success;
1483 }
1484
1485 /**
1486 * If the given revision is newer than the currently set page_latest,
1487 * update the page record. Otherwise, do nothing.
1488 *
1489 * @deprecated since 1.24, use updateRevisionOn instead
1490 *
1491 * @param IDatabase $dbw
1492 * @param Revision $revision
1493 * @return bool
1494 */
1495 public function updateIfNewerOn( $dbw, $revision ) {
1496 $row = $dbw->selectRow(
1497 [ 'revision', 'page' ],
1498 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1499 [
1500 'page_id' => $this->getId(),
1501 'page_latest=rev_id' ],
1502 __METHOD__ );
1503
1504 if ( $row ) {
1505 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1506 return false;
1507 }
1508 $prev = $row->rev_id;
1509 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1510 } else {
1511 // No or missing previous revision; mark the page as new
1512 $prev = 0;
1513 $lastRevIsRedirect = null;
1514 }
1515
1516 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1517
1518 return $ret;
1519 }
1520
1521 /**
1522 * Helper method for checking whether two revisions have differences that go
1523 * beyond the main slot.
1524 *
1525 * MCR migration note: this method should go away!
1526 *
1527 * @deprecated Use only as a stop-gap before refactoring to support MCR.
1528 *
1529 * @param Revision $a
1530 * @param Revision $b
1531 * @return bool
1532 */
1533 public static function hasDifferencesOutsideMainSlot( Revision $a, Revision $b ) {
1534 $aSlots = $a->getRevisionRecord()->getSlots();
1535 $bSlots = $b->getRevisionRecord()->getSlots();
1536 $changedRoles = $aSlots->getRolesWithDifferentContent( $bSlots );
1537
1538 return ( $changedRoles !== [ SlotRecord::MAIN ] && $changedRoles !== [] );
1539 }
1540
1541 /**
1542 * Get the content that needs to be saved in order to undo all revisions
1543 * between $undo and $undoafter. Revisions must belong to the same page,
1544 * must exist and must not be deleted
1545 *
1546 * @param Revision $undo
1547 * @param Revision $undoafter Must be an earlier revision than $undo
1548 * @return Content|bool Content on success, false on failure
1549 * @since 1.21
1550 * Before we had the Content object, this was done in getUndoText
1551 */
1552 public function getUndoContent( Revision $undo, Revision $undoafter ) {
1553 // TODO: MCR: replace this with a method that returns a RevisionSlotsUpdate
1554
1555 if ( self::hasDifferencesOutsideMainSlot( $undo, $undoafter ) ) {
1556 // Cannot yet undo edits that involve anything other the main slot.
1557 return false;
1558 }
1559
1560 $handler = $undo->getContentHandler();
1561 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1562 }
1563
1564 /**
1565 * Returns true if this page's content model supports sections.
1566 *
1567 * @return bool
1568 *
1569 * @todo The skin should check this and not offer section functionality if
1570 * sections are not supported.
1571 * @todo The EditPage should check this and not offer section functionality
1572 * if sections are not supported.
1573 */
1574 public function supportsSections() {
1575 return $this->getContentHandler()->supportsSections();
1576 }
1577
1578 /**
1579 * @param string|int|null|bool $sectionId Section identifier as a number or string
1580 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1581 * or 'new' for a new section.
1582 * @param Content $sectionContent New content of the section.
1583 * @param string $sectionTitle New section's subject, only if $section is "new".
1584 * @param string $edittime Revision timestamp or null to use the current revision.
1585 *
1586 * @throws MWException
1587 * @return Content|null New complete article content, or null if error.
1588 *
1589 * @since 1.21
1590 * @deprecated since 1.24, use replaceSectionAtRev instead
1591 */
1592 public function replaceSectionContent(
1593 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1594 ) {
1595 $baseRevId = null;
1596 if ( $edittime && $sectionId !== 'new' ) {
1597 $lb = $this->getDBLoadBalancer();
1598 $dbr = $lb->getConnectionRef( DB_REPLICA );
1599 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1600 // Try the master if this thread may have just added it.
1601 // This could be abstracted into a Revision method, but we don't want
1602 // to encourage loading of revisions by timestamp.
1603 if ( !$rev
1604 && $lb->getServerCount() > 1
1605 && $lb->hasOrMadeRecentMasterChanges()
1606 ) {
1607 $dbw = $lb->getConnectionRef( DB_MASTER );
1608 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1609 }
1610 if ( $rev ) {
1611 $baseRevId = $rev->getId();
1612 }
1613 }
1614
1615 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1616 }
1617
1618 /**
1619 * @param string|int|null|bool $sectionId Section identifier as a number or string
1620 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1621 * or 'new' for a new section.
1622 * @param Content $sectionContent New content of the section.
1623 * @param string $sectionTitle New section's subject, only if $section is "new".
1624 * @param int|null $baseRevId
1625 *
1626 * @throws MWException
1627 * @return Content|null New complete article content, or null if error.
1628 *
1629 * @since 1.24
1630 */
1631 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1632 $sectionTitle = '', $baseRevId = null
1633 ) {
1634 if ( strval( $sectionId ) === '' ) {
1635 // Whole-page edit; let the whole text through
1636 $newContent = $sectionContent;
1637 } else {
1638 if ( !$this->supportsSections() ) {
1639 throw new MWException( "sections not supported for content model " .
1640 $this->getContentHandler()->getModelID() );
1641 }
1642
1643 // T32711: always use current version when adding a new section
1644 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1645 $oldContent = $this->getContent();
1646 } else {
1647 $rev = Revision::newFromId( $baseRevId );
1648 if ( !$rev ) {
1649 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1650 $this->getId() . "; section: $sectionId)\n" );
1651 return null;
1652 }
1653
1654 $oldContent = $rev->getContent();
1655 }
1656
1657 if ( !$oldContent ) {
1658 wfDebug( __METHOD__ . ": no page text\n" );
1659 return null;
1660 }
1661
1662 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1663 }
1664
1665 return $newContent;
1666 }
1667
1668 /**
1669 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1670 *
1671 * @deprecated since 1.32, use exists() instead, or simply omit the EDIT_UPDATE
1672 * and EDIT_NEW flags. To protect against race conditions, use PageUpdater::grabParentRevision.
1673 *
1674 * @param int $flags
1675 * @return int Updated $flags
1676 */
1677 public function checkFlags( $flags ) {
1678 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1679 if ( $this->exists() ) {
1680 $flags |= EDIT_UPDATE;
1681 } else {
1682 $flags |= EDIT_NEW;
1683 }
1684 }
1685
1686 return $flags;
1687 }
1688
1689 /**
1690 * @return DerivedPageDataUpdater
1691 */
1692 private function newDerivedDataUpdater() {
1693 global $wgRCWatchCategoryMembership, $wgArticleCountMethod;
1694
1695 $derivedDataUpdater = new DerivedPageDataUpdater(
1696 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1697 $this->getRevisionStore(),
1698 $this->getRevisionRenderer(),
1699 $this->getSlotRoleRegistry(),
1700 $this->getParserCache(),
1701 JobQueueGroup::singleton(),
1702 MessageCache::singleton(),
1703 MediaWikiServices::getInstance()->getContentLanguage(),
1704 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()
1705 );
1706
1707 $derivedDataUpdater->setLogger( LoggerFactory::getInstance( 'SaveParse' ) );
1708 $derivedDataUpdater->setRcWatchCategoryMembership( $wgRCWatchCategoryMembership );
1709 $derivedDataUpdater->setArticleCountMethod( $wgArticleCountMethod );
1710
1711 return $derivedDataUpdater;
1712 }
1713
1714 /**
1715 * Returns a DerivedPageDataUpdater for use with the given target revision or new content.
1716 * This method attempts to re-use the same DerivedPageDataUpdater instance for subsequent calls.
1717 * The parameters passed to this method are used to ensure that the DerivedPageDataUpdater
1718 * returned matches that caller's expectations, allowing an existing instance to be re-used
1719 * if the given parameters match that instance's internal state according to
1720 * DerivedPageDataUpdater::isReusableFor(), and creating a new instance of the parameters do not
1721 * match the existign one.
1722 *
1723 * If neither $forRevision nor $forUpdate is given, a new DerivedPageDataUpdater is always
1724 * created, replacing any DerivedPageDataUpdater currently cached.
1725 *
1726 * MCR migration note: this replaces WikiPage::prepareContentForEdit.
1727 *
1728 * @since 1.32
1729 *
1730 * @param User|null $forUser The user that will be used for, or was used for, PST.
1731 * @param RevisionRecord|null $forRevision The revision created by the edit for which
1732 * to perform updates, if the edit was already saved.
1733 * @param RevisionSlotsUpdate|null $forUpdate The new content to be saved by the edit (pre PST),
1734 * if the edit was not yet saved.
1735 * @param bool $forEdit Only re-use if the cached DerivedPageDataUpdater has the current
1736 * revision as the edit's parent revision. This ensures that the same
1737 * DerivedPageDataUpdater cannot be re-used for two consecutive edits.
1738 *
1739 * @return DerivedPageDataUpdater
1740 */
1741 private function getDerivedDataUpdater(
1742 User $forUser = null,
1743 RevisionRecord $forRevision = null,
1744 RevisionSlotsUpdate $forUpdate = null,
1745 $forEdit = false
1746 ) {
1747 if ( !$forRevision && !$forUpdate ) {
1748 // NOTE: can't re-use an existing derivedDataUpdater if we don't know what the caller is
1749 // going to use it with.
1750 $this->derivedDataUpdater = null;
1751 }
1752
1753 if ( $this->derivedDataUpdater && !$this->derivedDataUpdater->isContentPrepared() ) {
1754 // NOTE: can't re-use an existing derivedDataUpdater if other code that has a reference
1755 // to it did not yet initialize it, because we don't know what data it will be
1756 // initialized with.
1757 $this->derivedDataUpdater = null;
1758 }
1759
1760 // XXX: It would be nice to have an LRU cache instead of trying to re-use a single instance.
1761 // However, there is no good way to construct a cache key. We'd need to check against all
1762 // cached instances.
1763
1764 if ( $this->derivedDataUpdater
1765 && !$this->derivedDataUpdater->isReusableFor(
1766 $forUser,
1767 $forRevision,
1768 $forUpdate,
1769 $forEdit ? $this->getLatest() : null
1770 )
1771 ) {
1772 $this->derivedDataUpdater = null;
1773 }
1774
1775 if ( !$this->derivedDataUpdater ) {
1776 $this->derivedDataUpdater = $this->newDerivedDataUpdater();
1777 }
1778
1779 return $this->derivedDataUpdater;
1780 }
1781
1782 /**
1783 * Returns a PageUpdater for creating new revisions on this page (or creating the page).
1784 *
1785 * The PageUpdater can also be used to detect the need for edit conflict resolution,
1786 * and to protected such conflict resolution from concurrent edits using a check-and-set
1787 * mechanism.
1788 *
1789 * @since 1.32
1790 *
1791 * @param User $user
1792 * @param RevisionSlotsUpdate|null $forUpdate If given, allows any cached ParserOutput
1793 * that may already have been returned via getDerivedDataUpdater to be re-used.
1794 *
1795 * @return PageUpdater
1796 */
1797 public function newPageUpdater( User $user, RevisionSlotsUpdate $forUpdate = null ) {
1798 global $wgAjaxEditStash, $wgUseAutomaticEditSummaries, $wgPageCreationLog;
1799
1800 $pageUpdater = new PageUpdater(
1801 $user,
1802 $this, // NOTE: eventually, PageUpdater should not know about WikiPage
1803 $this->getDerivedDataUpdater( $user, null, $forUpdate, true ),
1804 $this->getDBLoadBalancer(),
1805 $this->getRevisionStore(),
1806 $this->getSlotRoleRegistry()
1807 );
1808
1809 $pageUpdater->setUsePageCreationLog( $wgPageCreationLog );
1810 $pageUpdater->setAjaxEditStash( $wgAjaxEditStash );
1811 $pageUpdater->setUseAutomaticEditSummaries( $wgUseAutomaticEditSummaries );
1812
1813 return $pageUpdater;
1814 }
1815
1816 /**
1817 * Change an existing article or create a new article. Updates RC and all necessary caches,
1818 * optionally via the deferred update array.
1819 *
1820 * @deprecated since 1.32, use PageUpdater::saveRevision instead. Note that the new method
1821 * expects callers to take care of checking EDIT_MINOR against the minoredit right, and to
1822 * apply the autopatrol right as appropriate.
1823 *
1824 * @param Content $content New content
1825 * @param string|CommentStoreComment $summary Edit summary
1826 * @param int $flags Bitfield:
1827 * EDIT_NEW
1828 * Article is known or assumed to be non-existent, create a new one
1829 * EDIT_UPDATE
1830 * Article is known or assumed to be pre-existing, update it
1831 * EDIT_MINOR
1832 * Mark this edit minor, if the user is allowed to do so
1833 * EDIT_SUPPRESS_RC
1834 * Do not log the change in recentchanges
1835 * EDIT_FORCE_BOT
1836 * Mark the edit a "bot" edit regardless of user rights
1837 * EDIT_AUTOSUMMARY
1838 * Fill in blank summaries with generated text where possible
1839 * EDIT_INTERNAL
1840 * Signal that the page retrieve/save cycle happened entirely in this request.
1841 *
1842 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1843 * article will be detected. If EDIT_UPDATE is specified and the article
1844 * doesn't exist, the function will return an edit-gone-missing error. If
1845 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1846 * error will be returned. These two conditions are also possible with
1847 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1848 *
1849 * @param bool|int $originalRevId: The ID of an original revision that the edit
1850 * restores or repeats. The new revision is expected to have the exact same content as
1851 * the given original revision. This is used with rollbacks and with dummy "null" revisions
1852 * which are created to record things like page moves.
1853 * @param User|null $user The user doing the edit
1854 * @param string|null $serialFormat IGNORED.
1855 * @param array|null $tags Change tags to apply to this edit
1856 * Callers are responsible for permission checks
1857 * (with ChangeTags::canAddTagsAccompanyingChange)
1858 * @param Int $undidRevId Id of revision that was undone or 0
1859 *
1860 * @throws MWException
1861 * @return Status Possible errors:
1862 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1863 * set the fatal flag of $status.
1864 * edit-gone-missing: In update mode, but the article didn't exist.
1865 * edit-conflict: In update mode, the article changed unexpectedly.
1866 * edit-no-change: Warning that the text was the same as before.
1867 * edit-already-exists: In creation mode, but the article already exists.
1868 *
1869 * Extensions may define additional errors.
1870 *
1871 * $return->value will contain an associative array with members as follows:
1872 * new: Boolean indicating if the function attempted to create a new article.
1873 * revision: The revision object for the inserted revision, or null.
1874 *
1875 * @since 1.21
1876 * @throws MWException
1877 */
1878 public function doEditContent(
1879 Content $content, $summary, $flags = 0, $originalRevId = false,
1880 User $user = null, $serialFormat = null, $tags = [], $undidRevId = 0
1881 ) {
1882 global $wgUser, $wgUseNPPatrol, $wgUseRCPatrol;
1883
1884 if ( !( $summary instanceof CommentStoreComment ) ) {
1885 $summary = CommentStoreComment::newUnsavedComment( trim( $summary ) );
1886 }
1887
1888 if ( !$user ) {
1889 $user = $wgUser;
1890 }
1891
1892 // TODO: this check is here for backwards-compatibility with 1.31 behavior.
1893 // Checking the minoredit right should be done in the same place the 'bot' right is
1894 // checked for the EDIT_FORCE_BOT flag, which is currently in EditPage::attemptSave.
1895 if ( ( $flags & EDIT_MINOR ) && !$user->isAllowed( 'minoredit' ) ) {
1896 $flags = ( $flags & ~EDIT_MINOR );
1897 }
1898
1899 $slotsUpdate = new RevisionSlotsUpdate();
1900 $slotsUpdate->modifyContent( SlotRecord::MAIN, $content );
1901
1902 // NOTE: while doEditContent() executes, callbacks to getDerivedDataUpdater and
1903 // prepareContentForEdit will generally use the DerivedPageDataUpdater that is also
1904 // used by this PageUpdater. However, there is no guarantee for this.
1905 $updater = $this->newPageUpdater( $user, $slotsUpdate );
1906 $updater->setContent( SlotRecord::MAIN, $content );
1907 $updater->setOriginalRevisionId( $originalRevId );
1908 $updater->setUndidRevisionId( $undidRevId );
1909
1910 $needsPatrol = $wgUseRCPatrol || ( $wgUseNPPatrol && !$this->exists() );
1911
1912 // TODO: this logic should not be in the storage layer, it's here for compatibility
1913 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
1914 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
1915 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1916
1917 if ( $needsPatrol && $permissionManager->userCan(
1918 'autopatrol', $user, $this->getTitle()
1919 ) ) {
1920 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
1921 }
1922
1923 $updater->addTags( $tags );
1924
1925 $revRec = $updater->saveRevision(
1926 $summary,
1927 $flags
1928 );
1929
1930 // $revRec will be null if the edit failed, or if no new revision was created because
1931 // the content did not change.
1932 if ( $revRec ) {
1933 // update cached fields
1934 // TODO: this is currently redundant to what is done in updateRevisionOn.
1935 // But updateRevisionOn() should move into PageStore, and then this will be needed.
1936 $this->setLastEdit( new Revision( $revRec ) ); // TODO: use RevisionRecord
1937 $this->mLatest = $revRec->getId();
1938 }
1939
1940 return $updater->getStatus();
1941 }
1942
1943 /**
1944 * Get parser options suitable for rendering the primary article wikitext
1945 *
1946 * @see ParserOptions::newCanonical
1947 *
1948 * @param IContextSource|User|string $context One of the following:
1949 * - IContextSource: Use the User and the Language of the provided
1950 * context
1951 * - User: Use the provided User object and $wgLang for the language,
1952 * so use an IContextSource object if possible.
1953 * - 'canonical': Canonical options (anonymous user with default
1954 * preferences and content language).
1955 * @return ParserOptions
1956 */
1957 public function makeParserOptions( $context ) {
1958 $options = ParserOptions::newCanonical( $context );
1959
1960 if ( $this->getTitle()->isConversionTable() ) {
1961 // @todo ConversionTable should become a separate content model, so
1962 // we don't need special cases like this one.
1963 $options->disableContentConversion();
1964 }
1965
1966 return $options;
1967 }
1968
1969 /**
1970 * Prepare content which is about to be saved.
1971 *
1972 * Prior to 1.30, this returned a stdClass.
1973 *
1974 * @deprecated since 1.32, use getDerivedDataUpdater instead.
1975 *
1976 * @param Content $content
1977 * @param Revision|RevisionRecord|null $revision Revision object.
1978 * Used with vary-revision or vary-revision-id.
1979 * @param User|null $user
1980 * @param string|null $serialFormat IGNORED
1981 * @param bool $useCache Check shared prepared edit cache
1982 *
1983 * @return PreparedEdit
1984 *
1985 * @since 1.21
1986 */
1987 public function prepareContentForEdit(
1988 Content $content,
1989 $revision = null,
1990 User $user = null,
1991 $serialFormat = null,
1992 $useCache = true
1993 ) {
1994 global $wgUser;
1995
1996 if ( !$user ) {
1997 $user = $wgUser;
1998 }
1999
2000 if ( $revision !== null ) {
2001 if ( $revision instanceof Revision ) {
2002 $revision = $revision->getRevisionRecord();
2003 } elseif ( !( $revision instanceof RevisionRecord ) ) {
2004 throw new InvalidArgumentException(
2005 __METHOD__ . ': invalid $revision argument type ' . gettype( $revision ) );
2006 }
2007 }
2008
2009 $slots = RevisionSlotsUpdate::newFromContent( [ SlotRecord::MAIN => $content ] );
2010 $updater = $this->getDerivedDataUpdater( $user, $revision, $slots );
2011
2012 if ( !$updater->isUpdatePrepared() ) {
2013 $updater->prepareContent( $user, $slots, $useCache );
2014
2015 if ( $revision ) {
2016 $updater->prepareUpdate(
2017 $revision,
2018 [
2019 'causeAction' => 'prepare-edit',
2020 'causeAgent' => $user->getName(),
2021 ]
2022 );
2023 }
2024 }
2025
2026 return $updater->getPreparedEdit();
2027 }
2028
2029 /**
2030 * Do standard deferred updates after page edit.
2031 * Update links tables, site stats, search index and message cache.
2032 * Purges pages that include this page if the text was changed here.
2033 * Every 100th edit, prune the recent changes table.
2034 *
2035 * @deprecated since 1.32, use PageUpdater::doUpdates instead.
2036 *
2037 * @param Revision $revision
2038 * @param User $user User object that did the revision
2039 * @param array $options Array of options, following indexes are used:
2040 * - changed: bool, whether the revision changed the content (default true)
2041 * - created: bool, whether the revision created the page (default false)
2042 * - moved: bool, whether the page was moved (default false)
2043 * - restored: bool, whether the page was undeleted (default false)
2044 * - oldrevision: Revision object for the pre-update revision (default null)
2045 * - oldcountable: bool, null, or string 'no-change' (default null):
2046 * - bool: whether the page was counted as an article before that
2047 * revision, only used in changed is true and created is false
2048 * - null: if created is false, don't update the article count; if created
2049 * is true, do update the article count
2050 * - 'no-change': don't update the article count, ever
2051 * - causeAction: an arbitrary string identifying the reason for the update.
2052 * See DataUpdate::getCauseAction(). (default 'edit-page')
2053 * - causeAgent: name of the user who caused the update. See DataUpdate::getCauseAgent().
2054 * (string, defaults to the passed user)
2055 */
2056 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2057 $options += [
2058 'causeAction' => 'edit-page',
2059 'causeAgent' => $user->getName(),
2060 ];
2061
2062 $revision = $revision->getRevisionRecord();
2063
2064 $updater = $this->getDerivedDataUpdater( $user, $revision );
2065
2066 $updater->prepareUpdate( $revision, $options );
2067
2068 $updater->doUpdates();
2069 }
2070
2071 /**
2072 * Update the parser cache.
2073 *
2074 * @note This is a temporary workaround until there is a proper data updater class.
2075 * It will become deprecated soon.
2076 *
2077 * @param array $options
2078 * - causeAction: an arbitrary string identifying the reason for the update.
2079 * See DataUpdate::getCauseAction(). (default 'edit-page')
2080 * - causeAgent: name of the user who caused the update (string, defaults to the
2081 * user who created the revision)
2082 * @since 1.32
2083 */
2084 public function updateParserCache( array $options = [] ) {
2085 $revision = $this->getRevisionRecord();
2086 if ( !$revision || !$revision->getId() ) {
2087 LoggerFactory::getInstance( 'wikipage' )->info(
2088 __METHOD__ . 'called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
2089 );
2090 return;
2091 }
2092 $user = User::newFromIdentity( $revision->getUser( RevisionRecord::RAW ) );
2093
2094 $updater = $this->getDerivedDataUpdater( $user, $revision );
2095 $updater->prepareUpdate( $revision, $options );
2096 $updater->doParserCacheUpdate();
2097 }
2098
2099 /**
2100 * Do secondary data updates (such as updating link tables).
2101 * Secondary data updates are only a small part of the updates needed after saving
2102 * a new revision; normally PageUpdater::doUpdates should be used instead (which includes
2103 * secondary data updates). This method is provided for partial purges.
2104 *
2105 * @note This is a temporary workaround until there is a proper data updater class.
2106 * It will become deprecated soon.
2107 *
2108 * @param array $options
2109 * - recursive (bool, default true): whether to do a recursive update (update pages that
2110 * depend on this page, e.g. transclude it). This will set the $recursive parameter of
2111 * Content::getSecondaryDataUpdates. Typically this should be true unless the update
2112 * was something that did not really change the page, such as a null edit.
2113 * - triggeringUser: The user triggering the update (UserIdentity, defaults to the
2114 * user who created the revision)
2115 * - causeAction: an arbitrary string identifying the reason for the update.
2116 * See DataUpdate::getCauseAction(). (default 'unknown')
2117 * - causeAgent: name of the user who caused the update (string, default 'unknown')
2118 * - defer: one of the DeferredUpdates constants, or false to run immediately (default: false).
2119 * Note that even when this is set to false, some updates might still get deferred (as
2120 * some update might directly add child updates to DeferredUpdates).
2121 * - known-revision-output: a combined canonical ParserOutput for the revision, perhaps
2122 * from some cache. The caller is responsible for ensuring that the ParserOutput indeed
2123 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
2124 * for the time until caches have been changed to store RenderedRevision states instead
2125 * of ParserOutput objects. (default: null) (since 1.33)
2126 * @since 1.32
2127 */
2128 public function doSecondaryDataUpdates( array $options = [] ) {
2129 $options['recursive'] = $options['recursive'] ?? true;
2130 $revision = $this->getRevisionRecord();
2131 if ( !$revision || !$revision->getId() ) {
2132 LoggerFactory::getInstance( 'wikipage' )->info(
2133 __METHOD__ . 'called with ' . ( $revision ? 'unsaved' : 'no' ) . ' revision'
2134 );
2135 return;
2136 }
2137 $user = User::newFromIdentity( $revision->getUser( RevisionRecord::RAW ) );
2138
2139 $updater = $this->getDerivedDataUpdater( $user, $revision );
2140 $updater->prepareUpdate( $revision, $options );
2141 $updater->doSecondaryDataUpdates( $options );
2142 }
2143
2144 /**
2145 * Update the article's restriction field, and leave a log entry.
2146 * This works for protection both existing and non-existing pages.
2147 *
2148 * @param array $limit Set of restriction keys
2149 * @param array $expiry Per restriction type expiration
2150 * @param int &$cascade Set to false if cascading protection isn't allowed.
2151 * @param string $reason
2152 * @param User $user The user updating the restrictions
2153 * @param string|string[]|null $tags Change tags to add to the pages and protection log entries
2154 * ($user should be able to add the specified tags before this is called)
2155 * @return Status Status object; if action is taken, $status->value is the log_id of the
2156 * protection log entry.
2157 */
2158 public function doUpdateRestrictions( array $limit, array $expiry,
2159 &$cascade, $reason, User $user, $tags = null
2160 ) {
2161 global $wgCascadingRestrictionLevels;
2162
2163 if ( wfReadOnly() ) {
2164 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
2165 }
2166
2167 $this->loadPageData( 'fromdbmaster' );
2168 $this->mTitle->loadRestrictions( null, Title::READ_LATEST );
2169 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2170 $id = $this->getId();
2171
2172 if ( !$cascade ) {
2173 $cascade = false;
2174 }
2175
2176 // Take this opportunity to purge out expired restrictions
2177 Title::purgeExpiredRestrictions();
2178
2179 // @todo: Same limitations as described in ProtectionForm.php (line 37);
2180 // we expect a single selection, but the schema allows otherwise.
2181 $isProtected = false;
2182 $protect = false;
2183 $changed = false;
2184
2185 $dbw = wfGetDB( DB_MASTER );
2186
2187 foreach ( $restrictionTypes as $action ) {
2188 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2189 $expiry[$action] = 'infinity';
2190 }
2191 if ( !isset( $limit[$action] ) ) {
2192 $limit[$action] = '';
2193 } elseif ( $limit[$action] != '' ) {
2194 $protect = true;
2195 }
2196
2197 // Get current restrictions on $action
2198 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2199 if ( $current != '' ) {
2200 $isProtected = true;
2201 }
2202
2203 if ( $limit[$action] != $current ) {
2204 $changed = true;
2205 } elseif ( $limit[$action] != '' ) {
2206 // Only check expiry change if the action is actually being
2207 // protected, since expiry does nothing on an not-protected
2208 // action.
2209 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2210 $changed = true;
2211 }
2212 }
2213 }
2214
2215 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2216 $changed = true;
2217 }
2218
2219 // If nothing has changed, do nothing
2220 if ( !$changed ) {
2221 return Status::newGood();
2222 }
2223
2224 if ( !$protect ) { // No protection at all means unprotection
2225 $revCommentMsg = 'unprotectedarticle-comment';
2226 $logAction = 'unprotect';
2227 } elseif ( $isProtected ) {
2228 $revCommentMsg = 'modifiedarticleprotection-comment';
2229 $logAction = 'modify';
2230 } else {
2231 $revCommentMsg = 'protectedarticle-comment';
2232 $logAction = 'protect';
2233 }
2234
2235 $logRelationsValues = [];
2236 $logRelationsField = null;
2237 $logParamsDetails = [];
2238
2239 // Null revision (used for change tag insertion)
2240 $nullRevision = null;
2241
2242 if ( $id ) { // Protection of existing page
2243 // Avoid PHP 7.1 warning of passing $this by reference
2244 $wikiPage = $this;
2245
2246 if ( !Hooks::run( 'ArticleProtect', [ &$wikiPage, &$user, $limit, $reason ] ) ) {
2247 return Status::newGood();
2248 }
2249
2250 // Only certain restrictions can cascade...
2251 $editrestriction = isset( $limit['edit'] )
2252 ? [ $limit['edit'] ]
2253 : $this->mTitle->getRestrictions( 'edit' );
2254 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2255 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2256 }
2257 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2258 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2259 }
2260
2261 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2262 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2263 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2264 }
2265 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2266 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2267 }
2268
2269 // The schema allows multiple restrictions
2270 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2271 $cascade = false;
2272 }
2273
2274 // insert null revision to identify the page protection change as edit summary
2275 $latest = $this->getLatest();
2276 $nullRevision = $this->insertProtectNullRevision(
2277 $revCommentMsg,
2278 $limit,
2279 $expiry,
2280 $cascade,
2281 $reason,
2282 $user
2283 );
2284
2285 if ( $nullRevision === null ) {
2286 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2287 }
2288
2289 $logRelationsField = 'pr_id';
2290
2291 // Update restrictions table
2292 foreach ( $limit as $action => $restrictions ) {
2293 $dbw->delete(
2294 'page_restrictions',
2295 [
2296 'pr_page' => $id,
2297 'pr_type' => $action
2298 ],
2299 __METHOD__
2300 );
2301 if ( $restrictions != '' ) {
2302 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2303 $dbw->insert(
2304 'page_restrictions',
2305 [
2306 'pr_page' => $id,
2307 'pr_type' => $action,
2308 'pr_level' => $restrictions,
2309 'pr_cascade' => $cascadeValue,
2310 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2311 ],
2312 __METHOD__
2313 );
2314 $logRelationsValues[] = $dbw->insertId();
2315 $logParamsDetails[] = [
2316 'type' => $action,
2317 'level' => $restrictions,
2318 'expiry' => $expiry[$action],
2319 'cascade' => (bool)$cascadeValue,
2320 ];
2321 }
2322 }
2323
2324 // Clear out legacy restriction fields
2325 $dbw->update(
2326 'page',
2327 [ 'page_restrictions' => '' ],
2328 [ 'page_id' => $id ],
2329 __METHOD__
2330 );
2331
2332 // Avoid PHP 7.1 warning of passing $this by reference
2333 $wikiPage = $this;
2334
2335 Hooks::run( 'NewRevisionFromEditComplete',
2336 [ $this, $nullRevision, $latest, $user ] );
2337 Hooks::run( 'ArticleProtectComplete', [ &$wikiPage, &$user, $limit, $reason ] );
2338 } else { // Protection of non-existing page (also known as "title protection")
2339 // Cascade protection is meaningless in this case
2340 $cascade = false;
2341
2342 if ( $limit['create'] != '' ) {
2343 $commentFields = CommentStore::getStore()->insert( $dbw, 'pt_reason', $reason );
2344 $dbw->replace( 'protected_titles',
2345 [ [ 'pt_namespace', 'pt_title' ] ],
2346 [
2347 'pt_namespace' => $this->mTitle->getNamespace(),
2348 'pt_title' => $this->mTitle->getDBkey(),
2349 'pt_create_perm' => $limit['create'],
2350 'pt_timestamp' => $dbw->timestamp(),
2351 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2352 'pt_user' => $user->getId(),
2353 ] + $commentFields, __METHOD__
2354 );
2355 $logParamsDetails[] = [
2356 'type' => 'create',
2357 'level' => $limit['create'],
2358 'expiry' => $expiry['create'],
2359 ];
2360 } else {
2361 $dbw->delete( 'protected_titles',
2362 [
2363 'pt_namespace' => $this->mTitle->getNamespace(),
2364 'pt_title' => $this->mTitle->getDBkey()
2365 ], __METHOD__
2366 );
2367 }
2368 }
2369
2370 $this->mTitle->flushRestrictions();
2371 InfoAction::invalidateCache( $this->mTitle );
2372
2373 if ( $logAction == 'unprotect' ) {
2374 $params = [];
2375 } else {
2376 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2377 $params = [
2378 '4::description' => $protectDescriptionLog, // parameter for IRC
2379 '5:bool:cascade' => $cascade,
2380 'details' => $logParamsDetails, // parameter for localize and api
2381 ];
2382 }
2383
2384 // Update the protection log
2385 $logEntry = new ManualLogEntry( 'protect', $logAction );
2386 $logEntry->setTarget( $this->mTitle );
2387 $logEntry->setComment( $reason );
2388 $logEntry->setPerformer( $user );
2389 $logEntry->setParameters( $params );
2390 if ( !is_null( $nullRevision ) ) {
2391 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2392 }
2393 $logEntry->addTags( $tags );
2394 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2395 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2396 }
2397 $logId = $logEntry->insert();
2398 $logEntry->publish( $logId );
2399
2400 return Status::newGood( $logId );
2401 }
2402
2403 /**
2404 * Insert a new null revision for this page.
2405 *
2406 * @param string $revCommentMsg Comment message key for the revision
2407 * @param array $limit Set of restriction keys
2408 * @param array $expiry Per restriction type expiration
2409 * @param int $cascade Set to false if cascading protection isn't allowed.
2410 * @param string $reason
2411 * @param User|null $user
2412 * @return Revision|null Null on error
2413 */
2414 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2415 array $expiry, $cascade, $reason, $user = null
2416 ) {
2417 $dbw = wfGetDB( DB_MASTER );
2418
2419 // Prepare a null revision to be added to the history
2420 $editComment = wfMessage(
2421 $revCommentMsg,
2422 $this->mTitle->getPrefixedText(),
2423 $user ? $user->getName() : ''
2424 )->inContentLanguage()->text();
2425 if ( $reason ) {
2426 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2427 }
2428 $protectDescription = $this->protectDescription( $limit, $expiry );
2429 if ( $protectDescription ) {
2430 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2431 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2432 ->inContentLanguage()->text();
2433 }
2434 if ( $cascade ) {
2435 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2436 $editComment .= wfMessage( 'brackets' )->params(
2437 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2438 )->inContentLanguage()->text();
2439 }
2440
2441 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2442 if ( $nullRev ) {
2443 $nullRev->insertOn( $dbw );
2444
2445 // Update page record and touch page
2446 $oldLatest = $nullRev->getParentId();
2447 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2448 }
2449
2450 return $nullRev;
2451 }
2452
2453 /**
2454 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2455 * @return string
2456 */
2457 protected function formatExpiry( $expiry ) {
2458 if ( $expiry != 'infinity' ) {
2459 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2460 return wfMessage(
2461 'protect-expiring',
2462 $contLang->timeanddate( $expiry, false, false ),
2463 $contLang->date( $expiry, false, false ),
2464 $contLang->time( $expiry, false, false )
2465 )->inContentLanguage()->text();
2466 } else {
2467 return wfMessage( 'protect-expiry-indefinite' )
2468 ->inContentLanguage()->text();
2469 }
2470 }
2471
2472 /**
2473 * Builds the description to serve as comment for the edit.
2474 *
2475 * @param array $limit Set of restriction keys
2476 * @param array $expiry Per restriction type expiration
2477 * @return string
2478 */
2479 public function protectDescription( array $limit, array $expiry ) {
2480 $protectDescription = '';
2481
2482 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2483 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2484 # All possible message keys are listed here for easier grepping:
2485 # * restriction-create
2486 # * restriction-edit
2487 # * restriction-move
2488 # * restriction-upload
2489 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2490 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2491 # with '' filtered out. All possible message keys are listed below:
2492 # * protect-level-autoconfirmed
2493 # * protect-level-sysop
2494 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2495 ->inContentLanguage()->text();
2496
2497 $expiryText = $this->formatExpiry( $expiry[$action] );
2498
2499 if ( $protectDescription !== '' ) {
2500 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2501 }
2502 $protectDescription .= wfMessage( 'protect-summary-desc' )
2503 ->params( $actionText, $restrictionsText, $expiryText )
2504 ->inContentLanguage()->text();
2505 }
2506
2507 return $protectDescription;
2508 }
2509
2510 /**
2511 * Builds the description to serve as comment for the log entry.
2512 *
2513 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2514 * protect description text. Keep them in old format to avoid breaking compatibility.
2515 * TODO: Fix protection log to store structured description and format it on-the-fly.
2516 *
2517 * @param array $limit Set of restriction keys
2518 * @param array $expiry Per restriction type expiration
2519 * @return string
2520 */
2521 public function protectDescriptionLog( array $limit, array $expiry ) {
2522 $protectDescriptionLog = '';
2523
2524 $dirMark = MediaWikiServices::getInstance()->getContentLanguage()->getDirMark();
2525 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2526 $expiryText = $this->formatExpiry( $expiry[$action] );
2527 $protectDescriptionLog .=
2528 $dirMark .
2529 "[$action=$restrictions] ($expiryText)";
2530 }
2531
2532 return trim( $protectDescriptionLog );
2533 }
2534
2535 /**
2536 * Take an array of page restrictions and flatten it to a string
2537 * suitable for insertion into the page_restrictions field.
2538 *
2539 * @param string[] $limit
2540 *
2541 * @throws MWException
2542 * @return string
2543 */
2544 protected static function flattenRestrictions( $limit ) {
2545 if ( !is_array( $limit ) ) {
2546 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2547 }
2548
2549 $bits = [];
2550 ksort( $limit );
2551
2552 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2553 $bits[] = "$action=$restrictions";
2554 }
2555
2556 return implode( ':', $bits );
2557 }
2558
2559 /**
2560 * Determines if deletion of this page would be batched (executed over time by the job queue)
2561 * or not (completed in the same request as the delete call).
2562 *
2563 * It is unlikely but possible that an edit from another request could push the page over the
2564 * batching threshold after this function is called, but before the caller acts upon the
2565 * return value. Callers must decide for themselves how to deal with this. $safetyMargin
2566 * is provided as an unreliable but situationally useful help for some common cases.
2567 *
2568 * @param int $safetyMargin Added to the revision count when checking for batching
2569 * @return bool True if deletion would be batched, false otherwise
2570 */
2571 public function isBatchedDelete( $safetyMargin = 0 ) {
2572 global $wgDeleteRevisionsBatchSize;
2573
2574 $dbr = wfGetDB( DB_REPLICA );
2575 $revCount = $this->getRevisionStore()->countRevisionsByPageId( $dbr, $this->getId() );
2576 $revCount += $safetyMargin;
2577
2578 return $revCount >= $wgDeleteRevisionsBatchSize;
2579 }
2580
2581 /**
2582 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2583 * backwards compatibility, if you care about error reporting you should use
2584 * doDeleteArticleReal() instead.
2585 *
2586 * Deletes the article with database consistency, writes logs, purges caches
2587 *
2588 * @param string $reason Delete reason for deletion log
2589 * @param bool $suppress Suppress all revisions and log the deletion in
2590 * the suppression log instead of the deletion log
2591 * @param int|null $u1 Unused
2592 * @param bool|null $u2 Unused
2593 * @param array|string &$error Array of errors to append to
2594 * @param User|null $user The deleting user
2595 * @param bool $immediate false allows deleting over time via the job queue
2596 * @return bool True if successful
2597 * @throws FatalError
2598 * @throws MWException
2599 */
2600 public function doDeleteArticle(
2601 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2602 $immediate = false
2603 ) {
2604 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user,
2605 [], 'delete', $immediate );
2606
2607 // Returns true if the page was actually deleted, or is scheduled for deletion
2608 return $status->isOK();
2609 }
2610
2611 /**
2612 * Back-end article deletion
2613 * Deletes the article with database consistency, writes logs, purges caches
2614 *
2615 * @since 1.19
2616 *
2617 * @param string $reason Delete reason for deletion log
2618 * @param bool $suppress Suppress all revisions and log the deletion in
2619 * the suppression log instead of the deletion log
2620 * @param int|null $u1 Unused
2621 * @param bool|null $u2 Unused
2622 * @param array|string &$error Array of errors to append to
2623 * @param User|null $deleter The deleting user
2624 * @param array $tags Tags to apply to the deletion action
2625 * @param string $logsubtype
2626 * @param bool $immediate false allows deleting over time via the job queue
2627 * @return Status Status object; if successful, $status->value is the log_id of the
2628 * deletion log entry. If the page couldn't be deleted because it wasn't
2629 * found, $status is a non-fatal 'cannotdelete' error
2630 * @throws FatalError
2631 * @throws MWException
2632 */
2633 public function doDeleteArticleReal(
2634 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $deleter = null,
2635 $tags = [], $logsubtype = 'delete', $immediate = false
2636 ) {
2637 global $wgUser;
2638
2639 wfDebug( __METHOD__ . "\n" );
2640
2641 $status = Status::newGood();
2642
2643 // Avoid PHP 7.1 warning of passing $this by reference
2644 $wikiPage = $this;
2645
2646 if ( !$deleter ) {
2647 $deleter = $wgUser;
2648 }
2649 if ( !Hooks::run( 'ArticleDelete',
2650 [ &$wikiPage, &$deleter, &$reason, &$error, &$status, $suppress ]
2651 ) ) {
2652 if ( $status->isOK() ) {
2653 // Hook aborted but didn't set a fatal status
2654 $status->fatal( 'delete-hook-aborted' );
2655 }
2656 return $status;
2657 }
2658
2659 return $this->doDeleteArticleBatched( $reason, $suppress, $deleter, $tags,
2660 $logsubtype, $immediate );
2661 }
2662
2663 /**
2664 * Back-end article deletion
2665 *
2666 * Only invokes batching via the job queue if necessary per $wgDeleteRevisionsBatchSize.
2667 * Deletions can often be completed inline without involving the job queue.
2668 *
2669 * Potentially called many times per deletion operation for pages with many revisions.
2670 */
2671 public function doDeleteArticleBatched(
2672 $reason, $suppress, User $deleter, $tags,
2673 $logsubtype, $immediate = false, $webRequestId = null
2674 ) {
2675 wfDebug( __METHOD__ . "\n" );
2676
2677 $status = Status::newGood();
2678
2679 $dbw = wfGetDB( DB_MASTER );
2680 $dbw->startAtomic( __METHOD__ );
2681
2682 $this->loadPageData( self::READ_LATEST );
2683 $id = $this->getId();
2684 // T98706: lock the page from various other updates but avoid using
2685 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2686 // the revisions queries (which also JOIN on user). Only lock the page
2687 // row and CAS check on page_latest to see if the trx snapshot matches.
2688 $lockedLatest = $this->lockAndGetLatest();
2689 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2690 $dbw->endAtomic( __METHOD__ );
2691 // Page not there or trx snapshot is stale
2692 $status->error( 'cannotdelete',
2693 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2694 return $status;
2695 }
2696
2697 // At this point we are now committed to returning an OK
2698 // status unless some DB query error or other exception comes up.
2699 // This way callers don't have to call rollback() if $status is bad
2700 // unless they actually try to catch exceptions (which is rare).
2701
2702 // we need to remember the old content so we can use it to generate all deletion updates.
2703 $revision = $this->getRevision();
2704 try {
2705 $content = $this->getContent( RevisionRecord::RAW );
2706 } catch ( Exception $ex ) {
2707 wfLogWarning( __METHOD__ . ': failed to load content during deletion! '
2708 . $ex->getMessage() );
2709
2710 $content = null;
2711 }
2712
2713 // Archive revisions. In immediate mode, archive all revisions. Otherwise, archive
2714 // one batch of revisions and defer archival of any others to the job queue.
2715 $explictTrxLogged = false;
2716 while ( true ) {
2717 $done = $this->archiveRevisions( $dbw, $id, $suppress );
2718 if ( $done || !$immediate ) {
2719 break;
2720 }
2721 $dbw->endAtomic( __METHOD__ );
2722 if ( $dbw->explicitTrxActive() ) {
2723 // Explict transactions may never happen here in practice. Log to be sure.
2724 if ( !$explictTrxLogged ) {
2725 $explictTrxLogged = true;
2726 LoggerFactory::getInstance( 'wfDebug' )->debug(
2727 'explicit transaction active in ' . __METHOD__ . ' while deleting {title}', [
2728 'title' => $this->getTitle()->getText(),
2729 ] );
2730 }
2731 continue;
2732 }
2733 if ( $dbw->trxLevel() ) {
2734 $dbw->commit();
2735 }
2736 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2737 $lbFactory->waitForReplication();
2738 $dbw->startAtomic( __METHOD__ );
2739 }
2740
2741 // If done archiving, also delete the article.
2742 if ( !$done ) {
2743 $dbw->endAtomic( __METHOD__ );
2744
2745 $jobParams = [
2746 'namespace' => $this->getTitle()->getNamespace(),
2747 'title' => $this->getTitle()->getDBkey(),
2748 'wikiPageId' => $id,
2749 'requestId' => $webRequestId ?? WebRequest::getRequestId(),
2750 'reason' => $reason,
2751 'suppress' => $suppress,
2752 'userId' => $deleter->getId(),
2753 'tags' => json_encode( $tags ),
2754 'logsubtype' => $logsubtype,
2755 ];
2756
2757 $job = new DeletePageJob( $jobParams );
2758 JobQueueGroup::singleton()->push( $job );
2759
2760 $status->warning( 'delete-scheduled',
2761 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2762 } else {
2763 // Get archivedRevisionCount by db query, because there's no better alternative.
2764 // Jobs cannot pass a count of archived revisions to the next job, because additional
2765 // deletion operations can be started while the first is running. Jobs from each
2766 // gracefully interleave, but would not know about each other's count. Deduplication
2767 // in the job queue to avoid simultaneous deletion operations would add overhead.
2768 // Number of archived revisions cannot be known beforehand, because edits can be made
2769 // while deletion operations are being processed, changing the number of archivals.
2770 $archivedRevisionCount = (int)$dbw->selectField(
2771 'archive', 'COUNT(*)',
2772 [
2773 'ar_namespace' => $this->getTitle()->getNamespace(),
2774 'ar_title' => $this->getTitle()->getDBkey(),
2775 'ar_page_id' => $id
2776 ], __METHOD__
2777 );
2778
2779 // Clone the title and wikiPage, so we have the information we need when
2780 // we log and run the ArticleDeleteComplete hook.
2781 $logTitle = clone $this->mTitle;
2782 $wikiPageBeforeDelete = clone $this;
2783
2784 // Now that it's safely backed up, delete it
2785 $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2786
2787 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2788 $logtype = $suppress ? 'suppress' : 'delete';
2789
2790 $logEntry = new ManualLogEntry( $logtype, $logsubtype );
2791 $logEntry->setPerformer( $deleter );
2792 $logEntry->setTarget( $logTitle );
2793 $logEntry->setComment( $reason );
2794 $logEntry->addTags( $tags );
2795 $logid = $logEntry->insert();
2796
2797 $dbw->onTransactionPreCommitOrIdle(
2798 function () use ( $logEntry, $logid ) {
2799 // T58776: avoid deadlocks (especially from FileDeleteForm)
2800 $logEntry->publish( $logid );
2801 },
2802 __METHOD__
2803 );
2804
2805 $dbw->endAtomic( __METHOD__ );
2806
2807 $this->doDeleteUpdates( $id, $content, $revision, $deleter );
2808
2809 Hooks::run( 'ArticleDeleteComplete', [
2810 &$wikiPageBeforeDelete,
2811 &$deleter,
2812 $reason,
2813 $id,
2814 $content,
2815 $logEntry,
2816 $archivedRevisionCount
2817 ] );
2818 $status->value = $logid;
2819
2820 // Show log excerpt on 404 pages rather than just a link
2821 $dbCache = ObjectCache::getInstance( 'db-replicated' );
2822 $key = $dbCache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2823 $dbCache->set( $key, 1, $dbCache::TTL_DAY );
2824 }
2825
2826 return $status;
2827 }
2828
2829 /**
2830 * Archives revisions as part of page deletion.
2831 *
2832 * @param IDatabase $dbw
2833 * @param int $id
2834 * @param bool $suppress Suppress all revisions and log the deletion in
2835 * the suppression log instead of the deletion log
2836 * @return bool
2837 */
2838 protected function archiveRevisions( $dbw, $id, $suppress ) {
2839 global $wgContentHandlerUseDB, $wgMultiContentRevisionSchemaMigrationStage,
2840 $wgActorTableSchemaMigrationStage, $wgDeleteRevisionsBatchSize;
2841
2842 // Given the lock above, we can be confident in the title and page ID values
2843 $namespace = $this->getTitle()->getNamespace();
2844 $dbKey = $this->getTitle()->getDBkey();
2845
2846 $commentStore = CommentStore::getStore();
2847 $actorMigration = ActorMigration::newMigration();
2848
2849 $revQuery = Revision::getQueryInfo();
2850 $bitfield = false;
2851
2852 // Bitfields to further suppress the content
2853 if ( $suppress ) {
2854 $bitfield = RevisionRecord::SUPPRESSED_ALL;
2855 $revQuery['fields'] = array_diff( $revQuery['fields'], [ 'rev_deleted' ] );
2856 }
2857
2858 // For now, shunt the revision data into the archive table.
2859 // Text is *not* removed from the text table; bulk storage
2860 // is left intact to avoid breaking block-compression or
2861 // immutable storage schemes.
2862 // In the future, we may keep revisions and mark them with
2863 // the rev_deleted field, which is reserved for this purpose.
2864
2865 // Lock rows in `revision` and its temp tables, but not any others.
2866 // Note array_intersect() preserves keys from the first arg, and we're
2867 // assuming $revQuery has `revision` primary and isn't using subtables
2868 // for anything we care about.
2869 $dbw->lockForUpdate(
2870 array_intersect(
2871 $revQuery['tables'],
2872 [ 'revision', 'revision_comment_temp', 'revision_actor_temp' ]
2873 ),
2874 [ 'rev_page' => $id ],
2875 __METHOD__,
2876 [],
2877 $revQuery['joins']
2878 );
2879
2880 // If SCHEMA_COMPAT_WRITE_OLD is set, also select all extra fields we still write,
2881 // so we can copy it to the archive table.
2882 // We know the fields exist, otherwise SCHEMA_COMPAT_WRITE_OLD could not function.
2883 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
2884 $revQuery['fields'][] = 'rev_text_id';
2885
2886 if ( $wgContentHandlerUseDB ) {
2887 $revQuery['fields'][] = 'rev_content_model';
2888 $revQuery['fields'][] = 'rev_content_format';
2889 }
2890 }
2891
2892 // Get as many of the page revisions as we are allowed to. The +1 lets us recognize the
2893 // unusual case where there were exactly $wgDeleteRevisionBatchSize revisions remaining.
2894 $res = $dbw->select(
2895 $revQuery['tables'],
2896 $revQuery['fields'],
2897 [ 'rev_page' => $id ],
2898 __METHOD__,
2899 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $wgDeleteRevisionsBatchSize + 1 ],
2900 $revQuery['joins']
2901 );
2902
2903 // Build their equivalent archive rows
2904 $rowsInsert = [];
2905 $revids = [];
2906
2907 /** @var int[] Revision IDs of edits that were made by IPs */
2908 $ipRevIds = [];
2909
2910 $done = true;
2911 foreach ( $res as $row ) {
2912 if ( count( $revids ) >= $wgDeleteRevisionsBatchSize ) {
2913 $done = false;
2914 break;
2915 }
2916
2917 $comment = $commentStore->getComment( 'rev_comment', $row );
2918 $user = User::newFromAnyId( $row->rev_user, $row->rev_user_text, $row->rev_actor );
2919 $rowInsert = [
2920 'ar_namespace' => $namespace,
2921 'ar_title' => $dbKey,
2922 'ar_timestamp' => $row->rev_timestamp,
2923 'ar_minor_edit' => $row->rev_minor_edit,
2924 'ar_rev_id' => $row->rev_id,
2925 'ar_parent_id' => $row->rev_parent_id,
2926 /**
2927 * ar_text_id should probably not be written to when the multi content schema has
2928 * been migrated to (wgMultiContentRevisionSchemaMigrationStage) however there is no
2929 * default for the field in WMF production currently so we must keep writing
2930 * writing until a default of 0 is set.
2931 * Task: https://phabricator.wikimedia.org/T190148
2932 * Copying the value from the revision table should not lead to any issues for now.
2933 */
2934 'ar_len' => $row->rev_len,
2935 'ar_page_id' => $id,
2936 'ar_deleted' => $suppress ? $bitfield : $row->rev_deleted,
2937 'ar_sha1' => $row->rev_sha1,
2938 ] + $commentStore->insert( $dbw, 'ar_comment', $comment )
2939 + $actorMigration->getInsertValues( $dbw, 'ar_user', $user );
2940
2941 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
2942 $rowInsert['ar_text_id'] = $row->rev_text_id;
2943
2944 if ( $wgContentHandlerUseDB ) {
2945 $rowInsert['ar_content_model'] = $row->rev_content_model;
2946 $rowInsert['ar_content_format'] = $row->rev_content_format;
2947 }
2948 }
2949
2950 $rowsInsert[] = $rowInsert;
2951 $revids[] = $row->rev_id;
2952
2953 // Keep track of IP edits, so that the corresponding rows can
2954 // be deleted in the ip_changes table.
2955 if ( (int)$row->rev_user === 0 && IP::isValid( $row->rev_user_text ) ) {
2956 $ipRevIds[] = $row->rev_id;
2957 }
2958 }
2959
2960 // This conditional is just a sanity check
2961 if ( count( $revids ) > 0 ) {
2962 // Copy them into the archive table
2963 $dbw->insert( 'archive', $rowsInsert, __METHOD__ );
2964
2965 $dbw->delete( 'revision', [ 'rev_id' => $revids ], __METHOD__ );
2966 $dbw->delete( 'revision_comment_temp', [ 'revcomment_rev' => $revids ], __METHOD__ );
2967 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
2968 $dbw->delete( 'revision_actor_temp', [ 'revactor_rev' => $revids ], __METHOD__ );
2969 }
2970
2971 // Also delete records from ip_changes as applicable.
2972 if ( count( $ipRevIds ) > 0 ) {
2973 $dbw->delete( 'ip_changes', [ 'ipc_rev_id' => $ipRevIds ], __METHOD__ );
2974 }
2975 }
2976
2977 return $done;
2978 }
2979
2980 /**
2981 * Lock the page row for this title+id and return page_latest (or 0)
2982 *
2983 * @return int Returns 0 if no row was found with this title+id
2984 * @since 1.27
2985 */
2986 public function lockAndGetLatest() {
2987 return (int)wfGetDB( DB_MASTER )->selectField(
2988 'page',
2989 'page_latest',
2990 [
2991 'page_id' => $this->getId(),
2992 // Typically page_id is enough, but some code might try to do
2993 // updates assuming the title is the same, so verify that
2994 'page_namespace' => $this->getTitle()->getNamespace(),
2995 'page_title' => $this->getTitle()->getDBkey()
2996 ],
2997 __METHOD__,
2998 [ 'FOR UPDATE' ]
2999 );
3000 }
3001
3002 /**
3003 * Do some database updates after deletion
3004 *
3005 * @param int $id The page_id value of the page being deleted
3006 * @param Content|null $content Page content to be used when determining
3007 * the required updates. This may be needed because $this->getContent()
3008 * may already return null when the page proper was deleted.
3009 * @param Revision|null $revision The current page revision at the time of
3010 * deletion, used when determining the required updates. This may be needed because
3011 * $this->getRevision() may already return null when the page proper was deleted.
3012 * @param User|null $user The user that caused the deletion
3013 */
3014 public function doDeleteUpdates(
3015 $id, Content $content = null, Revision $revision = null, User $user = null
3016 ) {
3017 if ( $id !== $this->getId() ) {
3018 throw new InvalidArgumentException( 'Mismatching page ID' );
3019 }
3020
3021 try {
3022 $countable = $this->isCountable();
3023 } catch ( Exception $ex ) {
3024 // fallback for deleting broken pages for which we cannot load the content for
3025 // some reason. Note that doDeleteArticleReal() already logged this problem.
3026 $countable = false;
3027 }
3028
3029 // Update site status
3030 DeferredUpdates::addUpdate( SiteStatsUpdate::factory(
3031 [ 'edits' => 1, 'articles' => -$countable, 'pages' => -1 ]
3032 ) );
3033
3034 // Delete pagelinks, update secondary indexes, etc
3035 $updates = $this->getDeletionUpdates(
3036 $revision ? $revision->getRevisionRecord() : $content
3037 );
3038 foreach ( $updates as $update ) {
3039 DeferredUpdates::addUpdate( $update );
3040 }
3041
3042 $causeAgent = $user ? $user->getName() : 'unknown';
3043 // Reparse any pages transcluding this page
3044 LinksUpdate::queueRecursiveJobsForTable(
3045 $this->mTitle, 'templatelinks', 'delete-page', $causeAgent );
3046 // Reparse any pages including this image
3047 if ( $this->mTitle->getNamespace() == NS_FILE ) {
3048 LinksUpdate::queueRecursiveJobsForTable(
3049 $this->mTitle, 'imagelinks', 'delete-page', $causeAgent );
3050 }
3051
3052 // Clear caches
3053 self::onArticleDelete( $this->mTitle );
3054 ResourceLoaderWikiModule::invalidateModuleCache(
3055 $this->mTitle,
3056 $revision,
3057 null,
3058 WikiMap::getCurrentWikiDbDomain()->getId()
3059 );
3060
3061 // Reset this object and the Title object
3062 $this->loadFromRow( false, self::READ_LATEST );
3063
3064 // Search engine
3065 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3066 }
3067
3068 /**
3069 * Roll back the most recent consecutive set of edits to a page
3070 * from the same user; fails if there are no eligible edits to
3071 * roll back to, e.g. user is the sole contributor. This function
3072 * performs permissions checks on $user, then calls commitRollback()
3073 * to do the dirty work
3074 *
3075 * @todo Separate the business/permission stuff out from backend code
3076 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3077 *
3078 * @param string $fromP Name of the user whose edits to rollback.
3079 * @param string $summary Custom summary. Set to default summary if empty.
3080 * @param string $token Rollback token.
3081 * @param bool $bot If true, mark all reverted edits as bot.
3082 *
3083 * @param array &$resultDetails Array contains result-specific array of additional values
3084 * 'alreadyrolled' : 'current' (rev)
3085 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3086 *
3087 * @param User $user The user performing the rollback
3088 * @param array|null $tags Change tags to apply to the rollback
3089 * Callers are responsible for permission checks
3090 * (with ChangeTags::canAddTagsAccompanyingChange)
3091 *
3092 * @return array Array of errors, each error formatted as
3093 * [ messagekey, param1, param2, ... ].
3094 * On success, the array is empty. This array can also be passed to
3095 * OutputPage::showPermissionsErrorPage().
3096 */
3097 public function doRollback(
3098 $fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3099 ) {
3100 $resultDetails = null;
3101
3102 // Check permissions
3103 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3104 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3105 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3106
3107 if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3108 $errors[] = [ 'sessionfailure' ];
3109 }
3110
3111 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3112 $errors[] = [ 'actionthrottledtext' ];
3113 }
3114
3115 // If there were errors, bail out now
3116 if ( !empty( $errors ) ) {
3117 return $errors;
3118 }
3119
3120 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3121 }
3122
3123 /**
3124 * Backend implementation of doRollback(), please refer there for parameter
3125 * and return value documentation
3126 *
3127 * NOTE: This function does NOT check ANY permissions, it just commits the
3128 * rollback to the DB. Therefore, you should only call this function direct-
3129 * ly if you want to use custom permissions checks. If you don't, use
3130 * doRollback() instead.
3131 * @param string $fromP Name of the user whose edits to rollback.
3132 * @param string $summary Custom summary. Set to default summary if empty.
3133 * @param bool $bot If true, mark all reverted edits as bot.
3134 *
3135 * @param array &$resultDetails Contains result-specific array of additional values
3136 * @param User $guser The user performing the rollback
3137 * @param array|null $tags Change tags to apply to the rollback
3138 * Callers are responsible for permission checks
3139 * (with ChangeTags::canAddTagsAccompanyingChange)
3140 *
3141 * @return array An array of error messages, as returned by Status::getErrorsArray()
3142 */
3143 public function commitRollback( $fromP, $summary, $bot,
3144 &$resultDetails, User $guser, $tags = null
3145 ) {
3146 global $wgUseRCPatrol;
3147
3148 $dbw = wfGetDB( DB_MASTER );
3149
3150 if ( wfReadOnly() ) {
3151 return [ [ 'readonlytext' ] ];
3152 }
3153
3154 // Begin revision creation cycle by creating a PageUpdater.
3155 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
3156 $updater = $this->newPageUpdater( $guser );
3157 $current = $updater->grabParentRevision();
3158
3159 if ( is_null( $current ) ) {
3160 // Something wrong... no page?
3161 return [ [ 'notanarticle' ] ];
3162 }
3163
3164 $currentEditorForPublic = $current->getUser( RevisionRecord::FOR_PUBLIC );
3165 $legacyCurrent = new Revision( $current );
3166 $from = str_replace( '_', ' ', $fromP );
3167
3168 // User name given should match up with the top revision.
3169 // If the revision's user is not visible, then $from should be empty.
3170 if ( $from !== ( $currentEditorForPublic ? $currentEditorForPublic->getName() : '' ) ) {
3171 $resultDetails = [ 'current' => $legacyCurrent ];
3172 return [ [ 'alreadyrolled',
3173 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3174 htmlspecialchars( $fromP ),
3175 htmlspecialchars( $currentEditorForPublic ? $currentEditorForPublic->getName() : '' )
3176 ] ];
3177 }
3178
3179 // Get the last edit not by this person...
3180 // Note: these may not be public values
3181 $actorWhere = ActorMigration::newMigration()->getWhere(
3182 $dbw,
3183 'rev_user',
3184 $current->getUser( RevisionRecord::RAW )
3185 );
3186
3187 $s = $dbw->selectRow(
3188 [ 'revision' ] + $actorWhere['tables'],
3189 [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3190 [
3191 'rev_page' => $current->getPageId(),
3192 'NOT(' . $actorWhere['conds'] . ')',
3193 ],
3194 __METHOD__,
3195 [
3196 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
3197 'ORDER BY' => 'rev_timestamp DESC'
3198 ],
3199 $actorWhere['joins']
3200 );
3201 if ( $s === false ) {
3202 // No one else ever edited this page
3203 return [ [ 'cantrollback' ] ];
3204 } elseif ( $s->rev_deleted & RevisionRecord::DELETED_TEXT
3205 || $s->rev_deleted & RevisionRecord::DELETED_USER
3206 ) {
3207 // Only admins can see this text
3208 return [ [ 'notvisiblerev' ] ];
3209 }
3210
3211 // Generate the edit summary if necessary
3212 $target = $this->getRevisionStore()->getRevisionById(
3213 $s->rev_id,
3214 RevisionStore::READ_LATEST
3215 );
3216 if ( empty( $summary ) ) {
3217 if ( !$currentEditorForPublic ) { // no public user name
3218 $summary = wfMessage( 'revertpage-nouser' );
3219 } else {
3220 $summary = wfMessage( 'revertpage' );
3221 }
3222 }
3223 $legacyTarget = new Revision( $target );
3224 $targetEditorForPublic = $target->getUser( RevisionRecord::FOR_PUBLIC );
3225
3226 // Allow the custom summary to use the same args as the default message
3227 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
3228 $args = [
3229 $targetEditorForPublic ? $targetEditorForPublic->getName() : null,
3230 $currentEditorForPublic ? $currentEditorForPublic->getName() : null,
3231 $s->rev_id,
3232 $contLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3233 $current->getId(),
3234 $contLang->timeanddate( $current->getTimestamp() )
3235 ];
3236 if ( $summary instanceof Message ) {
3237 $summary = $summary->params( $args )->inContentLanguage()->text();
3238 } else {
3239 $summary = wfMsgReplaceArgs( $summary, $args );
3240 }
3241
3242 // Trim spaces on user supplied text
3243 $summary = trim( $summary );
3244
3245 // Save
3246 $flags = EDIT_UPDATE | EDIT_INTERNAL;
3247
3248 if ( $guser->isAllowed( 'minoredit' ) ) {
3249 $flags |= EDIT_MINOR;
3250 }
3251
3252 if ( $bot && ( MediaWikiServices::getInstance()
3253 ->getPermissionManager()
3254 ->userHasAnyRight( $guser, 'markbotedits', 'bot' ) )
3255 ) {
3256 $flags |= EDIT_FORCE_BOT;
3257 }
3258
3259 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
3260 $currentContent = $current->getContent( SlotRecord::MAIN );
3261 $targetContent = $target->getContent( SlotRecord::MAIN );
3262 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
3263
3264 if ( in_array( 'mw-rollback', ChangeTags::getSoftwareTags() ) ) {
3265 $tags[] = 'mw-rollback';
3266 }
3267
3268 // Build rollback revision:
3269 // Restore old content
3270 // TODO: MCR: test this once we can store multiple slots
3271 foreach ( $target->getSlots()->getSlots() as $slot ) {
3272 $updater->inheritSlot( $slot );
3273 }
3274
3275 // Remove extra slots
3276 // TODO: MCR: test this once we can store multiple slots
3277 foreach ( $current->getSlotRoles() as $role ) {
3278 if ( !$target->hasSlot( $role ) ) {
3279 $updater->removeSlot( $role );
3280 }
3281 }
3282
3283 $updater->setOriginalRevisionId( $target->getId() );
3284 // Do not call setUndidRevisionId(), that causes an extra "mw-undo" tag to be added (T190374)
3285 $updater->addTags( $tags );
3286
3287 // TODO: this logic should not be in the storage layer, it's here for compatibility
3288 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
3289 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
3290 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
3291
3292 if ( $wgUseRCPatrol && $permissionManager->userCan(
3293 'autopatrol', $guser, $this->getTitle()
3294 ) ) {
3295 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
3296 }
3297
3298 // Actually store the rollback
3299 $rev = $updater->saveRevision(
3300 CommentStoreComment::newUnsavedComment( $summary ),
3301 $flags
3302 );
3303
3304 // Set patrolling and bot flag on the edits, which gets rollbacked.
3305 // This is done even on edit failure to have patrolling in that case (T64157).
3306 $set = [];
3307 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3308 // Mark all reverted edits as bot
3309 $set['rc_bot'] = 1;
3310 }
3311
3312 if ( $wgUseRCPatrol ) {
3313 // Mark all reverted edits as patrolled
3314 $set['rc_patrolled'] = RecentChange::PRC_AUTOPATROLLED;
3315 }
3316
3317 if ( count( $set ) ) {
3318 $actorWhere = ActorMigration::newMigration()->getWhere(
3319 $dbw,
3320 'rc_user',
3321 $current->getUser( RevisionRecord::RAW ),
3322 false
3323 );
3324 $dbw->update( 'recentchanges', $set,
3325 [ /* WHERE */
3326 'rc_cur_id' => $current->getPageId(),
3327 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3328 $actorWhere['conds'], // No tables/joins are needed for rc_user
3329 ],
3330 __METHOD__
3331 );
3332 }
3333
3334 if ( !$updater->wasSuccessful() ) {
3335 return $updater->getStatus()->getErrorsArray();
3336 }
3337
3338 // Report if the edit was not created because it did not change the content.
3339 if ( $updater->isUnchanged() ) {
3340 $resultDetails = [ 'current' => $legacyCurrent ];
3341 return [ [ 'alreadyrolled',
3342 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3343 htmlspecialchars( $fromP ),
3344 htmlspecialchars( $currentEditorForPublic ? $currentEditorForPublic->getName() : '' )
3345 ] ];
3346 }
3347
3348 if ( $changingContentModel ) {
3349 // If the content model changed during the rollback,
3350 // make sure it gets logged to Special:Log/contentmodel
3351 $log = new ManualLogEntry( 'contentmodel', 'change' );
3352 $log->setPerformer( $guser );
3353 $log->setTarget( $this->mTitle );
3354 $log->setComment( $summary );
3355 $log->setParameters( [
3356 '4::oldmodel' => $currentContent->getModel(),
3357 '5::newmodel' => $targetContent->getModel(),
3358 ] );
3359
3360 $logId = $log->insert( $dbw );
3361 $log->publish( $logId );
3362 }
3363
3364 $revId = $rev->getId();
3365
3366 Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $legacyTarget, $legacyCurrent ] );
3367
3368 $resultDetails = [
3369 'summary' => $summary,
3370 'current' => $legacyCurrent,
3371 'target' => $legacyTarget,
3372 'newid' => $revId,
3373 'tags' => $tags
3374 ];
3375
3376 // TODO: make this return a Status object and wrap $resultDetails in that.
3377 return [];
3378 }
3379
3380 /**
3381 * The onArticle*() functions are supposed to be a kind of hooks
3382 * which should be called whenever any of the specified actions
3383 * are done.
3384 *
3385 * This is a good place to put code to clear caches, for instance.
3386 *
3387 * This is called on page move and undelete, as well as edit
3388 *
3389 * @param Title $title
3390 */
3391 public static function onArticleCreate( Title $title ) {
3392 // TODO: move this into a PageEventEmitter service
3393
3394 // Update existence markers on article/talk tabs...
3395 $other = $title->getOtherPage();
3396
3397 $other->purgeSquid();
3398
3399 $title->touchLinks();
3400 $title->purgeSquid();
3401 $title->deleteTitleProtection();
3402
3403 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3404
3405 // Invalidate caches of articles which include this page
3406 DeferredUpdates::addUpdate(
3407 new HTMLCacheUpdate( $title, 'templatelinks', 'page-create' )
3408 );
3409
3410 if ( $title->getNamespace() == NS_CATEGORY ) {
3411 // Load the Category object, which will schedule a job to create
3412 // the category table row if necessary. Checking a replica DB is ok
3413 // here, in the worst case it'll run an unnecessary recount job on
3414 // a category that probably doesn't have many members.
3415 Category::newFromTitle( $title )->getID();
3416 }
3417 }
3418
3419 /**
3420 * Clears caches when article is deleted
3421 *
3422 * @param Title $title
3423 */
3424 public static function onArticleDelete( Title $title ) {
3425 // TODO: move this into a PageEventEmitter service
3426
3427 // Update existence markers on article/talk tabs...
3428 // Clear Backlink cache first so that purge jobs use more up-to-date backlink information
3429 BacklinkCache::get( $title )->clear();
3430 $other = $title->getOtherPage();
3431
3432 $other->purgeSquid();
3433
3434 $title->touchLinks();
3435 $title->purgeSquid();
3436
3437 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3438
3439 // File cache
3440 HTMLFileCache::clearFileCache( $title );
3441 InfoAction::invalidateCache( $title );
3442
3443 // Messages
3444 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3445 MessageCache::singleton()->updateMessageOverride( $title, null );
3446 }
3447
3448 // Images
3449 if ( $title->getNamespace() == NS_FILE ) {
3450 DeferredUpdates::addUpdate(
3451 new HTMLCacheUpdate( $title, 'imagelinks', 'page-delete' )
3452 );
3453 }
3454
3455 // User talk pages
3456 if ( $title->getNamespace() == NS_USER_TALK ) {
3457 $user = User::newFromName( $title->getText(), false );
3458 if ( $user ) {
3459 $user->setNewtalk( false );
3460 }
3461 }
3462
3463 // Image redirects
3464 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3465
3466 // Purge cross-wiki cache entities referencing this page
3467 self::purgeInterwikiCheckKey( $title );
3468 }
3469
3470 /**
3471 * Purge caches on page update etc
3472 *
3473 * @param Title $title
3474 * @param Revision|null $revision Revision that was just saved, may be null
3475 * @param string[]|null $slotsChanged The role names of the slots that were changed.
3476 * If not given, all slots are assumed to have changed.
3477 */
3478 public static function onArticleEdit(
3479 Title $title,
3480 Revision $revision = null,
3481 $slotsChanged = null
3482 ) {
3483 // TODO: move this into a PageEventEmitter service
3484
3485 if ( $slotsChanged === null || in_array( SlotRecord::MAIN, $slotsChanged ) ) {
3486 // Invalidate caches of articles which include this page.
3487 // Only for the main slot, because only the main slot is transcluded.
3488 // TODO: MCR: not true for TemplateStyles! [SlotHandler]
3489 DeferredUpdates::addUpdate(
3490 new HTMLCacheUpdate( $title, 'templatelinks', 'page-edit' )
3491 );
3492 }
3493
3494 // Invalidate the caches of all pages which redirect here
3495 DeferredUpdates::addUpdate(
3496 new HTMLCacheUpdate( $title, 'redirect', 'page-edit' )
3497 );
3498
3499 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $title );
3500
3501 // Purge CDN for this page only
3502 $title->purgeSquid();
3503 // Clear file cache for this page only
3504 HTMLFileCache::clearFileCache( $title );
3505
3506 // Purge ?action=info cache
3507 $revid = $revision ? $revision->getId() : null;
3508 DeferredUpdates::addCallableUpdate( function () use ( $title, $revid ) {
3509 InfoAction::invalidateCache( $title, $revid );
3510 } );
3511
3512 // Purge cross-wiki cache entities referencing this page
3513 self::purgeInterwikiCheckKey( $title );
3514 }
3515
3516 /** #@- */
3517
3518 /**
3519 * Purge the check key for cross-wiki cache entries referencing this page
3520 *
3521 * @param Title $title
3522 */
3523 private static function purgeInterwikiCheckKey( Title $title ) {
3524 global $wgEnableScaryTranscluding;
3525
3526 if ( !$wgEnableScaryTranscluding ) {
3527 return; // @todo: perhaps this wiki is only used as a *source* for content?
3528 }
3529
3530 DeferredUpdates::addCallableUpdate( function () use ( $title ) {
3531 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
3532 $cache->resetCheckKey(
3533 // Do not include the namespace since there can be multiple aliases to it
3534 // due to different namespace text definitions on different wikis. This only
3535 // means that some cache invalidations happen that are not strictly needed.
3536 $cache->makeGlobalKey(
3537 'interwiki-page',
3538 WikiMap::getCurrentWikiDbDomain()->getId(),
3539 $title->getDBkey()
3540 )
3541 );
3542 } );
3543 }
3544
3545 /**
3546 * Returns a list of categories this page is a member of.
3547 * Results will include hidden categories
3548 *
3549 * @return TitleArray
3550 */
3551 public function getCategories() {
3552 $id = $this->getId();
3553 if ( $id == 0 ) {
3554 return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3555 }
3556
3557 $dbr = wfGetDB( DB_REPLICA );
3558 $res = $dbr->select( 'categorylinks',
3559 [ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3560 // Have to do that since Database::fieldNamesWithAlias treats numeric indexes
3561 // as not being aliases, and NS_CATEGORY is numeric
3562 [ 'cl_from' => $id ],
3563 __METHOD__ );
3564
3565 return TitleArray::newFromResult( $res );
3566 }
3567
3568 /**
3569 * Returns a list of hidden categories this page is a member of.
3570 * Uses the page_props and categorylinks tables.
3571 *
3572 * @return array Array of Title objects
3573 */
3574 public function getHiddenCategories() {
3575 $result = [];
3576 $id = $this->getId();
3577
3578 if ( $id == 0 ) {
3579 return [];
3580 }
3581
3582 $dbr = wfGetDB( DB_REPLICA );
3583 $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3584 [ 'cl_to' ],
3585 [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3586 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3587 __METHOD__ );
3588
3589 if ( $res !== false ) {
3590 foreach ( $res as $row ) {
3591 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3592 }
3593 }
3594
3595 return $result;
3596 }
3597
3598 /**
3599 * Auto-generates a deletion reason
3600 *
3601 * @param bool &$hasHistory Whether the page has a history
3602 * @return string|bool String containing deletion reason or empty string, or boolean false
3603 * if no revision occurred
3604 */
3605 public function getAutoDeleteReason( &$hasHistory ) {
3606 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3607 }
3608
3609 /**
3610 * Update all the appropriate counts in the category table, given that
3611 * we've added the categories $added and deleted the categories $deleted.
3612 *
3613 * This should only be called from deferred updates or jobs to avoid contention.
3614 *
3615 * @param array $added The names of categories that were added
3616 * @param array $deleted The names of categories that were deleted
3617 * @param int $id Page ID (this should be the original deleted page ID)
3618 */
3619 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3620 $id = $id ?: $this->getId();
3621 $type = MediaWikiServices::getInstance()->getNamespaceInfo()->
3622 getCategoryLinkType( $this->getTitle()->getNamespace() );
3623
3624 $addFields = [ 'cat_pages = cat_pages + 1' ];
3625 $removeFields = [ 'cat_pages = cat_pages - 1' ];
3626 if ( $type !== 'page' ) {
3627 $addFields[] = "cat_{$type}s = cat_{$type}s + 1";
3628 $removeFields[] = "cat_{$type}s = cat_{$type}s - 1";
3629 }
3630
3631 $dbw = wfGetDB( DB_MASTER );
3632
3633 if ( count( $added ) ) {
3634 $existingAdded = $dbw->selectFieldValues(
3635 'category',
3636 'cat_title',
3637 [ 'cat_title' => $added ],
3638 __METHOD__
3639 );
3640
3641 // For category rows that already exist, do a plain
3642 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3643 // to avoid creating gaps in the cat_id sequence.
3644 if ( count( $existingAdded ) ) {
3645 $dbw->update(
3646 'category',
3647 $addFields,
3648 [ 'cat_title' => $existingAdded ],
3649 __METHOD__
3650 );
3651 }
3652
3653 $missingAdded = array_diff( $added, $existingAdded );
3654 if ( count( $missingAdded ) ) {
3655 $insertRows = [];
3656 foreach ( $missingAdded as $cat ) {
3657 $insertRows[] = [
3658 'cat_title' => $cat,
3659 'cat_pages' => 1,
3660 'cat_subcats' => ( $type === 'subcat' ) ? 1 : 0,
3661 'cat_files' => ( $type === 'file' ) ? 1 : 0,
3662 ];
3663 }
3664 $dbw->upsert(
3665 'category',
3666 $insertRows,
3667 [ 'cat_title' ],
3668 $addFields,
3669 __METHOD__
3670 );
3671 }
3672 }
3673
3674 if ( count( $deleted ) ) {
3675 $dbw->update(
3676 'category',
3677 $removeFields,
3678 [ 'cat_title' => $deleted ],
3679 __METHOD__
3680 );
3681 }
3682
3683 foreach ( $added as $catName ) {
3684 $cat = Category::newFromName( $catName );
3685 Hooks::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3686 }
3687
3688 foreach ( $deleted as $catName ) {
3689 $cat = Category::newFromName( $catName );
3690 Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3691 // Refresh counts on categories that should be empty now (after commit, T166757)
3692 DeferredUpdates::addCallableUpdate( function () use ( $cat ) {
3693 $cat->refreshCountsIfEmpty();
3694 } );
3695 }
3696 }
3697
3698 /**
3699 * Opportunistically enqueue link update jobs given fresh parser output if useful
3700 *
3701 * @param ParserOutput $parserOutput Current version page output
3702 * @since 1.25
3703 */
3704 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3705 if ( wfReadOnly() ) {
3706 return;
3707 }
3708
3709 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3710 [ $this, $this->mTitle, $parserOutput ]
3711 ) ) {
3712 return;
3713 }
3714
3715 $config = RequestContext::getMain()->getConfig();
3716
3717 $params = [
3718 'isOpportunistic' => true,
3719 'rootJobTimestamp' => $parserOutput->getCacheTime()
3720 ];
3721
3722 if ( $this->mTitle->areRestrictionsCascading() ) {
3723 // If the page is cascade protecting, the links should really be up-to-date
3724 JobQueueGroup::singleton()->lazyPush(
3725 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3726 );
3727 } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3728 // Assume the output contains "dynamic" time/random based magic words.
3729 // Only update pages that expired due to dynamic content and NOT due to edits
3730 // to referenced templates/files. When the cache expires due to dynamic content,
3731 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3732 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3733 // template/file edit already triggered recursive RefreshLinksJob jobs.
3734 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3735 // If a page is uncacheable, do not keep spamming a job for it.
3736 // Although it would be de-duplicated, it would still waste I/O.
3737 $cache = ObjectCache::getLocalClusterInstance();
3738 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3739 $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3740 if ( $cache->add( $key, time(), $ttl ) ) {
3741 JobQueueGroup::singleton()->lazyPush(
3742 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3743 );
3744 }
3745 }
3746 }
3747 }
3748
3749 /**
3750 * Returns a list of updates to be performed when this page is deleted. The
3751 * updates should remove any information about this page from secondary data
3752 * stores such as links tables.
3753 *
3754 * @param RevisionRecord|Content|null $rev The revision being deleted. Also accepts a Content
3755 * object for backwards compatibility.
3756 * @return DeferrableUpdate[]
3757 */
3758 public function getDeletionUpdates( $rev = null ) {
3759 if ( !$rev ) {
3760 wfDeprecated( __METHOD__ . ' without a RevisionRecord', '1.32' );
3761
3762 try {
3763 $rev = $this->getRevisionRecord();
3764 } catch ( Exception $ex ) {
3765 // If we can't load the content, something is wrong. Perhaps that's why
3766 // the user is trying to delete the page, so let's not fail in that case.
3767 // Note that doDeleteArticleReal() will already have logged an issue with
3768 // loading the content.
3769 wfDebug( __METHOD__ . ' failed to load current revision of page ' . $this->getId() );
3770 }
3771 }
3772
3773 if ( !$rev ) {
3774 $slotContent = [];
3775 } elseif ( $rev instanceof Content ) {
3776 wfDeprecated( __METHOD__ . ' with a Content object instead of a RevisionRecord', '1.32' );
3777
3778 $slotContent = [ SlotRecord::MAIN => $rev ];
3779 } else {
3780 $slotContent = array_map( function ( SlotRecord $slot ) {
3781 return $slot->getContent( RevisionRecord::RAW );
3782 }, $rev->getSlots()->getSlots() );
3783 }
3784
3785 $allUpdates = [ new LinksDeletionUpdate( $this ) ];
3786
3787 // NOTE: once Content::getDeletionUpdates() is removed, we only need to content
3788 // model here, not the content object!
3789 // TODO: consolidate with similar logic in DerivedPageDataUpdater::getSecondaryDataUpdates()
3790 /** @var Content $content */
3791 foreach ( $slotContent as $role => $content ) {
3792 $handler = $content->getContentHandler();
3793
3794 $updates = $handler->getDeletionUpdates(
3795 $this->getTitle(),
3796 $role
3797 );
3798 $allUpdates = array_merge( $allUpdates, $updates );
3799
3800 // TODO: remove B/C hack in 1.32!
3801 $legacyUpdates = $content->getDeletionUpdates( $this );
3802
3803 // HACK: filter out redundant and incomplete LinksDeletionUpdate
3804 $legacyUpdates = array_filter( $legacyUpdates, function ( $update ) {
3805 return !( $update instanceof LinksDeletionUpdate );
3806 } );
3807
3808 $allUpdates = array_merge( $allUpdates, $legacyUpdates );
3809 }
3810
3811 Hooks::run( 'PageDeletionDataUpdates', [ $this->getTitle(), $rev, &$allUpdates ] );
3812
3813 // TODO: hard deprecate old hook in 1.33
3814 Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$allUpdates ] );
3815 return $allUpdates;
3816 }
3817
3818 /**
3819 * Whether this content displayed on this page
3820 * comes from the local database
3821 *
3822 * @since 1.28
3823 * @return bool
3824 */
3825 public function isLocal() {
3826 return true;
3827 }
3828
3829 /**
3830 * The display name for the site this content
3831 * come from. If a subclass overrides isLocal(),
3832 * this could return something other than the
3833 * current site name
3834 *
3835 * @since 1.28
3836 * @return string
3837 */
3838 public function getWikiDisplayName() {
3839 global $wgSitename;
3840 return $wgSitename;
3841 }
3842
3843 /**
3844 * Get the source URL for the content on this page,
3845 * typically the canonical URL, but may be a remote
3846 * link if the content comes from another site
3847 *
3848 * @since 1.28
3849 * @return string
3850 */
3851 public function getSourceURL() {
3852 return $this->getTitle()->getCanonicalURL();
3853 }
3854
3855 /**
3856 * @param WANObjectCache $cache
3857 * @return string[]
3858 * @since 1.28
3859 */
3860 public function getMutableCacheKeys( WANObjectCache $cache ) {
3861 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3862
3863 return $linkCache->getMutableCacheKeys( $cache, $this->getTitle() );
3864 }
3865
3866 }