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