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