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