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