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