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