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