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