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