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