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