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