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