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