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