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