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