3 * Updater for link tracking tables after a page edit.
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.
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.
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
22 use MediaWiki\MediaWikiServices
;
25 * Job to add recent change entries mentioning category membership changes
29 * - revTimestamp : timestamp of the triggering revision
31 * Category changes will be mentioned for revisions at/after the timestamp for this page
35 class CategoryMembershipChangeJob
extends Job
{
36 const ENQUEUE_FUDGE_SEC
= 60;
38 public function __construct( Title
$title, array $params ) {
39 parent
::__construct( 'categoryMembershipChange', $title, $params );
40 // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
41 // older revision job gets inserted while the newer revision job is de-duplicated.
42 $this->removeDuplicates
= true;
45 public function run() {
46 $page = WikiPage
::newFromID( $this->params
['pageId'], WikiPage
::READ_LATEST
);
48 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
49 return false; // deleted?
52 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
53 $dbw = $lb->getConnection( DB_MASTER
);
54 // Use a named lock so that jobs for this page see each others' changes
55 $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
56 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__
, 10 );
58 $this->setLastError( "Could not acquire lock '$lockKey'" );
62 $dbr = wfGetDB( DB_REPLICA
, [ 'recentchanges' ] );
63 // Wait till the replica DB is caught up so that jobs for this page see each others' changes
64 if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
65 $this->setLastError( "Timed out while waiting for replica DB to catch up" );
68 // Clear any stale REPEATABLE-READ snapshot
69 $dbr->flushSnapshot( __METHOD__
);
71 $cutoffUnix = wfTimestamp( TS_UNIX
, $this->params
['revTimestamp'] );
72 // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
73 // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
74 $cutoffUnix -= self
::ENQUEUE_FUDGE_SEC
;
76 // Get the newest revision that has a SRC_CATEGORIZE row...
77 $row = $dbr->selectRow(
78 [ 'revision', 'recentchanges' ],
79 [ 'rev_timestamp', 'rev_id' ],
81 'rev_page' => $page->getId(),
82 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) )
85 [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ],
90 'rc_this_oldid = rev_id',
91 'rc_source' => RecentChange
::SRC_CATEGORIZE
,
92 // Allow rc_cur_id or rc_timestamp index usage
93 'rc_cur_id = rev_page',
94 'rc_timestamp >= rev_timestamp'
99 // Only consider revisions newer than any such revision
101 $cutoffUnix = wfTimestamp( TS_UNIX
, $row->rev_timestamp
);
102 $lastRevId = (int)$row->rev_id
;
107 // Find revisions to this page made around and after this revision which lack category
108 // notifications in recent changes. This lets jobs pick up were the last one left off.
109 $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
112 Revision
::selectFields(),
114 'rev_page' => $page->getId(),
115 "rev_timestamp > $encCutoff" .
116 " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
119 [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ]
122 // Apply all category updates in revision timestamp order
123 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
124 foreach ( $res as $row ) {
125 $this->notifyUpdatesForRevision( $lbFactory, $page, Revision
::newFromRow( $row ) );
132 * @param LBFactory $lbFactory
133 * @param WikiPage $page
134 * @param Revision $newRev
135 * @throws MWException
137 protected function notifyUpdatesForRevision(
138 LBFactory
$lbFactory, WikiPage
$page, Revision
$newRev
140 $config = RequestContext
::getMain()->getConfig();
141 $title = $page->getTitle();
143 // Get the new revision
144 if ( !$newRev->getContent() ) {
148 // Get the prior revision (the same for null edits)
149 if ( $newRev->getParentId() ) {
150 $oldRev = Revision
::newFromId( $newRev->getParentId(), Revision
::READ_LATEST
);
151 if ( !$oldRev->getContent() ) {
158 // Parse the new revision and get the categories
159 $categoryChanges = $this->getExplicitCategoriesChanges( $title, $newRev, $oldRev );
160 list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
161 if ( !$categoryInserts && !$categoryDeletes ) {
162 return; // nothing to do
165 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
167 $catMembChange = new CategoryMembershipChange( $title, $newRev );
168 $catMembChange->checkTemplateLinks();
170 $batchSize = $config->get( 'UpdateRowsPerQuery' );
173 foreach ( $categoryInserts as $categoryName ) {
174 $categoryTitle = Title
::makeTitle( NS_CATEGORY
, $categoryName );
175 $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
176 if ( $insertCount++
&& ( $insertCount %
$batchSize ) == 0 ) {
177 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
181 foreach ( $categoryDeletes as $categoryName ) {
182 $categoryTitle = Title
::makeTitle( NS_CATEGORY
, $categoryName );
183 $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
184 if ( $insertCount++
&& ( $insertCount++ %
$batchSize ) == 0 ) {
185 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
190 private function getExplicitCategoriesChanges(
191 Title
$title, Revision
$newRev, Revision
$oldRev = null
193 // Inject the same timestamp for both revision parses to avoid seeing category changes
194 // due to time-based parser functions. Inject the same page title for the parses too.
195 // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
196 $parseTimestamp = $newRev->getTimestamp();
197 // Parse the old rev and get the categories. Do not use link tables as that
198 // assumes these updates are perfectly FIFO and that link tables are always
199 // up to date, neither of which are true.
200 $oldCategories = $oldRev
201 ?
$this->getCategoriesAtRev( $title, $oldRev, $parseTimestamp )
203 // Parse the new revision and get the categories
204 $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
206 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
207 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
209 return [ $categoryInserts, $categoryDeletes ];
213 * @param Title $title
214 * @param Revision $rev
215 * @param string $parseTimestamp TS_MW
217 * @return string[] category names
219 private function getCategoriesAtRev( Title
$title, Revision
$rev, $parseTimestamp ) {
220 $content = $rev->getContent();
221 $options = $content->getContentHandler()->makeParserOptions( 'canonical' );
222 $options->setTimestamp( $parseTimestamp );
223 // This could possibly use the parser cache if it checked the revision ID,
224 // but that's more complicated than it's worth.
225 $output = $content->getParserOutput( $title, $rev->getId(), $options );
227 // array keys will cast numeric category names to ints
228 // so we need to cast them back to strings to avoid breaking things!
229 return array_map( 'strval', array_keys( $output->getCategories() ) );
232 public function getDeduplicationInfo() {
233 $info = parent
::getDeduplicationInfo();
234 unset( $info['params']['revTimestamp'] ); // first job wins