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