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