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