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