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