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