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