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