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