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