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