WikiPage::prepareTextForEdit() was removed
[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 Hooks::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
320
321 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
322
323 Hooks::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
324
325 return $row;
326 }
327
328 /**
329 * Fetch a page record matching the Title object's namespace and title
330 * using a sanitized title string
331 *
332 * @param IDatabase $dbr
333 * @param Title $title
334 * @param array $options
335 * @return object|bool Database result resource, or false on failure
336 */
337 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
338 return $this->pageData( $dbr, [
339 'page_namespace' => $title->getNamespace(),
340 'page_title' => $title->getDBkey() ], $options );
341 }
342
343 /**
344 * Fetch a page record matching the requested ID
345 *
346 * @param IDatabase $dbr
347 * @param int $id
348 * @param array $options
349 * @return object|bool Database result resource, or false on failure
350 */
351 public function pageDataFromId( $dbr, $id, $options = [] ) {
352 return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
353 }
354
355 /**
356 * Load the object from a given source by title
357 *
358 * @param object|string|int $from One of the following:
359 * - A DB query result object.
360 * - "fromdb" or WikiPage::READ_NORMAL to get from a replica DB.
361 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
362 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
363 * using SELECT FOR UPDATE.
364 *
365 * @return void
366 */
367 public function loadPageData( $from = 'fromdb' ) {
368 $from = self::convertSelectType( $from );
369 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
370 // We already have the data from the correct location, no need to load it twice.
371 return;
372 }
373
374 if ( is_int( $from ) ) {
375 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
376 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
377
378 if ( !$data
379 && $index == DB_REPLICA
380 && wfGetLB()->getServerCount() > 1
381 && wfGetLB()->hasOrMadeRecentMasterChanges()
382 ) {
383 $from = self::READ_LATEST;
384 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
385 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
386 }
387 } else {
388 // No idea from where the caller got this data, assume replica DB.
389 $data = $from;
390 $from = self::READ_NORMAL;
391 }
392
393 $this->loadFromRow( $data, $from );
394 }
395
396 /**
397 * Load the object from a database row
398 *
399 * @since 1.20
400 * @param object|bool $data DB row containing fields returned by selectFields() or false
401 * @param string|int $from One of the following:
402 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a replica DB
403 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
404 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
405 * the master DB using SELECT FOR UPDATE
406 */
407 public function loadFromRow( $data, $from ) {
408 $lc = LinkCache::singleton();
409 $lc->clearLink( $this->mTitle );
410
411 if ( $data ) {
412 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
413
414 $this->mTitle->loadFromRow( $data );
415
416 // Old-fashioned restrictions
417 $this->mTitle->loadRestrictions( $data->page_restrictions );
418
419 $this->mId = intval( $data->page_id );
420 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
421 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
422 $this->mIsRedirect = intval( $data->page_is_redirect );
423 $this->mLatest = intval( $data->page_latest );
424 // Bug 37225: $latest may no longer match the cached latest Revision object.
425 // Double-check the ID of any cached latest Revision object for consistency.
426 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
427 $this->mLastRevision = null;
428 $this->mTimestamp = '';
429 }
430 } else {
431 $lc->addBadLinkObj( $this->mTitle );
432
433 $this->mTitle->loadFromRow( false );
434
435 $this->clearCacheFields();
436
437 $this->mId = 0;
438 }
439
440 $this->mDataLoaded = true;
441 $this->mDataLoadedFrom = self::convertSelectType( $from );
442 }
443
444 /**
445 * @return int Page ID
446 */
447 public function getId() {
448 if ( !$this->mDataLoaded ) {
449 $this->loadPageData();
450 }
451 return $this->mId;
452 }
453
454 /**
455 * @return bool Whether or not the page exists in the database
456 */
457 public function exists() {
458 if ( !$this->mDataLoaded ) {
459 $this->loadPageData();
460 }
461 return $this->mId > 0;
462 }
463
464 /**
465 * Check if this page is something we're going to be showing
466 * some sort of sensible content for. If we return false, page
467 * views (plain action=view) will return an HTTP 404 response,
468 * so spiders and robots can know they're following a bad link.
469 *
470 * @return bool
471 */
472 public function hasViewableContent() {
473 return $this->mTitle->isKnown();
474 }
475
476 /**
477 * Tests if the article content represents a redirect
478 *
479 * @return bool
480 */
481 public function isRedirect() {
482 if ( !$this->mDataLoaded ) {
483 $this->loadPageData();
484 }
485
486 return (bool)$this->mIsRedirect;
487 }
488
489 /**
490 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
491 *
492 * Will use the revisions actual content model if the page exists,
493 * and the page's default if the page doesn't exist yet.
494 *
495 * @return string
496 *
497 * @since 1.21
498 */
499 public function getContentModel() {
500 if ( $this->exists() ) {
501 $cache = ObjectCache::getMainWANInstance();
502
503 return $cache->getWithSetCallback(
504 $cache->makeKey( 'page', 'content-model', $this->getLatest() ),
505 $cache::TTL_MONTH,
506 function () {
507 $rev = $this->getRevision();
508 if ( $rev ) {
509 // Look at the revision's actual content model
510 return $rev->getContentModel();
511 } else {
512 $title = $this->mTitle->getPrefixedDBkey();
513 wfWarn( "Page $title exists but has no (visible) revisions!" );
514 return $this->mTitle->getContentModel();
515 }
516 }
517 );
518 }
519
520 // use the default model for this page
521 return $this->mTitle->getContentModel();
522 }
523
524 /**
525 * Loads page_touched and returns a value indicating if it should be used
526 * @return bool True if this page exists and is not a redirect
527 */
528 public function checkTouched() {
529 if ( !$this->mDataLoaded ) {
530 $this->loadPageData();
531 }
532 return ( $this->mId && !$this->mIsRedirect );
533 }
534
535 /**
536 * Get the page_touched field
537 * @return string Containing GMT timestamp
538 */
539 public function getTouched() {
540 if ( !$this->mDataLoaded ) {
541 $this->loadPageData();
542 }
543 return $this->mTouched;
544 }
545
546 /**
547 * Get the page_links_updated field
548 * @return string|null Containing GMT timestamp
549 */
550 public function getLinksTimestamp() {
551 if ( !$this->mDataLoaded ) {
552 $this->loadPageData();
553 }
554 return $this->mLinksUpdated;
555 }
556
557 /**
558 * Get the page_latest field
559 * @return int The rev_id of current revision
560 */
561 public function getLatest() {
562 if ( !$this->mDataLoaded ) {
563 $this->loadPageData();
564 }
565 return (int)$this->mLatest;
566 }
567
568 /**
569 * Get the Revision object of the oldest revision
570 * @return Revision|null
571 */
572 public function getOldestRevision() {
573
574 // Try using the replica DB first, then try the master
575 $continue = 2;
576 $db = wfGetDB( DB_REPLICA );
577 $revSelectFields = Revision::selectFields();
578
579 $row = null;
580 while ( $continue ) {
581 $row = $db->selectRow(
582 [ 'page', 'revision' ],
583 $revSelectFields,
584 [
585 'page_namespace' => $this->mTitle->getNamespace(),
586 'page_title' => $this->mTitle->getDBkey(),
587 'rev_page = page_id'
588 ],
589 __METHOD__,
590 [
591 'ORDER BY' => 'rev_timestamp ASC'
592 ]
593 );
594
595 if ( $row ) {
596 $continue = 0;
597 } else {
598 $db = wfGetDB( DB_MASTER );
599 $continue--;
600 }
601 }
602
603 return $row ? Revision::newFromRow( $row ) : null;
604 }
605
606 /**
607 * Loads everything except the text
608 * This isn't necessary for all uses, so it's only done if needed.
609 */
610 protected function loadLastEdit() {
611 if ( $this->mLastRevision !== null ) {
612 return; // already loaded
613 }
614
615 $latest = $this->getLatest();
616 if ( !$latest ) {
617 return; // page doesn't exist or is missing page_latest info
618 }
619
620 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
621 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
622 // includes the latest changes committed. This is true even within REPEATABLE-READ
623 // transactions, where S1 normally only sees changes committed before the first S1
624 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
625 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
626 // happened after the first S1 SELECT.
627 // https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
628 $flags = Revision::READ_LOCKING;
629 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
630 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
631 // Bug T93976: if page_latest was loaded from the master, fetch the
632 // revision from there as well, as it may not exist yet on a replica DB.
633 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
634 $flags = Revision::READ_LATEST;
635 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
636 } else {
637 $dbr = wfGetDB( DB_REPLICA );
638 $revision = Revision::newKnownCurrent( $dbr, $this->getId(), $latest );
639 }
640
641 if ( $revision ) { // sanity
642 $this->setLastEdit( $revision );
643 }
644 }
645
646 /**
647 * Set the latest revision
648 * @param Revision $revision
649 */
650 protected function setLastEdit( Revision $revision ) {
651 $this->mLastRevision = $revision;
652 $this->mTimestamp = $revision->getTimestamp();
653 }
654
655 /**
656 * Get the latest revision
657 * @return Revision|null
658 */
659 public function getRevision() {
660 $this->loadLastEdit();
661 if ( $this->mLastRevision ) {
662 return $this->mLastRevision;
663 }
664 return null;
665 }
666
667 /**
668 * Get the content of the current revision. No side-effects...
669 *
670 * @param int $audience One of:
671 * Revision::FOR_PUBLIC to be displayed to all users
672 * Revision::FOR_THIS_USER to be displayed to $wgUser
673 * Revision::RAW get the text regardless of permissions
674 * @param User $user User object to check for, only if FOR_THIS_USER is passed
675 * to the $audience parameter
676 * @return Content|null The content of the current revision
677 *
678 * @since 1.21
679 */
680 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
681 $this->loadLastEdit();
682 if ( $this->mLastRevision ) {
683 return $this->mLastRevision->getContent( $audience, $user );
684 }
685 return null;
686 }
687
688 /**
689 * Get the text of the current revision. No side-effects...
690 *
691 * @param int $audience One of:
692 * Revision::FOR_PUBLIC to be displayed to all users
693 * Revision::FOR_THIS_USER to be displayed to the given user
694 * Revision::RAW get the text regardless of permissions
695 * @param User $user User object to check for, only if FOR_THIS_USER is passed
696 * to the $audience parameter
697 * @return string|bool The text of the current revision
698 * @deprecated since 1.21, getContent() should be used instead.
699 */
700 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
701 wfDeprecated( __METHOD__, '1.21' );
702
703 $this->loadLastEdit();
704 if ( $this->mLastRevision ) {
705 return $this->mLastRevision->getText( $audience, $user );
706 }
707 return false;
708 }
709
710 /**
711 * @return string MW timestamp of last article revision
712 */
713 public function getTimestamp() {
714 // Check if the field has been filled by WikiPage::setTimestamp()
715 if ( !$this->mTimestamp ) {
716 $this->loadLastEdit();
717 }
718
719 return wfTimestamp( TS_MW, $this->mTimestamp );
720 }
721
722 /**
723 * Set the page timestamp (use only to avoid DB queries)
724 * @param string $ts MW timestamp of last article revision
725 * @return void
726 */
727 public function setTimestamp( $ts ) {
728 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
729 }
730
731 /**
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 int User ID for the user that made the last article revision
739 */
740 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
741 $this->loadLastEdit();
742 if ( $this->mLastRevision ) {
743 return $this->mLastRevision->getUser( $audience, $user );
744 } else {
745 return -1;
746 }
747 }
748
749 /**
750 * Get the User object of the user who created the page
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 User|null
758 */
759 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
760 $revision = $this->getOldestRevision();
761 if ( $revision ) {
762 $userName = $revision->getUserText( $audience, $user );
763 return User::newFromName( $userName, false );
764 } else {
765 return null;
766 }
767 }
768
769 /**
770 * @param int $audience One of:
771 * Revision::FOR_PUBLIC to be displayed to all users
772 * Revision::FOR_THIS_USER to be displayed to the given user
773 * Revision::RAW get the text regardless of permissions
774 * @param User $user User object to check for, only if FOR_THIS_USER is passed
775 * to the $audience parameter
776 * @return string Username of the user that made the last article revision
777 */
778 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
779 $this->loadLastEdit();
780 if ( $this->mLastRevision ) {
781 return $this->mLastRevision->getUserText( $audience, $user );
782 } else {
783 return '';
784 }
785 }
786
787 /**
788 * @param int $audience One of:
789 * Revision::FOR_PUBLIC to be displayed to all users
790 * Revision::FOR_THIS_USER to be displayed to the given user
791 * Revision::RAW get the text regardless of permissions
792 * @param User $user User object to check for, only if FOR_THIS_USER is passed
793 * to the $audience parameter
794 * @return string Comment stored for the last article revision
795 */
796 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
797 $this->loadLastEdit();
798 if ( $this->mLastRevision ) {
799 return $this->mLastRevision->getComment( $audience, $user );
800 } else {
801 return '';
802 }
803 }
804
805 /**
806 * Returns true if last revision was marked as "minor edit"
807 *
808 * @return bool Minor edit indicator for the last article revision.
809 */
810 public function getMinorEdit() {
811 $this->loadLastEdit();
812 if ( $this->mLastRevision ) {
813 return $this->mLastRevision->isMinor();
814 } else {
815 return false;
816 }
817 }
818
819 /**
820 * Determine whether a page would be suitable for being counted as an
821 * article in the site_stats table based on the title & its content
822 *
823 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
824 * if false, the current database state will be used
825 * @return bool
826 */
827 public function isCountable( $editInfo = false ) {
828 global $wgArticleCountMethod;
829
830 if ( !$this->mTitle->isContentPage() ) {
831 return false;
832 }
833
834 if ( $editInfo ) {
835 $content = $editInfo->pstContent;
836 } else {
837 $content = $this->getContent();
838 }
839
840 if ( !$content || $content->isRedirect() ) {
841 return false;
842 }
843
844 $hasLinks = null;
845
846 if ( $wgArticleCountMethod === 'link' ) {
847 // nasty special case to avoid re-parsing to detect links
848
849 if ( $editInfo ) {
850 // ParserOutput::getLinks() is a 2D array of page links, so
851 // to be really correct we would need to recurse in the array
852 // but the main array should only have items in it if there are
853 // links.
854 $hasLinks = (bool)count( $editInfo->output->getLinks() );
855 } else {
856 $hasLinks = (bool)wfGetDB( DB_REPLICA )->selectField( 'pagelinks', 1,
857 [ 'pl_from' => $this->getId() ], __METHOD__ );
858 }
859 }
860
861 return $content->isCountable( $hasLinks );
862 }
863
864 /**
865 * If this page is a redirect, get its target
866 *
867 * The target will be fetched from the redirect table if possible.
868 * If this page doesn't have an entry there, call insertRedirect()
869 * @return Title|null Title object, or null if this page is not a redirect
870 */
871 public function getRedirectTarget() {
872 if ( !$this->mTitle->isRedirect() ) {
873 return null;
874 }
875
876 if ( $this->mRedirectTarget !== null ) {
877 return $this->mRedirectTarget;
878 }
879
880 // Query the redirect table
881 $dbr = wfGetDB( DB_REPLICA );
882 $row = $dbr->selectRow( 'redirect',
883 [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
884 [ 'rd_from' => $this->getId() ],
885 __METHOD__
886 );
887
888 // rd_fragment and rd_interwiki were added later, populate them if empty
889 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
890 $this->mRedirectTarget = Title::makeTitle(
891 $row->rd_namespace, $row->rd_title,
892 $row->rd_fragment, $row->rd_interwiki
893 );
894 return $this->mRedirectTarget;
895 }
896
897 // This page doesn't have an entry in the redirect table
898 $this->mRedirectTarget = $this->insertRedirect();
899 return $this->mRedirectTarget;
900 }
901
902 /**
903 * Insert an entry for this page into the redirect table if the content is a redirect
904 *
905 * The database update will be deferred via DeferredUpdates
906 *
907 * Don't call this function directly unless you know what you're doing.
908 * @return Title|null Title object or null if not a redirect
909 */
910 public function insertRedirect() {
911 $content = $this->getContent();
912 $retval = $content ? $content->getUltimateRedirectTarget() : null;
913 if ( !$retval ) {
914 return null;
915 }
916
917 // Update the DB post-send if the page has not cached since now
918 $that = $this;
919 $latest = $this->getLatest();
920 DeferredUpdates::addCallableUpdate(
921 function () use ( $that, $retval, $latest ) {
922 $that->insertRedirectEntry( $retval, $latest );
923 },
924 DeferredUpdates::POSTSEND,
925 wfGetDB( DB_MASTER )
926 );
927
928 return $retval;
929 }
930
931 /**
932 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
933 * @param Title $rt Redirect target
934 * @param int|null $oldLatest Prior page_latest for check and set
935 */
936 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
937 $dbw = wfGetDB( DB_MASTER );
938 $dbw->startAtomic( __METHOD__ );
939
940 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
941 $dbw->upsert(
942 'redirect',
943 [
944 'rd_from' => $this->getId(),
945 'rd_namespace' => $rt->getNamespace(),
946 'rd_title' => $rt->getDBkey(),
947 'rd_fragment' => $rt->getFragment(),
948 'rd_interwiki' => $rt->getInterwiki(),
949 ],
950 [ 'rd_from' ],
951 [
952 'rd_namespace' => $rt->getNamespace(),
953 'rd_title' => $rt->getDBkey(),
954 'rd_fragment' => $rt->getFragment(),
955 'rd_interwiki' => $rt->getInterwiki(),
956 ],
957 __METHOD__
958 );
959 }
960
961 $dbw->endAtomic( __METHOD__ );
962 }
963
964 /**
965 * Get the Title object or URL this page redirects to
966 *
967 * @return bool|Title|string False, Title of in-wiki target, or string with URL
968 */
969 public function followRedirect() {
970 return $this->getRedirectURL( $this->getRedirectTarget() );
971 }
972
973 /**
974 * Get the Title object or URL to use for a redirect. We use Title
975 * objects for same-wiki, non-special redirects and URLs for everything
976 * else.
977 * @param Title $rt Redirect target
978 * @return bool|Title|string False, Title object of local target, or string with URL
979 */
980 public function getRedirectURL( $rt ) {
981 if ( !$rt ) {
982 return false;
983 }
984
985 if ( $rt->isExternal() ) {
986 if ( $rt->isLocal() ) {
987 // Offsite wikis need an HTTP redirect.
988 // This can be hard to reverse and may produce loops,
989 // so they may be disabled in the site configuration.
990 $source = $this->mTitle->getFullURL( 'redirect=no' );
991 return $rt->getFullURL( [ 'rdfrom' => $source ] );
992 } else {
993 // External pages without "local" bit set are not valid
994 // redirect targets
995 return false;
996 }
997 }
998
999 if ( $rt->isSpecialPage() ) {
1000 // Gotta handle redirects to special pages differently:
1001 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
1002 // Some pages are not valid targets.
1003 if ( $rt->isValidRedirectTarget() ) {
1004 return $rt->getFullURL();
1005 } else {
1006 return false;
1007 }
1008 }
1009
1010 return $rt;
1011 }
1012
1013 /**
1014 * Get a list of users who have edited this article, not including the user who made
1015 * the most recent revision, which you can get from $article->getUser() if you want it
1016 * @return UserArrayFromResult
1017 */
1018 public function getContributors() {
1019 // @todo FIXME: This is expensive; cache this info somewhere.
1020
1021 $dbr = wfGetDB( DB_REPLICA );
1022
1023 if ( $dbr->implicitGroupby() ) {
1024 $realNameField = 'user_real_name';
1025 } else {
1026 $realNameField = 'MIN(user_real_name) AS user_real_name';
1027 }
1028
1029 $tables = [ 'revision', 'user' ];
1030
1031 $fields = [
1032 'user_id' => 'rev_user',
1033 'user_name' => 'rev_user_text',
1034 $realNameField,
1035 'timestamp' => 'MAX(rev_timestamp)',
1036 ];
1037
1038 $conds = [ 'rev_page' => $this->getId() ];
1039
1040 // The user who made the top revision gets credited as "this page was last edited by
1041 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1042 $user = $this->getUser();
1043 if ( $user ) {
1044 $conds[] = "rev_user != $user";
1045 } else {
1046 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1047 }
1048
1049 // Username hidden?
1050 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1051
1052 $jconds = [
1053 'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1054 ];
1055
1056 $options = [
1057 'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1058 'ORDER BY' => 'timestamp DESC',
1059 ];
1060
1061 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1062 return new UserArrayFromResult( $res );
1063 }
1064
1065 /**
1066 * Should the parser cache be used?
1067 *
1068 * @param ParserOptions $parserOptions ParserOptions to check
1069 * @param int $oldId
1070 * @return bool
1071 */
1072 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1073 return $parserOptions->getStubThreshold() == 0
1074 && $this->exists()
1075 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1076 && $this->getContentHandler()->isParserCacheSupported();
1077 }
1078
1079 /**
1080 * Get a ParserOutput for the given ParserOptions and revision ID.
1081 *
1082 * The parser cache will be used if possible. Cache misses that result
1083 * in parser runs are debounced with PoolCounter.
1084 *
1085 * @since 1.19
1086 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1087 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1088 * get the current revision (default value)
1089 * @param bool $forceParse Force reindexing, regardless of cache settings
1090 * @return bool|ParserOutput ParserOutput or false if the revision was not found
1091 */
1092 public function getParserOutput(
1093 ParserOptions $parserOptions, $oldid = null, $forceParse = false
1094 ) {
1095 $useParserCache =
1096 ( !$forceParse ) && $this->shouldCheckParserCache( $parserOptions, $oldid );
1097 wfDebug( __METHOD__ .
1098 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1099 if ( $parserOptions->getStubThreshold() ) {
1100 wfIncrStats( 'pcache.miss.stub' );
1101 }
1102
1103 if ( $useParserCache ) {
1104 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1105 if ( $parserOutput !== false ) {
1106 return $parserOutput;
1107 }
1108 }
1109
1110 if ( $oldid === null || $oldid === 0 ) {
1111 $oldid = $this->getLatest();
1112 }
1113
1114 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1115 $pool->execute();
1116
1117 return $pool->getParserOutput();
1118 }
1119
1120 /**
1121 * Do standard deferred updates after page view (existing or missing page)
1122 * @param User $user The relevant user
1123 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1124 */
1125 public function doViewUpdates( User $user, $oldid = 0 ) {
1126 if ( wfReadOnly() ) {
1127 return;
1128 }
1129
1130 Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1131 // Update newtalk / watchlist notification status
1132 try {
1133 $user->clearNotification( $this->mTitle, $oldid );
1134 } catch ( DBError $e ) {
1135 // Avoid outage if the master is not reachable
1136 MWExceptionHandler::logException( $e );
1137 }
1138 }
1139
1140 /**
1141 * Perform the actions of a page purging
1142 * @param integer $flags Bitfield of WikiPage::PURGE_* constants
1143 * @return bool
1144 */
1145 public function doPurge( $flags = self::PURGE_ALL ) {
1146 if ( !Hooks::run( 'ArticlePurge', [ &$this ] ) ) {
1147 return false;
1148 }
1149
1150 if ( ( $flags & self::PURGE_GLOBAL_PCACHE ) == self::PURGE_GLOBAL_PCACHE ) {
1151 // Set page_touched in the database to invalidate all DC caches
1152 $this->mTitle->invalidateCache();
1153 } elseif ( ( $flags & self::PURGE_CLUSTER_PCACHE ) == self::PURGE_CLUSTER_PCACHE ) {
1154 // Delete the parser options key in the local cluster to invalidate the DC cache
1155 ParserCache::singleton()->deleteOptionsKey( $this );
1156 // Avoid sending HTTP 304s in ViewAction to the client who just issued the purge
1157 $cache = ObjectCache::getLocalClusterInstance();
1158 $cache->set(
1159 $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ),
1160 wfTimestamp( TS_MW ),
1161 $cache::TTL_HOUR
1162 );
1163 }
1164
1165 if ( ( $flags & self::PURGE_CDN_CACHE ) == self::PURGE_CDN_CACHE ) {
1166 // Clear any HTML file cache
1167 HTMLFileCache::clearFileCache( $this->getTitle() );
1168 // Send purge after any page_touched above update was committed
1169 DeferredUpdates::addUpdate(
1170 new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1171 DeferredUpdates::PRESEND
1172 );
1173 }
1174
1175 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1176 // @todo move this logic to MessageCache
1177 if ( $this->exists() ) {
1178 // NOTE: use transclusion text for messages.
1179 // This is consistent with MessageCache::getMsgFromNamespace()
1180
1181 $content = $this->getContent();
1182 $text = $content === null ? null : $content->getWikitextForTransclusion();
1183
1184 if ( $text === null ) {
1185 $text = false;
1186 }
1187 } else {
1188 $text = false;
1189 }
1190
1191 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1192 }
1193
1194 return true;
1195 }
1196
1197 /**
1198 * Get the last time a user explicitly purged the page via action=purge
1199 *
1200 * @return string|bool TS_MW timestamp or false
1201 * @since 1.28
1202 */
1203 public function getLastPurgeTimestamp() {
1204 $cache = ObjectCache::getLocalClusterInstance();
1205
1206 return $cache->get( $cache->makeKey( 'page', 'last-dc-purge', $this->getId() ) );
1207 }
1208
1209 /**
1210 * Insert a new empty page record for this article.
1211 * This *must* be followed up by creating a revision
1212 * and running $this->updateRevisionOn( ... );
1213 * or else the record will be left in a funky state.
1214 * Best if all done inside a transaction.
1215 *
1216 * @param IDatabase $dbw
1217 * @param int|null $pageId Custom page ID that will be used for the insert statement
1218 *
1219 * @return bool|int The newly created page_id key; false if the row was not
1220 * inserted, e.g. because the title already existed or because the specified
1221 * page ID is already in use.
1222 */
1223 public function insertOn( $dbw, $pageId = null ) {
1224 $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1225 $dbw->insert(
1226 'page',
1227 [
1228 'page_id' => $pageIdForInsert,
1229 'page_namespace' => $this->mTitle->getNamespace(),
1230 'page_title' => $this->mTitle->getDBkey(),
1231 'page_restrictions' => '',
1232 'page_is_redirect' => 0, // Will set this shortly...
1233 'page_is_new' => 1,
1234 'page_random' => wfRandom(),
1235 'page_touched' => $dbw->timestamp(),
1236 'page_latest' => 0, // Fill this in shortly...
1237 'page_len' => 0, // Fill this in shortly...
1238 ],
1239 __METHOD__,
1240 'IGNORE'
1241 );
1242
1243 if ( $dbw->affectedRows() > 0 ) {
1244 $newid = $pageId ?: $dbw->insertId();
1245 $this->mId = $newid;
1246 $this->mTitle->resetArticleID( $newid );
1247
1248 return $newid;
1249 } else {
1250 return false; // nothing changed
1251 }
1252 }
1253
1254 /**
1255 * Update the page record to point to a newly saved revision.
1256 *
1257 * @param IDatabase $dbw
1258 * @param Revision $revision For ID number, and text used to set
1259 * length and redirect status fields
1260 * @param int $lastRevision If given, will not overwrite the page field
1261 * when different from the currently set value.
1262 * Giving 0 indicates the new page flag should be set on.
1263 * @param bool $lastRevIsRedirect If given, will optimize adding and
1264 * removing rows in redirect table.
1265 * @return bool Success; false if the page row was missing or page_latest changed
1266 */
1267 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1268 $lastRevIsRedirect = null
1269 ) {
1270 global $wgContentHandlerUseDB;
1271
1272 // Assertion to try to catch T92046
1273 if ( (int)$revision->getId() === 0 ) {
1274 throw new InvalidArgumentException(
1275 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1276 );
1277 }
1278
1279 $content = $revision->getContent();
1280 $len = $content ? $content->getSize() : 0;
1281 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1282
1283 $conditions = [ 'page_id' => $this->getId() ];
1284
1285 if ( !is_null( $lastRevision ) ) {
1286 // An extra check against threads stepping on each other
1287 $conditions['page_latest'] = $lastRevision;
1288 }
1289
1290 $row = [ /* SET */
1291 'page_latest' => $revision->getId(),
1292 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1293 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1294 'page_is_redirect' => $rt !== null ? 1 : 0,
1295 'page_len' => $len,
1296 ];
1297
1298 if ( $wgContentHandlerUseDB ) {
1299 $row['page_content_model'] = $revision->getContentModel();
1300 }
1301
1302 $dbw->update( 'page',
1303 $row,
1304 $conditions,
1305 __METHOD__ );
1306
1307 $result = $dbw->affectedRows() > 0;
1308 if ( $result ) {
1309 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1310 $this->setLastEdit( $revision );
1311 $this->mLatest = $revision->getId();
1312 $this->mIsRedirect = (bool)$rt;
1313 // Update the LinkCache.
1314 LinkCache::singleton()->addGoodLinkObj(
1315 $this->getId(),
1316 $this->mTitle,
1317 $len,
1318 $this->mIsRedirect,
1319 $this->mLatest,
1320 $revision->getContentModel()
1321 );
1322 }
1323
1324 return $result;
1325 }
1326
1327 /**
1328 * Add row to the redirect table if this is a redirect, remove otherwise.
1329 *
1330 * @param IDatabase $dbw
1331 * @param Title $redirectTitle Title object pointing to the redirect target,
1332 * or NULL if this is not a redirect
1333 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1334 * removing rows in redirect table.
1335 * @return bool True on success, false on failure
1336 * @private
1337 */
1338 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1339 // Always update redirects (target link might have changed)
1340 // Update/Insert if we don't know if the last revision was a redirect or not
1341 // Delete if changing from redirect to non-redirect
1342 $isRedirect = !is_null( $redirectTitle );
1343
1344 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1345 return true;
1346 }
1347
1348 if ( $isRedirect ) {
1349 $this->insertRedirectEntry( $redirectTitle );
1350 } else {
1351 // This is not a redirect, remove row from redirect table
1352 $where = [ 'rd_from' => $this->getId() ];
1353 $dbw->delete( 'redirect', $where, __METHOD__ );
1354 }
1355
1356 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1357 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1358 }
1359
1360 return ( $dbw->affectedRows() != 0 );
1361 }
1362
1363 /**
1364 * If the given revision is newer than the currently set page_latest,
1365 * update the page record. Otherwise, do nothing.
1366 *
1367 * @deprecated since 1.24, use updateRevisionOn instead
1368 *
1369 * @param IDatabase $dbw
1370 * @param Revision $revision
1371 * @return bool
1372 */
1373 public function updateIfNewerOn( $dbw, $revision ) {
1374
1375 $row = $dbw->selectRow(
1376 [ 'revision', 'page' ],
1377 [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1378 [
1379 'page_id' => $this->getId(),
1380 'page_latest=rev_id' ],
1381 __METHOD__ );
1382
1383 if ( $row ) {
1384 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1385 return false;
1386 }
1387 $prev = $row->rev_id;
1388 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1389 } else {
1390 // No or missing previous revision; mark the page as new
1391 $prev = 0;
1392 $lastRevIsRedirect = null;
1393 }
1394
1395 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1396
1397 return $ret;
1398 }
1399
1400 /**
1401 * Get the content that needs to be saved in order to undo all revisions
1402 * between $undo and $undoafter. Revisions must belong to the same page,
1403 * must exist and must not be deleted
1404 * @param Revision $undo
1405 * @param Revision $undoafter Must be an earlier revision than $undo
1406 * @return Content|bool Content on success, false on failure
1407 * @since 1.21
1408 * Before we had the Content object, this was done in getUndoText
1409 */
1410 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1411 $handler = $undo->getContentHandler();
1412 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1413 }
1414
1415 /**
1416 * Returns true if this page's content model supports sections.
1417 *
1418 * @return bool
1419 *
1420 * @todo The skin should check this and not offer section functionality if
1421 * sections are not supported.
1422 * @todo The EditPage should check this and not offer section functionality
1423 * if sections are not supported.
1424 */
1425 public function supportsSections() {
1426 return $this->getContentHandler()->supportsSections();
1427 }
1428
1429 /**
1430 * @param string|number|null|bool $sectionId Section identifier as a number or string
1431 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1432 * or 'new' for a new section.
1433 * @param Content $sectionContent New content of the section.
1434 * @param string $sectionTitle New section's subject, only if $section is "new".
1435 * @param string $edittime Revision timestamp or null to use the current revision.
1436 *
1437 * @throws MWException
1438 * @return Content|null New complete article content, or null if error.
1439 *
1440 * @since 1.21
1441 * @deprecated since 1.24, use replaceSectionAtRev instead
1442 */
1443 public function replaceSectionContent(
1444 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1445 ) {
1446
1447 $baseRevId = null;
1448 if ( $edittime && $sectionId !== 'new' ) {
1449 $dbr = wfGetDB( DB_REPLICA );
1450 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1451 // Try the master if this thread may have just added it.
1452 // This could be abstracted into a Revision method, but we don't want
1453 // to encourage loading of revisions by timestamp.
1454 if ( !$rev
1455 && wfGetLB()->getServerCount() > 1
1456 && wfGetLB()->hasOrMadeRecentMasterChanges()
1457 ) {
1458 $dbw = wfGetDB( DB_MASTER );
1459 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1460 }
1461 if ( $rev ) {
1462 $baseRevId = $rev->getId();
1463 }
1464 }
1465
1466 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1467 }
1468
1469 /**
1470 * @param string|number|null|bool $sectionId Section identifier as a number or string
1471 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1472 * or 'new' for a new section.
1473 * @param Content $sectionContent New content of the section.
1474 * @param string $sectionTitle New section's subject, only if $section is "new".
1475 * @param int|null $baseRevId
1476 *
1477 * @throws MWException
1478 * @return Content|null New complete article content, or null if error.
1479 *
1480 * @since 1.24
1481 */
1482 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1483 $sectionTitle = '', $baseRevId = null
1484 ) {
1485
1486 if ( strval( $sectionId ) === '' ) {
1487 // Whole-page edit; let the whole text through
1488 $newContent = $sectionContent;
1489 } else {
1490 if ( !$this->supportsSections() ) {
1491 throw new MWException( "sections not supported for content model " .
1492 $this->getContentHandler()->getModelID() );
1493 }
1494
1495 // Bug 30711: always use current version when adding a new section
1496 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1497 $oldContent = $this->getContent();
1498 } else {
1499 $rev = Revision::newFromId( $baseRevId );
1500 if ( !$rev ) {
1501 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1502 $this->getId() . "; section: $sectionId)\n" );
1503 return null;
1504 }
1505
1506 $oldContent = $rev->getContent();
1507 }
1508
1509 if ( !$oldContent ) {
1510 wfDebug( __METHOD__ . ": no page text\n" );
1511 return null;
1512 }
1513
1514 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1515 }
1516
1517 return $newContent;
1518 }
1519
1520 /**
1521 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1522 * @param int $flags
1523 * @return int Updated $flags
1524 */
1525 public function checkFlags( $flags ) {
1526 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1527 if ( $this->exists() ) {
1528 $flags |= EDIT_UPDATE;
1529 } else {
1530 $flags |= EDIT_NEW;
1531 }
1532 }
1533
1534 return $flags;
1535 }
1536
1537 /**
1538 * Change an existing article or create a new article. Updates RC and all necessary caches,
1539 * optionally via the deferred update array.
1540 *
1541 * @param string $text New text
1542 * @param string $summary Edit summary
1543 * @param int $flags Bitfield:
1544 * EDIT_NEW
1545 * Article is known or assumed to be non-existent, create a new one
1546 * EDIT_UPDATE
1547 * Article is known or assumed to be pre-existing, update it
1548 * EDIT_MINOR
1549 * Mark this edit minor, if the user is allowed to do so
1550 * EDIT_SUPPRESS_RC
1551 * Do not log the change in recentchanges
1552 * EDIT_FORCE_BOT
1553 * Mark the edit a "bot" edit regardless of user rights
1554 * EDIT_AUTOSUMMARY
1555 * Fill in blank summaries with generated text where possible
1556 * EDIT_INTERNAL
1557 * Signal that the page retrieve/save cycle happened entirely in this request.
1558 *
1559 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1560 * article will be detected. If EDIT_UPDATE is specified and the article
1561 * doesn't exist, the function will return an edit-gone-missing error. If
1562 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1563 * error will be returned. These two conditions are also possible with
1564 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1565 *
1566 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1567 * This is not the parent revision ID, rather the revision ID for older
1568 * content used as the source for a rollback, for example.
1569 * @param User $user The user doing the edit
1570 *
1571 * @throws MWException
1572 * @return Status Possible errors:
1573 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1574 * set the fatal flag of $status
1575 * edit-gone-missing: In update mode, but the article didn't exist.
1576 * edit-conflict: In update mode, the article changed unexpectedly.
1577 * edit-no-change: Warning that the text was the same as before.
1578 * edit-already-exists: In creation mode, but the article already exists.
1579 *
1580 * Extensions may define additional errors.
1581 *
1582 * $return->value will contain an associative array with members as follows:
1583 * new: Boolean indicating if the function attempted to create a new article.
1584 * revision: The revision object for the inserted revision, or null.
1585 *
1586 * Compatibility note: this function previously returned a boolean value
1587 * indicating success/failure
1588 *
1589 * @deprecated since 1.21: use doEditContent() instead.
1590 */
1591 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1592 wfDeprecated( __METHOD__, '1.21' );
1593
1594 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1595
1596 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1597 }
1598
1599 /**
1600 * Change an existing article or create a new article. Updates RC and all necessary caches,
1601 * optionally via the deferred update array.
1602 *
1603 * @param Content $content New content
1604 * @param string $summary Edit summary
1605 * @param int $flags Bitfield:
1606 * EDIT_NEW
1607 * Article is known or assumed to be non-existent, create a new one
1608 * EDIT_UPDATE
1609 * Article is known or assumed to be pre-existing, update it
1610 * EDIT_MINOR
1611 * Mark this edit minor, if the user is allowed to do so
1612 * EDIT_SUPPRESS_RC
1613 * Do not log the change in recentchanges
1614 * EDIT_FORCE_BOT
1615 * Mark the edit a "bot" edit regardless of user rights
1616 * EDIT_AUTOSUMMARY
1617 * Fill in blank summaries with generated text where possible
1618 * EDIT_INTERNAL
1619 * Signal that the page retrieve/save cycle happened entirely in this request.
1620 *
1621 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1622 * article will be detected. If EDIT_UPDATE is specified and the article
1623 * doesn't exist, the function will return an edit-gone-missing error. If
1624 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1625 * error will be returned. These two conditions are also possible with
1626 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1627 *
1628 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1629 * This is not the parent revision ID, rather the revision ID for older
1630 * content used as the source for a rollback, for example.
1631 * @param User $user The user doing the edit
1632 * @param string $serialFormat Format for storing the content in the
1633 * database.
1634 * @param array|null $tags Change tags to apply to this edit
1635 * Callers are responsible for permission checks
1636 * (with ChangeTags::canAddTagsAccompanyingChange)
1637 *
1638 * @throws MWException
1639 * @return Status Possible errors:
1640 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1641 * set the fatal flag of $status.
1642 * edit-gone-missing: In update mode, but the article didn't exist.
1643 * edit-conflict: In update mode, the article changed unexpectedly.
1644 * edit-no-change: Warning that the text was the same as before.
1645 * edit-already-exists: In creation mode, but the article already exists.
1646 *
1647 * Extensions may define additional errors.
1648 *
1649 * $return->value will contain an associative array with members as follows:
1650 * new: Boolean indicating if the function attempted to create a new article.
1651 * revision: The revision object for the inserted revision, or null.
1652 *
1653 * @since 1.21
1654 * @throws MWException
1655 */
1656 public function doEditContent(
1657 Content $content, $summary, $flags = 0, $baseRevId = false,
1658 User $user = null, $serialFormat = null, $tags = []
1659 ) {
1660 global $wgUser, $wgUseAutomaticEditSummaries;
1661
1662 // Old default parameter for $tags was null
1663 if ( $tags === null ) {
1664 $tags = [];
1665 }
1666
1667 // Low-level sanity check
1668 if ( $this->mTitle->getText() === '' ) {
1669 throw new MWException( 'Something is trying to edit an article with an empty title' );
1670 }
1671 // Make sure the given content type is allowed for this page
1672 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1673 return Status::newFatal( 'content-not-allowed-here',
1674 ContentHandler::getLocalizedName( $content->getModel() ),
1675 $this->mTitle->getPrefixedText()
1676 );
1677 }
1678
1679 // Load the data from the master database if needed.
1680 // The caller may already loaded it from the master or even loaded it using
1681 // SELECT FOR UPDATE, so do not override that using clear().
1682 $this->loadPageData( 'fromdbmaster' );
1683
1684 $user = $user ?: $wgUser;
1685 $flags = $this->checkFlags( $flags );
1686
1687 // Trigger pre-save hook (using provided edit summary)
1688 $hookStatus = Status::newGood( [] );
1689 $hook_args = [ &$this, &$user, &$content, &$summary,
1690 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1691 // Check if the hook rejected the attempted save
1692 if ( !Hooks::run( 'PageContentSave', $hook_args )
1693 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args, '1.21' )
1694 ) {
1695 if ( $hookStatus->isOK() ) {
1696 // Hook returned false but didn't call fatal(); use generic message
1697 $hookStatus->fatal( 'edit-hook-aborted' );
1698 }
1699
1700 return $hookStatus;
1701 }
1702
1703 $old_revision = $this->getRevision(); // current revision
1704 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1705
1706 if ( $old_content && $old_content->getModel() !== $content->getModel() ) {
1707 $tags[] = 'mw-contentmodelchange';
1708 }
1709
1710 // Provide autosummaries if one is not provided and autosummaries are enabled
1711 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1712 $handler = $content->getContentHandler();
1713 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1714 }
1715
1716 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1717 if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1718 $useCache = false;
1719 } else {
1720 $useCache = true;
1721 }
1722
1723 // Get the pre-save transform content and final parser output
1724 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1725 $pstContent = $editInfo->pstContent; // Content object
1726 $meta = [
1727 'bot' => ( $flags & EDIT_FORCE_BOT ),
1728 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1729 'serialized' => $editInfo->pst,
1730 'serialFormat' => $serialFormat,
1731 'baseRevId' => $baseRevId,
1732 'oldRevision' => $old_revision,
1733 'oldContent' => $old_content,
1734 'oldId' => $this->getLatest(),
1735 'oldIsRedirect' => $this->isRedirect(),
1736 'oldCountable' => $this->isCountable(),
1737 'tags' => ( $tags !== null ) ? (array)$tags : []
1738 ];
1739
1740 // Actually create the revision and create/update the page
1741 if ( $flags & EDIT_UPDATE ) {
1742 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1743 } else {
1744 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1745 }
1746
1747 // Promote user to any groups they meet the criteria for
1748 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1749 $user->addAutopromoteOnceGroups( 'onEdit' );
1750 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1751 } );
1752
1753 return $status;
1754 }
1755
1756 /**
1757 * @param Content $content Pre-save transform content
1758 * @param integer $flags
1759 * @param User $user
1760 * @param string $summary
1761 * @param array $meta
1762 * @return Status
1763 * @throws DBUnexpectedError
1764 * @throws Exception
1765 * @throws FatalError
1766 * @throws MWException
1767 */
1768 private function doModify(
1769 Content $content, $flags, User $user, $summary, array $meta
1770 ) {
1771 global $wgUseRCPatrol;
1772
1773 // Update article, but only if changed.
1774 $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1775
1776 // Convenience variables
1777 $now = wfTimestampNow();
1778 $oldid = $meta['oldId'];
1779 /** @var $oldContent Content|null */
1780 $oldContent = $meta['oldContent'];
1781 $newsize = $content->getSize();
1782
1783 if ( !$oldid ) {
1784 // Article gone missing
1785 $status->fatal( 'edit-gone-missing' );
1786
1787 return $status;
1788 } elseif ( !$oldContent ) {
1789 // Sanity check for bug 37225
1790 throw new MWException( "Could not find text for current revision {$oldid}." );
1791 }
1792
1793 // @TODO: pass content object?!
1794 $revision = new Revision( [
1795 'page' => $this->getId(),
1796 'title' => $this->mTitle, // for determining the default content model
1797 'comment' => $summary,
1798 'minor_edit' => $meta['minor'],
1799 'text' => $meta['serialized'],
1800 'len' => $newsize,
1801 'parent_id' => $oldid,
1802 'user' => $user->getId(),
1803 'user_text' => $user->getName(),
1804 'timestamp' => $now,
1805 'content_model' => $content->getModel(),
1806 'content_format' => $meta['serialFormat'],
1807 ] );
1808
1809 $changed = !$content->equals( $oldContent );
1810
1811 $dbw = wfGetDB( DB_MASTER );
1812
1813 if ( $changed ) {
1814 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1815 $status->merge( $prepStatus );
1816 if ( !$status->isOK() ) {
1817 return $status;
1818 }
1819
1820 $dbw->startAtomic( __METHOD__ );
1821 // Get the latest page_latest value while locking it.
1822 // Do a CAS style check to see if it's the same as when this method
1823 // started. If it changed then bail out before touching the DB.
1824 $latestNow = $this->lockAndGetLatest();
1825 if ( $latestNow != $oldid ) {
1826 $dbw->endAtomic( __METHOD__ );
1827 // Page updated or deleted in the mean time
1828 $status->fatal( 'edit-conflict' );
1829
1830 return $status;
1831 }
1832
1833 // At this point we are now comitted to returning an OK
1834 // status unless some DB query error or other exception comes up.
1835 // This way callers don't have to call rollback() if $status is bad
1836 // unless they actually try to catch exceptions (which is rare).
1837
1838 // Save the revision text
1839 $revisionId = $revision->insertOn( $dbw );
1840 // Update page_latest and friends to reflect the new revision
1841 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1842 throw new MWException( "Failed to update page row to use new revision." );
1843 }
1844
1845 Hooks::run( 'NewRevisionFromEditComplete',
1846 [ $this, $revision, $meta['baseRevId'], $user ] );
1847
1848 // Update recentchanges
1849 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1850 // Mark as patrolled if the user can do so
1851 $patrolled = $wgUseRCPatrol && !count(
1852 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1853 // Add RC row to the DB
1854 RecentChange::notifyEdit(
1855 $now,
1856 $this->mTitle,
1857 $revision->isMinor(),
1858 $user,
1859 $summary,
1860 $oldid,
1861 $this->getTimestamp(),
1862 $meta['bot'],
1863 '',
1864 $oldContent ? $oldContent->getSize() : 0,
1865 $newsize,
1866 $revisionId,
1867 $patrolled,
1868 $meta['tags']
1869 );
1870 }
1871
1872 $user->incEditCount();
1873
1874 $dbw->endAtomic( __METHOD__ );
1875 $this->mTimestamp = $now;
1876 } else {
1877 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1878 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1879 $revision->setId( $this->getLatest() );
1880 $revision->setUserIdAndName(
1881 $this->getUser( Revision::RAW ),
1882 $this->getUserText( Revision::RAW )
1883 );
1884 }
1885
1886 if ( $changed ) {
1887 // Return the new revision to the caller
1888 $status->value['revision'] = $revision;
1889 } else {
1890 $status->warning( 'edit-no-change' );
1891 // Update page_touched as updateRevisionOn() was not called.
1892 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1893 $this->mTitle->invalidateCache( $now );
1894 }
1895
1896 // Do secondary updates once the main changes have been committed...
1897 DeferredUpdates::addUpdate(
1898 new AtomicSectionUpdate(
1899 $dbw,
1900 __METHOD__,
1901 function () use (
1902 $revision, &$user, $content, $summary, &$flags,
1903 $changed, $meta, &$status
1904 ) {
1905 // Update links tables, site stats, etc.
1906 $this->doEditUpdates(
1907 $revision,
1908 $user,
1909 [
1910 'changed' => $changed,
1911 'oldcountable' => $meta['oldCountable'],
1912 'oldrevision' => $meta['oldRevision']
1913 ]
1914 );
1915 // Trigger post-save hook
1916 $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR,
1917 null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1918 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1919 Hooks::run( 'PageContentSaveComplete', $params );
1920 }
1921 ),
1922 DeferredUpdates::PRESEND
1923 );
1924
1925 return $status;
1926 }
1927
1928 /**
1929 * @param Content $content Pre-save transform content
1930 * @param integer $flags
1931 * @param User $user
1932 * @param string $summary
1933 * @param array $meta
1934 * @return Status
1935 * @throws DBUnexpectedError
1936 * @throws Exception
1937 * @throws FatalError
1938 * @throws MWException
1939 */
1940 private function doCreate(
1941 Content $content, $flags, User $user, $summary, array $meta
1942 ) {
1943 global $wgUseRCPatrol, $wgUseNPPatrol;
1944
1945 $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1946
1947 $now = wfTimestampNow();
1948 $newsize = $content->getSize();
1949 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1950 $status->merge( $prepStatus );
1951 if ( !$status->isOK() ) {
1952 return $status;
1953 }
1954
1955 $dbw = wfGetDB( DB_MASTER );
1956 $dbw->startAtomic( __METHOD__ );
1957
1958 // Add the page record unless one already exists for the title
1959 $newid = $this->insertOn( $dbw );
1960 if ( $newid === false ) {
1961 $dbw->endAtomic( __METHOD__ ); // nothing inserted
1962 $status->fatal( 'edit-already-exists' );
1963
1964 return $status; // nothing done
1965 }
1966
1967 // At this point we are now comitted to returning an OK
1968 // status unless some DB query error or other exception comes up.
1969 // This way callers don't have to call rollback() if $status is bad
1970 // unless they actually try to catch exceptions (which is rare).
1971
1972 // @TODO: pass content object?!
1973 $revision = new Revision( [
1974 'page' => $newid,
1975 'title' => $this->mTitle, // for determining the default content model
1976 'comment' => $summary,
1977 'minor_edit' => $meta['minor'],
1978 'text' => $meta['serialized'],
1979 'len' => $newsize,
1980 'user' => $user->getId(),
1981 'user_text' => $user->getName(),
1982 'timestamp' => $now,
1983 'content_model' => $content->getModel(),
1984 'content_format' => $meta['serialFormat'],
1985 ] );
1986
1987 // Save the revision text...
1988 $revisionId = $revision->insertOn( $dbw );
1989 // Update the page record with revision data
1990 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1991 throw new MWException( "Failed to update page row to use new revision." );
1992 }
1993
1994 Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1995
1996 // Update recentchanges
1997 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1998 // Mark as patrolled if the user can do so
1999 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
2000 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
2001 // Add RC row to the DB
2002 RecentChange::notifyNew(
2003 $now,
2004 $this->mTitle,
2005 $revision->isMinor(),
2006 $user,
2007 $summary,
2008 $meta['bot'],
2009 '',
2010 $newsize,
2011 $revisionId,
2012 $patrolled,
2013 $meta['tags']
2014 );
2015 }
2016
2017 $user->incEditCount();
2018
2019 $dbw->endAtomic( __METHOD__ );
2020 $this->mTimestamp = $now;
2021
2022 // Return the new revision to the caller
2023 $status->value['revision'] = $revision;
2024
2025 // Do secondary updates once the main changes have been committed...
2026 DeferredUpdates::addUpdate(
2027 new AtomicSectionUpdate(
2028 $dbw,
2029 __METHOD__,
2030 function () use (
2031 $revision, &$user, $content, $summary, &$flags, $meta, &$status
2032 ) {
2033 // Update links, etc.
2034 $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
2035 // Trigger post-create hook
2036 $params = [ &$this, &$user, $content, $summary,
2037 $flags & EDIT_MINOR, null, null, &$flags, $revision ];
2038 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $params, '1.21' );
2039 Hooks::run( 'PageContentInsertComplete', $params );
2040 // Trigger post-save hook
2041 $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
2042 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params, '1.21' );
2043 Hooks::run( 'PageContentSaveComplete', $params );
2044
2045 }
2046 ),
2047 DeferredUpdates::PRESEND
2048 );
2049
2050 return $status;
2051 }
2052
2053 /**
2054 * Get parser options suitable for rendering the primary article wikitext
2055 *
2056 * @see ContentHandler::makeParserOptions
2057 *
2058 * @param IContextSource|User|string $context One of the following:
2059 * - IContextSource: Use the User and the Language of the provided
2060 * context
2061 * - User: Use the provided User object and $wgLang for the language,
2062 * so use an IContextSource object if possible.
2063 * - 'canonical': Canonical options (anonymous user with default
2064 * preferences and content language).
2065 * @return ParserOptions
2066 */
2067 public function makeParserOptions( $context ) {
2068 $options = $this->getContentHandler()->makeParserOptions( $context );
2069
2070 if ( $this->getTitle()->isConversionTable() ) {
2071 // @todo ConversionTable should become a separate content model, so
2072 // we don't need special cases like this one.
2073 $options->disableContentConversion();
2074 }
2075
2076 return $options;
2077 }
2078
2079 /**
2080 * Prepare content which is about to be saved.
2081 * Returns a stdClass with source, pst and output members
2082 *
2083 * @param Content $content
2084 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2085 * revision ID is also accepted, but this is deprecated.
2086 * @param User|null $user
2087 * @param string|null $serialFormat
2088 * @param bool $useCache Check shared prepared edit cache
2089 *
2090 * @return object
2091 *
2092 * @since 1.21
2093 */
2094 public function prepareContentForEdit(
2095 Content $content, $revision = null, User $user = null,
2096 $serialFormat = null, $useCache = true
2097 ) {
2098 global $wgContLang, $wgUser, $wgAjaxEditStash;
2099
2100 if ( is_object( $revision ) ) {
2101 $revid = $revision->getId();
2102 } else {
2103 $revid = $revision;
2104 // This code path is deprecated, and nothing is known to
2105 // use it, so performance here shouldn't be a worry.
2106 if ( $revid !== null ) {
2107 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2108 } else {
2109 $revision = null;
2110 }
2111 }
2112
2113 $user = is_null( $user ) ? $wgUser : $user;
2114 // XXX: check $user->getId() here???
2115
2116 // Use a sane default for $serialFormat, see bug 57026
2117 if ( $serialFormat === null ) {
2118 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2119 }
2120
2121 if ( $this->mPreparedEdit
2122 && isset( $this->mPreparedEdit->newContent )
2123 && $this->mPreparedEdit->newContent->equals( $content )
2124 && $this->mPreparedEdit->revid == $revid
2125 && $this->mPreparedEdit->format == $serialFormat
2126 // XXX: also check $user here?
2127 ) {
2128 // Already prepared
2129 return $this->mPreparedEdit;
2130 }
2131
2132 // The edit may have already been prepared via api.php?action=stashedit
2133 $cachedEdit = $useCache && $wgAjaxEditStash
2134 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2135 : false;
2136
2137 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2138 Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2139
2140 $edit = (object)[];
2141 if ( $cachedEdit ) {
2142 $edit->timestamp = $cachedEdit->timestamp;
2143 } else {
2144 $edit->timestamp = wfTimestampNow();
2145 }
2146 // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2147 $edit->revid = $revid;
2148
2149 if ( $cachedEdit ) {
2150 $edit->pstContent = $cachedEdit->pstContent;
2151 } else {
2152 $edit->pstContent = $content
2153 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2154 : null;
2155 }
2156
2157 $edit->format = $serialFormat;
2158 $edit->popts = $this->makeParserOptions( 'canonical' );
2159 if ( $cachedEdit ) {
2160 $edit->output = $cachedEdit->output;
2161 } else {
2162 if ( $revision ) {
2163 // We get here if vary-revision is set. This means that this page references
2164 // itself (such as via self-transclusion). In this case, we need to make sure
2165 // that any such self-references refer to the newly-saved revision, and not
2166 // to the previous one, which could otherwise happen due to replica DB lag.
2167 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2168 $edit->popts->setCurrentRevisionCallback(
2169 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2170 if ( $title->equals( $revision->getTitle() ) ) {
2171 return $revision;
2172 } else {
2173 return call_user_func( $oldCallback, $title, $parser );
2174 }
2175 }
2176 );
2177 } else {
2178 // Try to avoid a second parse if {{REVISIONID}} is used
2179 $edit->popts->setSpeculativeRevIdCallback( function () {
2180 return 1 + (int)wfGetDB( DB_MASTER )->selectField(
2181 'revision',
2182 'MAX(rev_id)',
2183 [],
2184 __METHOD__
2185 );
2186 } );
2187 }
2188 $edit->output = $edit->pstContent
2189 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2190 : null;
2191 }
2192
2193 $edit->newContent = $content;
2194 $edit->oldContent = $this->getContent( Revision::RAW );
2195
2196 // NOTE: B/C for hooks! don't use these fields!
2197 $edit->newText = $edit->newContent
2198 ? ContentHandler::getContentText( $edit->newContent )
2199 : '';
2200 $edit->oldText = $edit->oldContent
2201 ? ContentHandler::getContentText( $edit->oldContent )
2202 : '';
2203 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2204
2205 if ( $edit->output ) {
2206 $edit->output->setCacheTime( wfTimestampNow() );
2207 }
2208
2209 // Process cache the result
2210 $this->mPreparedEdit = $edit;
2211
2212 return $edit;
2213 }
2214
2215 /**
2216 * Do standard deferred updates after page edit.
2217 * Update links tables, site stats, search index and message cache.
2218 * Purges pages that include this page if the text was changed here.
2219 * Every 100th edit, prune the recent changes table.
2220 *
2221 * @param Revision $revision
2222 * @param User $user User object that did the revision
2223 * @param array $options Array of options, following indexes are used:
2224 * - changed: boolean, whether the revision changed the content (default true)
2225 * - created: boolean, whether the revision created the page (default false)
2226 * - moved: boolean, whether the page was moved (default false)
2227 * - restored: boolean, whether the page was undeleted (default false)
2228 * - oldrevision: Revision object for the pre-update revision (default null)
2229 * - oldcountable: boolean, null, or string 'no-change' (default null):
2230 * - boolean: whether the page was counted as an article before that
2231 * revision, only used in changed is true and created is false
2232 * - null: if created is false, don't update the article count; if created
2233 * is true, do update the article count
2234 * - 'no-change': don't update the article count, ever
2235 */
2236 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2237 global $wgRCWatchCategoryMembership, $wgContLang;
2238
2239 $options += [
2240 'changed' => true,
2241 'created' => false,
2242 'moved' => false,
2243 'restored' => false,
2244 'oldrevision' => null,
2245 'oldcountable' => null
2246 ];
2247 $content = $revision->getContent();
2248
2249 $logger = LoggerFactory::getInstance( 'SaveParse' );
2250
2251 // See if the parser output before $revision was inserted is still valid
2252 $editInfo = false;
2253 if ( !$this->mPreparedEdit ) {
2254 $logger->debug( __METHOD__ . ": No prepared edit...\n" );
2255 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2256 $logger->info( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2257 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision-id' )
2258 && $this->mPreparedEdit->output->getSpeculativeRevIdUsed() !== $revision->getId()
2259 ) {
2260 $logger->info( __METHOD__ . ": Prepared edit has vary-revision-id with wrong ID...\n" );
2261 } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2262 $logger->info( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2263 } else {
2264 wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2265 $editInfo = $this->mPreparedEdit;
2266 }
2267
2268 if ( !$editInfo ) {
2269 // Parse the text again if needed. Be careful not to do pre-save transform twice:
2270 // $text is usually already pre-save transformed once. Avoid using the edit stash
2271 // as any prepared content from there or in doEditContent() was already rejected.
2272 $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2273 }
2274
2275 // Save it to the parser cache.
2276 // Make sure the cache time matches page_touched to avoid double parsing.
2277 ParserCache::singleton()->save(
2278 $editInfo->output, $this, $editInfo->popts,
2279 $revision->getTimestamp(), $editInfo->revid
2280 );
2281
2282 // Update the links tables and other secondary data
2283 if ( $content ) {
2284 $recursive = $options['changed']; // bug 50785
2285 $updates = $content->getSecondaryDataUpdates(
2286 $this->getTitle(), null, $recursive, $editInfo->output
2287 );
2288 foreach ( $updates as $update ) {
2289 if ( $update instanceof LinksUpdate ) {
2290 $update->setRevision( $revision );
2291 $update->setTriggeringUser( $user );
2292 }
2293 DeferredUpdates::addUpdate( $update );
2294 }
2295 if ( $wgRCWatchCategoryMembership
2296 && $this->getContentHandler()->supportsCategories() === true
2297 && ( $options['changed'] || $options['created'] )
2298 && !$options['restored']
2299 ) {
2300 // Note: jobs are pushed after deferred updates, so the job should be able to see
2301 // the recent change entry (also done via deferred updates) and carry over any
2302 // bot/deletion/IP flags, ect.
2303 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2304 $this->getTitle(),
2305 [
2306 'pageId' => $this->getId(),
2307 'revTimestamp' => $revision->getTimestamp()
2308 ]
2309 ) );
2310 }
2311 }
2312
2313 Hooks::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2314
2315 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2316 // Flush old entries from the `recentchanges` table
2317 if ( mt_rand( 0, 9 ) == 0 ) {
2318 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2319 }
2320 }
2321
2322 if ( !$this->exists() ) {
2323 return;
2324 }
2325
2326 $id = $this->getId();
2327 $title = $this->mTitle->getPrefixedDBkey();
2328 $shortTitle = $this->mTitle->getDBkey();
2329
2330 if ( $options['oldcountable'] === 'no-change' ||
2331 ( !$options['changed'] && !$options['moved'] )
2332 ) {
2333 $good = 0;
2334 } elseif ( $options['created'] ) {
2335 $good = (int)$this->isCountable( $editInfo );
2336 } elseif ( $options['oldcountable'] !== null ) {
2337 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2338 } else {
2339 $good = 0;
2340 }
2341 $edits = $options['changed'] ? 1 : 0;
2342 $total = $options['created'] ? 1 : 0;
2343
2344 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2345 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2346
2347 // If this is another user's talk page, update newtalk.
2348 // Don't do this if $options['changed'] = false (null-edits) nor if
2349 // it's a minor edit and the user doesn't want notifications for those.
2350 if ( $options['changed']
2351 && $this->mTitle->getNamespace() == NS_USER_TALK
2352 && $shortTitle != $user->getTitleKey()
2353 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2354 ) {
2355 $recipient = User::newFromName( $shortTitle, false );
2356 if ( !$recipient ) {
2357 wfDebug( __METHOD__ . ": invalid username\n" );
2358 } else {
2359 // Allow extensions to prevent user notification
2360 // when a new message is added to their talk page
2361 if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2362 if ( User::isIP( $shortTitle ) ) {
2363 // An anonymous user
2364 $recipient->setNewtalk( true, $revision );
2365 } elseif ( $recipient->isLoggedIn() ) {
2366 $recipient->setNewtalk( true, $revision );
2367 } else {
2368 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2369 }
2370 }
2371 }
2372 }
2373
2374 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2375 // XXX: could skip pseudo-messages like js/css here, based on content model.
2376 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2377 if ( $msgtext === false || $msgtext === null ) {
2378 $msgtext = '';
2379 }
2380
2381 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2382
2383 if ( $wgContLang->hasVariants() ) {
2384 $wgContLang->updateConversionTable( $this->mTitle );
2385 }
2386 }
2387
2388 if ( $options['created'] ) {
2389 self::onArticleCreate( $this->mTitle );
2390 } elseif ( $options['changed'] ) { // bug 50785
2391 self::onArticleEdit( $this->mTitle, $revision );
2392 }
2393
2394 ResourceLoaderWikiModule::invalidateModuleCache(
2395 $this->mTitle, $options['oldrevision'], $revision, wfWikiID()
2396 );
2397 }
2398
2399 /**
2400 * Update the article's restriction field, and leave a log entry.
2401 * This works for protection both existing and non-existing pages.
2402 *
2403 * @param array $limit Set of restriction keys
2404 * @param array $expiry Per restriction type expiration
2405 * @param int &$cascade Set to false if cascading protection isn't allowed.
2406 * @param string $reason
2407 * @param User $user The user updating the restrictions
2408 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2409 * ($user should be able to add the specified tags before this is called)
2410 * @return Status Status object; if action is taken, $status->value is the log_id of the
2411 * protection log entry.
2412 */
2413 public function doUpdateRestrictions( array $limit, array $expiry,
2414 &$cascade, $reason, User $user, $tags = null
2415 ) {
2416 global $wgCascadingRestrictionLevels, $wgContLang;
2417
2418 if ( wfReadOnly() ) {
2419 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2420 }
2421
2422 $this->loadPageData( 'fromdbmaster' );
2423 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2424 $id = $this->getId();
2425
2426 if ( !$cascade ) {
2427 $cascade = false;
2428 }
2429
2430 // Take this opportunity to purge out expired restrictions
2431 Title::purgeExpiredRestrictions();
2432
2433 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2434 // we expect a single selection, but the schema allows otherwise.
2435 $isProtected = false;
2436 $protect = false;
2437 $changed = false;
2438
2439 $dbw = wfGetDB( DB_MASTER );
2440
2441 foreach ( $restrictionTypes as $action ) {
2442 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2443 $expiry[$action] = 'infinity';
2444 }
2445 if ( !isset( $limit[$action] ) ) {
2446 $limit[$action] = '';
2447 } elseif ( $limit[$action] != '' ) {
2448 $protect = true;
2449 }
2450
2451 // Get current restrictions on $action
2452 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2453 if ( $current != '' ) {
2454 $isProtected = true;
2455 }
2456
2457 if ( $limit[$action] != $current ) {
2458 $changed = true;
2459 } elseif ( $limit[$action] != '' ) {
2460 // Only check expiry change if the action is actually being
2461 // protected, since expiry does nothing on an not-protected
2462 // action.
2463 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2464 $changed = true;
2465 }
2466 }
2467 }
2468
2469 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2470 $changed = true;
2471 }
2472
2473 // If nothing has changed, do nothing
2474 if ( !$changed ) {
2475 return Status::newGood();
2476 }
2477
2478 if ( !$protect ) { // No protection at all means unprotection
2479 $revCommentMsg = 'unprotectedarticle-comment';
2480 $logAction = 'unprotect';
2481 } elseif ( $isProtected ) {
2482 $revCommentMsg = 'modifiedarticleprotection-comment';
2483 $logAction = 'modify';
2484 } else {
2485 $revCommentMsg = 'protectedarticle-comment';
2486 $logAction = 'protect';
2487 }
2488
2489 // Truncate for whole multibyte characters
2490 $reason = $wgContLang->truncate( $reason, 255 );
2491
2492 $logRelationsValues = [];
2493 $logRelationsField = null;
2494 $logParamsDetails = [];
2495
2496 // Null revision (used for change tag insertion)
2497 $nullRevision = null;
2498
2499 if ( $id ) { // Protection of existing page
2500 if ( !Hooks::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2501 return Status::newGood();
2502 }
2503
2504 // Only certain restrictions can cascade...
2505 $editrestriction = isset( $limit['edit'] )
2506 ? [ $limit['edit'] ]
2507 : $this->mTitle->getRestrictions( 'edit' );
2508 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2509 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2510 }
2511 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2512 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2513 }
2514
2515 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2516 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2517 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2518 }
2519 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2520 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2521 }
2522
2523 // The schema allows multiple restrictions
2524 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2525 $cascade = false;
2526 }
2527
2528 // insert null revision to identify the page protection change as edit summary
2529 $latest = $this->getLatest();
2530 $nullRevision = $this->insertProtectNullRevision(
2531 $revCommentMsg,
2532 $limit,
2533 $expiry,
2534 $cascade,
2535 $reason,
2536 $user
2537 );
2538
2539 if ( $nullRevision === null ) {
2540 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2541 }
2542
2543 $logRelationsField = 'pr_id';
2544
2545 // Update restrictions table
2546 foreach ( $limit as $action => $restrictions ) {
2547 $dbw->delete(
2548 'page_restrictions',
2549 [
2550 'pr_page' => $id,
2551 'pr_type' => $action
2552 ],
2553 __METHOD__
2554 );
2555 if ( $restrictions != '' ) {
2556 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2557 $dbw->insert(
2558 'page_restrictions',
2559 [
2560 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2561 'pr_page' => $id,
2562 'pr_type' => $action,
2563 'pr_level' => $restrictions,
2564 'pr_cascade' => $cascadeValue,
2565 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2566 ],
2567 __METHOD__
2568 );
2569 $logRelationsValues[] = $dbw->insertId();
2570 $logParamsDetails[] = [
2571 'type' => $action,
2572 'level' => $restrictions,
2573 'expiry' => $expiry[$action],
2574 'cascade' => (bool)$cascadeValue,
2575 ];
2576 }
2577 }
2578
2579 // Clear out legacy restriction fields
2580 $dbw->update(
2581 'page',
2582 [ 'page_restrictions' => '' ],
2583 [ 'page_id' => $id ],
2584 __METHOD__
2585 );
2586
2587 Hooks::run( 'NewRevisionFromEditComplete',
2588 [ $this, $nullRevision, $latest, $user ] );
2589 Hooks::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2590 } else { // Protection of non-existing page (also known as "title protection")
2591 // Cascade protection is meaningless in this case
2592 $cascade = false;
2593
2594 if ( $limit['create'] != '' ) {
2595 $dbw->replace( 'protected_titles',
2596 [ [ 'pt_namespace', 'pt_title' ] ],
2597 [
2598 'pt_namespace' => $this->mTitle->getNamespace(),
2599 'pt_title' => $this->mTitle->getDBkey(),
2600 'pt_create_perm' => $limit['create'],
2601 'pt_timestamp' => $dbw->timestamp(),
2602 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2603 'pt_user' => $user->getId(),
2604 'pt_reason' => $reason,
2605 ], __METHOD__
2606 );
2607 $logParamsDetails[] = [
2608 'type' => 'create',
2609 'level' => $limit['create'],
2610 'expiry' => $expiry['create'],
2611 ];
2612 } else {
2613 $dbw->delete( 'protected_titles',
2614 [
2615 'pt_namespace' => $this->mTitle->getNamespace(),
2616 'pt_title' => $this->mTitle->getDBkey()
2617 ], __METHOD__
2618 );
2619 }
2620 }
2621
2622 $this->mTitle->flushRestrictions();
2623 InfoAction::invalidateCache( $this->mTitle );
2624
2625 if ( $logAction == 'unprotect' ) {
2626 $params = [];
2627 } else {
2628 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2629 $params = [
2630 '4::description' => $protectDescriptionLog, // parameter for IRC
2631 '5:bool:cascade' => $cascade,
2632 'details' => $logParamsDetails, // parameter for localize and api
2633 ];
2634 }
2635
2636 // Update the protection log
2637 $logEntry = new ManualLogEntry( 'protect', $logAction );
2638 $logEntry->setTarget( $this->mTitle );
2639 $logEntry->setComment( $reason );
2640 $logEntry->setPerformer( $user );
2641 $logEntry->setParameters( $params );
2642 if ( !is_null( $nullRevision ) ) {
2643 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2644 }
2645 $logEntry->setTags( $tags );
2646 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2647 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2648 }
2649 $logId = $logEntry->insert();
2650 $logEntry->publish( $logId );
2651
2652 return Status::newGood( $logId );
2653 }
2654
2655 /**
2656 * Insert a new null revision for this page.
2657 *
2658 * @param string $revCommentMsg Comment message key for the revision
2659 * @param array $limit Set of restriction keys
2660 * @param array $expiry Per restriction type expiration
2661 * @param int $cascade Set to false if cascading protection isn't allowed.
2662 * @param string $reason
2663 * @param User|null $user
2664 * @return Revision|null Null on error
2665 */
2666 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2667 array $expiry, $cascade, $reason, $user = null
2668 ) {
2669 $dbw = wfGetDB( DB_MASTER );
2670
2671 // Prepare a null revision to be added to the history
2672 $editComment = wfMessage(
2673 $revCommentMsg,
2674 $this->mTitle->getPrefixedText(),
2675 $user ? $user->getName() : ''
2676 )->inContentLanguage()->text();
2677 if ( $reason ) {
2678 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2679 }
2680 $protectDescription = $this->protectDescription( $limit, $expiry );
2681 if ( $protectDescription ) {
2682 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2683 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2684 ->inContentLanguage()->text();
2685 }
2686 if ( $cascade ) {
2687 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2688 $editComment .= wfMessage( 'brackets' )->params(
2689 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2690 )->inContentLanguage()->text();
2691 }
2692
2693 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2694 if ( $nullRev ) {
2695 $nullRev->insertOn( $dbw );
2696
2697 // Update page record and touch page
2698 $oldLatest = $nullRev->getParentId();
2699 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2700 }
2701
2702 return $nullRev;
2703 }
2704
2705 /**
2706 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2707 * @return string
2708 */
2709 protected function formatExpiry( $expiry ) {
2710 global $wgContLang;
2711
2712 if ( $expiry != 'infinity' ) {
2713 return wfMessage(
2714 'protect-expiring',
2715 $wgContLang->timeanddate( $expiry, false, false ),
2716 $wgContLang->date( $expiry, false, false ),
2717 $wgContLang->time( $expiry, false, false )
2718 )->inContentLanguage()->text();
2719 } else {
2720 return wfMessage( 'protect-expiry-indefinite' )
2721 ->inContentLanguage()->text();
2722 }
2723 }
2724
2725 /**
2726 * Builds the description to serve as comment for the edit.
2727 *
2728 * @param array $limit Set of restriction keys
2729 * @param array $expiry Per restriction type expiration
2730 * @return string
2731 */
2732 public function protectDescription( array $limit, array $expiry ) {
2733 $protectDescription = '';
2734
2735 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2736 # $action is one of $wgRestrictionTypes = [ 'create', 'edit', 'move', 'upload' ].
2737 # All possible message keys are listed here for easier grepping:
2738 # * restriction-create
2739 # * restriction-edit
2740 # * restriction-move
2741 # * restriction-upload
2742 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2743 # $restrictions is one of $wgRestrictionLevels = [ '', 'autoconfirmed', 'sysop' ],
2744 # with '' filtered out. All possible message keys are listed below:
2745 # * protect-level-autoconfirmed
2746 # * protect-level-sysop
2747 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2748 ->inContentLanguage()->text();
2749
2750 $expiryText = $this->formatExpiry( $expiry[$action] );
2751
2752 if ( $protectDescription !== '' ) {
2753 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2754 }
2755 $protectDescription .= wfMessage( 'protect-summary-desc' )
2756 ->params( $actionText, $restrictionsText, $expiryText )
2757 ->inContentLanguage()->text();
2758 }
2759
2760 return $protectDescription;
2761 }
2762
2763 /**
2764 * Builds the description to serve as comment for the log entry.
2765 *
2766 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2767 * protect description text. Keep them in old format to avoid breaking compatibility.
2768 * TODO: Fix protection log to store structured description and format it on-the-fly.
2769 *
2770 * @param array $limit Set of restriction keys
2771 * @param array $expiry Per restriction type expiration
2772 * @return string
2773 */
2774 public function protectDescriptionLog( array $limit, array $expiry ) {
2775 global $wgContLang;
2776
2777 $protectDescriptionLog = '';
2778
2779 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2780 $expiryText = $this->formatExpiry( $expiry[$action] );
2781 $protectDescriptionLog .= $wgContLang->getDirMark() .
2782 "[$action=$restrictions] ($expiryText)";
2783 }
2784
2785 return trim( $protectDescriptionLog );
2786 }
2787
2788 /**
2789 * Take an array of page restrictions and flatten it to a string
2790 * suitable for insertion into the page_restrictions field.
2791 *
2792 * @param string[] $limit
2793 *
2794 * @throws MWException
2795 * @return string
2796 */
2797 protected static function flattenRestrictions( $limit ) {
2798 if ( !is_array( $limit ) ) {
2799 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2800 }
2801
2802 $bits = [];
2803 ksort( $limit );
2804
2805 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2806 $bits[] = "$action=$restrictions";
2807 }
2808
2809 return implode( ':', $bits );
2810 }
2811
2812 /**
2813 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2814 * backwards compatibility, if you care about error reporting you should use
2815 * doDeleteArticleReal() instead.
2816 *
2817 * Deletes the article with database consistency, writes logs, purges caches
2818 *
2819 * @param string $reason Delete reason for deletion log
2820 * @param bool $suppress Suppress all revisions and log the deletion in
2821 * the suppression log instead of the deletion log
2822 * @param int $u1 Unused
2823 * @param bool $u2 Unused
2824 * @param array|string &$error Array of errors to append to
2825 * @param User $user The deleting user
2826 * @return bool True if successful
2827 */
2828 public function doDeleteArticle(
2829 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2830 ) {
2831 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2832 return $status->isGood();
2833 }
2834
2835 /**
2836 * Back-end article deletion
2837 * Deletes the article with database consistency, writes logs, purges caches
2838 *
2839 * @since 1.19
2840 *
2841 * @param string $reason Delete reason for deletion log
2842 * @param bool $suppress Suppress all revisions and log the deletion in
2843 * the suppression log instead of the deletion log
2844 * @param int $u1 Unused
2845 * @param bool $u2 Unused
2846 * @param array|string &$error Array of errors to append to
2847 * @param User $user The deleting user
2848 * @param array $tags Tags to apply to the deletion action
2849 * @return Status Status object; if successful, $status->value is the log_id of the
2850 * deletion log entry. If the page couldn't be deleted because it wasn't
2851 * found, $status is a non-fatal 'cannotdelete' error
2852 */
2853 public function doDeleteArticleReal(
2854 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2855 $tags = [], $logsubtype = 'delete'
2856 ) {
2857 global $wgUser, $wgContentHandlerUseDB;
2858
2859 wfDebug( __METHOD__ . "\n" );
2860
2861 $status = Status::newGood();
2862
2863 if ( $this->mTitle->getDBkey() === '' ) {
2864 $status->error( 'cannotdelete',
2865 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2866 return $status;
2867 }
2868
2869 $user = is_null( $user ) ? $wgUser : $user;
2870 if ( !Hooks::run( 'ArticleDelete',
2871 [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2872 ) ) {
2873 if ( $status->isOK() ) {
2874 // Hook aborted but didn't set a fatal status
2875 $status->fatal( 'delete-hook-aborted' );
2876 }
2877 return $status;
2878 }
2879
2880 $dbw = wfGetDB( DB_MASTER );
2881 $dbw->startAtomic( __METHOD__ );
2882
2883 $this->loadPageData( self::READ_LATEST );
2884 $id = $this->getId();
2885 // T98706: lock the page from various other updates but avoid using
2886 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2887 // the revisions queries (which also JOIN on user). Only lock the page
2888 // row and CAS check on page_latest to see if the trx snapshot matches.
2889 $lockedLatest = $this->lockAndGetLatest();
2890 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2891 $dbw->endAtomic( __METHOD__ );
2892 // Page not there or trx snapshot is stale
2893 $status->error( 'cannotdelete',
2894 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2895 return $status;
2896 }
2897
2898 // Given the lock above, we can be confident in the title and page ID values
2899 $namespace = $this->getTitle()->getNamespace();
2900 $dbKey = $this->getTitle()->getDBkey();
2901
2902 // At this point we are now comitted to returning an OK
2903 // status unless some DB query error or other exception comes up.
2904 // This way callers don't have to call rollback() if $status is bad
2905 // unless they actually try to catch exceptions (which is rare).
2906
2907 // we need to remember the old content so we can use it to generate all deletion updates.
2908 $revision = $this->getRevision();
2909 try {
2910 $content = $this->getContent( Revision::RAW );
2911 } catch ( Exception $ex ) {
2912 wfLogWarning( __METHOD__ . ': failed to load content during deletion! '
2913 . $ex->getMessage() );
2914
2915 $content = null;
2916 }
2917
2918 $fields = Revision::selectFields();
2919 $bitfield = false;
2920
2921 // Bitfields to further suppress the content
2922 if ( $suppress ) {
2923 $bitfield = Revision::SUPPRESSED_ALL;
2924 $fields = array_diff( $fields, [ 'rev_deleted' ] );
2925 }
2926
2927 // For now, shunt the revision data into the archive table.
2928 // Text is *not* removed from the text table; bulk storage
2929 // is left intact to avoid breaking block-compression or
2930 // immutable storage schemes.
2931 // In the future, we may keep revisions and mark them with
2932 // the rev_deleted field, which is reserved for this purpose.
2933
2934 // Get all of the page revisions
2935 $res = $dbw->select(
2936 'revision',
2937 $fields,
2938 [ 'rev_page' => $id ],
2939 __METHOD__,
2940 'FOR UPDATE'
2941 );
2942 // Build their equivalent archive rows
2943 $rowsInsert = [];
2944 foreach ( $res as $row ) {
2945 $rowInsert = [
2946 'ar_namespace' => $namespace,
2947 'ar_title' => $dbKey,
2948 'ar_comment' => $row->rev_comment,
2949 'ar_user' => $row->rev_user,
2950 'ar_user_text' => $row->rev_user_text,
2951 'ar_timestamp' => $row->rev_timestamp,
2952 'ar_minor_edit' => $row->rev_minor_edit,
2953 'ar_rev_id' => $row->rev_id,
2954 'ar_parent_id' => $row->rev_parent_id,
2955 'ar_text_id' => $row->rev_text_id,
2956 'ar_text' => '',
2957 'ar_flags' => '',
2958 'ar_len' => $row->rev_len,
2959 'ar_page_id' => $id,
2960 'ar_deleted' => $suppress ? $bitfield : $row->rev_deleted,
2961 'ar_sha1' => $row->rev_sha1,
2962 ];
2963 if ( $wgContentHandlerUseDB ) {
2964 $rowInsert['ar_content_model'] = $row->rev_content_model;
2965 $rowInsert['ar_content_format'] = $row->rev_content_format;
2966 }
2967 $rowsInsert[] = $rowInsert;
2968 }
2969 // Copy them into the archive table
2970 $dbw->insert( 'archive', $rowsInsert, __METHOD__ );
2971 // Save this so we can pass it to the ArticleDeleteComplete hook.
2972 $archivedRevisionCount = $dbw->affectedRows();
2973
2974 // Clone the title and wikiPage, so we have the information we need when
2975 // we log and run the ArticleDeleteComplete hook.
2976 $logTitle = clone $this->mTitle;
2977 $wikiPageBeforeDelete