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