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