Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / jobqueue / jobs / CategoryMembershipChangeJob.php
bloba52ff065b0c3a4decd46be99f801fd7da23c8fed
1 <?php
2 /**
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
20 * @file
22 use MediaWiki\MediaWikiServices;
24 /**
25 * Job to add recent change entries mentioning category membership changes
27 * Parameters include:
28 * - pageId : page ID
29 * - revTimestamp : timestamp of the triggering revision
31 * Category changes will be mentioned for revisions at/after the timestamp for this page
33 * @since 1.27
35 class CategoryMembershipChangeJob extends Job {
36 /** @var integer|null */
37 private $ticket;
39 const ENQUEUE_FUDGE_SEC = 60;
41 public function __construct( Title $title, array $params ) {
42 parent::__construct( 'categoryMembershipChange', $title, $params );
43 // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
44 // older revision job gets inserted while the newer revision job is de-duplicated.
45 $this->removeDuplicates = true;
48 public function run() {
49 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
50 $lb = $lbFactory->getMainLB();
51 $dbw = $lb->getConnection( DB_MASTER );
53 $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
55 $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
56 if ( !$page ) {
57 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
58 return false; // deleted?
61 // Use a named lock so that jobs for this page see each others' changes
62 $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
63 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
64 if ( !$scopedLock ) {
65 $this->setLastError( "Could not acquire lock '$lockKey'" );
66 return false;
69 $dbr = $lb->getConnection( DB_REPLICA, [ 'recentchanges' ] );
70 // Wait till the replica DB is caught up so that jobs for this page see each others' changes
71 if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
72 $this->setLastError( "Timed out while waiting for replica DB to catch up" );
73 return false;
75 // Clear any stale REPEATABLE-READ snapshot
76 $dbr->flushSnapshot( __METHOD__ );
78 $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
79 // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
80 // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
81 $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
83 // Get the newest revision that has a SRC_CATEGORIZE row...
84 $row = $dbr->selectRow(
85 [ 'revision', 'recentchanges' ],
86 [ 'rev_timestamp', 'rev_id' ],
88 'rev_page' => $page->getId(),
89 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) )
91 __METHOD__,
92 [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ],
94 'recentchanges' => [
95 'INNER JOIN',
97 'rc_this_oldid = rev_id',
98 'rc_source' => RecentChange::SRC_CATEGORIZE,
99 // Allow rc_cur_id or rc_timestamp index usage
100 'rc_cur_id = rev_page',
101 'rc_timestamp >= rev_timestamp'
106 // Only consider revisions newer than any such revision
107 if ( $row ) {
108 $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
109 $lastRevId = (int)$row->rev_id;
110 } else {
111 $lastRevId = 0;
114 // Find revisions to this page made around and after this revision which lack category
115 // notifications in recent changes. This lets jobs pick up were the last one left off.
116 $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
117 $res = $dbr->select(
118 'revision',
119 Revision::selectFields(),
121 'rev_page' => $page->getId(),
122 "rev_timestamp > $encCutoff" .
123 " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
125 __METHOD__,
126 [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ]
129 // Apply all category updates in revision timestamp order
130 foreach ( $res as $row ) {
131 $this->notifyUpdatesForRevision( $lbFactory, $page, Revision::newFromRow( $row ) );
134 return true;
138 * @param LBFactory $lbFactory
139 * @param WikiPage $page
140 * @param Revision $newRev
141 * @throws MWException
143 protected function notifyUpdatesForRevision(
144 LBFactory $lbFactory, WikiPage $page, Revision $newRev
146 $config = RequestContext::getMain()->getConfig();
147 $title = $page->getTitle();
149 // Get the new revision
150 if ( !$newRev->getContent() ) {
151 return; // deleted?
154 // Get the prior revision (the same for null edits)
155 if ( $newRev->getParentId() ) {
156 $oldRev = Revision::newFromId( $newRev->getParentId(), Revision::READ_LATEST );
157 if ( !$oldRev->getContent() ) {
158 return; // deleted?
160 } else {
161 $oldRev = null;
164 // Parse the new revision and get the categories
165 $categoryChanges = $this->getExplicitCategoriesChanges( $title, $newRev, $oldRev );
166 list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
167 if ( !$categoryInserts && !$categoryDeletes ) {
168 return; // nothing to do
171 $catMembChange = new CategoryMembershipChange( $title, $newRev );
172 $catMembChange->checkTemplateLinks();
174 $batchSize = $config->get( 'UpdateRowsPerQuery' );
175 $insertCount = 0;
177 foreach ( $categoryInserts as $categoryName ) {
178 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
179 $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
180 if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
181 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
185 foreach ( $categoryDeletes as $categoryName ) {
186 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
187 $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
188 if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
189 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
194 private function getExplicitCategoriesChanges(
195 Title $title, Revision $newRev, Revision $oldRev = null
197 // Inject the same timestamp for both revision parses to avoid seeing category changes
198 // due to time-based parser functions. Inject the same page title for the parses too.
199 // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
200 $parseTimestamp = $newRev->getTimestamp();
201 // Parse the old rev and get the categories. Do not use link tables as that
202 // assumes these updates are perfectly FIFO and that link tables are always
203 // up to date, neither of which are true.
204 $oldCategories = $oldRev
205 ? $this->getCategoriesAtRev( $title, $oldRev, $parseTimestamp )
206 : [];
207 // Parse the new revision and get the categories
208 $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
210 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
211 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
213 return [ $categoryInserts, $categoryDeletes ];
217 * @param Title $title
218 * @param Revision $rev
219 * @param string $parseTimestamp TS_MW
221 * @return string[] category names
223 private function getCategoriesAtRev( Title $title, Revision $rev, $parseTimestamp ) {
224 $content = $rev->getContent();
225 $options = $content->getContentHandler()->makeParserOptions( 'canonical' );
226 $options->setTimestamp( $parseTimestamp );
227 // This could possibly use the parser cache if it checked the revision ID,
228 // but that's more complicated than it's worth.
229 $output = $content->getParserOutput( $title, $rev->getId(), $options );
231 // array keys will cast numeric category names to ints
232 // so we need to cast them back to strings to avoid breaking things!
233 return array_map( 'strval', array_keys( $output->getCategories() ) );
236 public function getDeduplicationInfo() {
237 $info = parent::getDeduplicationInfo();
238 unset( $info['params']['revTimestamp'] ); // first job wins
240 return $info;