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