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