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