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