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