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