Ensure users are able to edit the page after changing the content model
[lhc/web/wiklou.git] / includes / jobqueue / jobs / CategoryMembershipChangeJob.php
1 <?php
2 /**
3 * Updater for link tracking tables after a page edit.
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 use MediaWiki\MediaWikiServices;
23
24 /**
25 * Job to add recent change entries mentioning category membership changes
26 *
27 * Parameters include:
28 * - pageId : page ID
29 * - revTimestamp : timestamp of the triggering revision
30 *
31 * Category changes will be mentioned for revisions at/after the timestamp for this page
32 *
33 * @since 1.27
34 */
35 class CategoryMembershipChangeJob extends Job {
36 const ENQUEUE_FUDGE_SEC = 60;
37
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;
43 }
44
45 public function run() {
46 $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
47 if ( !$page ) {
48 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
49 return false; // deleted?
50 }
51
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 );
57 if ( !$scopedLock ) {
58 $this->setLastError( "Could not acquire lock '$lockKey'" );
59 return false;
60 }
61
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" );
66 return false;
67 }
68 // Clear any stale REPEATABLE-READ snapshot
69 $dbr->flushSnapshot( __METHOD__ );
70
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;
75
76 // Get the newest revision that has a SRC_CATEGORIZE row...
77 $row = $dbr->selectRow(
78 [ 'revision', 'recentchanges' ],
79 [ 'rev_timestamp', 'rev_id' ],
80 [
81 'rev_page' => $page->getId(),
82 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) )
83 ],
84 __METHOD__,
85 [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ],
86 [
87 'recentchanges' => [
88 'INNER JOIN',
89 [
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'
95 ]
96 ]
97 ]
98 );
99 // Only consider revisions newer than any such revision
100 if ( $row ) {
101 $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
102 $lastRevId = (int)$row->rev_id;
103 } else {
104 $lastRevId = 0;
105 }
106
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 ) );
110 $res = $dbr->select(
111 'revision',
112 Revision::selectFields(),
113 [
114 'rev_page' => $page->getId(),
115 "rev_timestamp > $encCutoff" .
116 " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
117 ],
118 __METHOD__,
119 [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ]
120 );
121
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 ) );
126 }
127
128 return true;
129 }
130
131 /**
132 * @param LBFactory $lbFactory
133 * @param WikiPage $page
134 * @param Revision $newRev
135 * @throws MWException
136 */
137 protected function notifyUpdatesForRevision(
138 LBFactory $lbFactory, WikiPage $page, Revision $newRev
139 ) {
140 $config = RequestContext::getMain()->getConfig();
141 $title = $page->getTitle();
142
143 // Get the new revision
144 if ( !$newRev->getContent() ) {
145 return; // deleted?
146 }
147
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() ) {
152 return; // deleted?
153 }
154 } else {
155 $oldRev = null;
156 }
157
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
163 }
164
165 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
166
167 $catMembChange = new CategoryMembershipChange( $title, $newRev );
168 $catMembChange->checkTemplateLinks();
169
170 $batchSize = $config->get( 'UpdateRowsPerQuery' );
171 $insertCount = 0;
172
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 );
178 }
179 }
180
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 );
186 }
187 }
188 }
189
190 private function getExplicitCategoriesChanges(
191 Title $title, Revision $newRev, Revision $oldRev = null
192 ) {
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 )
202 : [];
203 // Parse the new revision and get the categories
204 $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
205
206 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
207 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
208
209 return [ $categoryInserts, $categoryDeletes ];
210 }
211
212 /**
213 * @param Title $title
214 * @param Revision $rev
215 * @param string $parseTimestamp TS_MW
216 *
217 * @return string[] category names
218 */
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 );
226
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() ) );
230 }
231
232 public function getDeduplicationInfo() {
233 $info = parent::getDeduplicationInfo();
234 unset( $info['params']['revTimestamp'] ); // first job wins
235
236 return $info;
237 }
238 }