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