SECURITY: Disallow loading JS/CSS/Json subpages from unregistered users and log
[lhc/web/wiklou.git] / includes / ActorMigration.php
1 <?php
2 /**
3 * Methods to help with the actor table migration
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\MediaWikiServices;
24 use MediaWiki\User\UserIdentity;
25 use Wikimedia\Rdbms\IDatabase;
26
27 /**
28 * This class handles the logic for the actor table migration.
29 *
30 * This is not intended to be a long-term part of MediaWiki; it will be
31 * deprecated and removed along with $wgActorTableSchemaMigrationStage.
32 *
33 * @since 1.31
34 */
35 class ActorMigration {
36
37 /**
38 * Define fields that use temporary tables for transitional purposes
39 * @var array Keys are '$key', values are arrays with four fields:
40 * - table: Temporary table name
41 * - pk: Temporary table column referring to the main table's primary key
42 * - field: Temporary table column referring actor.actor_id
43 * - joinPK: Main table's primary key
44 */
45 private static $tempTables = [
46 'rev_user' => [
47 'table' => 'revision_actor_temp',
48 'pk' => 'revactor_rev',
49 'field' => 'revactor_actor',
50 'joinPK' => 'rev_id',
51 'extra' => [
52 'revactor_timestamp' => 'rev_timestamp',
53 'revactor_page' => 'rev_page',
54 ],
55 ],
56 ];
57
58 /**
59 * Fields that formerly used $tempTables
60 * @var array Key is '$key', value is the MediaWiki version in which it was
61 * removed from $tempTables.
62 */
63 private static $formerTempTables = [];
64
65 /**
66 * Define fields that use non-standard mapping
67 * @var array Keys are the user id column name, values are arrays with two
68 * elements (the user text column name and the actor id column name)
69 */
70 private static $specialFields = [
71 'ipb_by' => [ 'ipb_by_text', 'ipb_by_actor' ],
72 ];
73
74 /** @var array|null Cache for `self::getJoin()` */
75 private $joinCache = null;
76
77 /** @var int One of the MIGRATION_* constants */
78 private $stage;
79
80 /** @private */
81 public function __construct( $stage ) {
82 $this->stage = $stage;
83 }
84
85 /**
86 * Static constructor
87 * @return ActorMigration
88 */
89 public static function newMigration() {
90 return MediaWikiServices::getInstance()->getActorMigration();
91 }
92
93 /**
94 * Return an SQL condition to test if a user field is anonymous
95 * @param string $field Field name or SQL fragment
96 * @return string
97 */
98 public function isAnon( $field ) {
99 return $this->stage === MIGRATION_NEW ? "$field IS NULL" : "$field = 0";
100 }
101
102 /**
103 * Return an SQL condition to test if a user field is non-anonymous
104 * @param string $field Field name or SQL fragment
105 * @return string
106 */
107 public function isNotAnon( $field ) {
108 return $this->stage === MIGRATION_NEW ? "$field IS NOT NULL" : "$field != 0";
109 }
110
111 /**
112 * @param string $key A key such as "rev_user" identifying the actor
113 * field being fetched.
114 * @return string[] [ $text, $actor ]
115 */
116 private static function getFieldNames( $key ) {
117 if ( isset( self::$specialFields[$key] ) ) {
118 return self::$specialFields[$key];
119 }
120
121 return [ $key . '_text', substr( $key, 0, -5 ) . '_actor' ];
122 }
123
124 /**
125 * Get SELECT fields and joins for the actor key
126 *
127 * @param string $key A key such as "rev_user" identifying the actor
128 * field being fetched.
129 * @return array With three keys:
130 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
131 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
132 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
133 * All tables, fields, and joins are aliased, so `+` is safe to use.
134 */
135 public function getJoin( $key ) {
136 if ( !isset( $this->joinCache[$key] ) ) {
137 $tables = [];
138 $fields = [];
139 $joins = [];
140
141 list( $text, $actor ) = self::getFieldNames( $key );
142
143 if ( $this->stage === MIGRATION_OLD ) {
144 $fields[$key] = $key;
145 $fields[$text] = $text;
146 $fields[$actor] = 'NULL';
147 } else {
148 $join = $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN';
149
150 if ( isset( self::$tempTables[$key] ) ) {
151 $t = self::$tempTables[$key];
152 $alias = "temp_$key";
153 $tables[$alias] = $t['table'];
154 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
155 $joinField = "{$alias}.{$t['field']}";
156 } else {
157 $joinField = $actor;
158 }
159
160 $alias = "actor_$key";
161 $tables[$alias] = 'actor';
162 $joins[$alias] = [ $join, "{$alias}.actor_id = {$joinField}" ];
163
164 if ( $this->stage === MIGRATION_NEW ) {
165 $fields[$key] = "{$alias}.actor_user";
166 $fields[$text] = "{$alias}.actor_name";
167 } else {
168 $fields[$key] = "COALESCE( {$alias}.actor_user, $key )";
169 $fields[$text] = "COALESCE( {$alias}.actor_name, $text )";
170 }
171 $fields[$actor] = $joinField;
172 }
173
174 $this->joinCache[$key] = [
175 'tables' => $tables,
176 'fields' => $fields,
177 'joins' => $joins,
178 ];
179 }
180
181 return $this->joinCache[$key];
182 }
183
184 /**
185 * Get UPDATE fields for the actor
186 *
187 * @param IDatabase $dbw Database to use for creating an actor ID, if necessary
188 * @param string $key A key such as "rev_user" identifying the actor
189 * field being fetched.
190 * @param UserIdentity $user User to set in the update
191 * @return array to merge into `$values` to `IDatabase->update()` or `$a` to `IDatabase->insert()`
192 */
193 public function getInsertValues( IDatabase $dbw, $key, UserIdentity $user ) {
194 if ( isset( self::$tempTables[$key] ) ) {
195 throw new InvalidArgumentException( "Must use getInsertValuesWithTempTable() for $key" );
196 }
197
198 list( $text, $actor ) = self::getFieldNames( $key );
199 $ret = [];
200 if ( $this->stage <= MIGRATION_WRITE_BOTH ) {
201 $ret[$key] = $user->getId();
202 $ret[$text] = $user->getName();
203 }
204 if ( $this->stage >= MIGRATION_WRITE_BOTH ) {
205 // We need to be able to assign an actor ID if none exists
206 if ( !$user instanceof User && !$user->getActorId() ) {
207 $user = User::newFromAnyId( $user->getId(), $user->getName(), null );
208 }
209 $ret[$actor] = $user->getActorId( $dbw );
210 }
211 return $ret;
212 }
213
214 /**
215 * Get UPDATE fields for the actor
216 *
217 * @param IDatabase $dbw Database to use for creating an actor ID, if necessary
218 * @param string $key A key such as "rev_user" identifying the actor
219 * field being fetched.
220 * @param UserIdentity $user User to set in the update
221 * @return array with two values:
222 * - array to merge into `$values` to `IDatabase->update()` or `$a` to `IDatabase->insert()`
223 * - callback to call with the the primary key for the main table insert
224 * and extra fields needed for the temp table.
225 */
226 public function getInsertValuesWithTempTable( IDatabase $dbw, $key, UserIdentity $user ) {
227 if ( isset( self::$formerTempTables[$key] ) ) {
228 wfDeprecated( __METHOD__ . " for $key", self::$formerTempTables[$key] );
229 } elseif ( !isset( self::$tempTables[$key] ) ) {
230 throw new InvalidArgumentException( "Must use getInsertValues() for $key" );
231 }
232
233 list( $text, $actor ) = self::getFieldNames( $key );
234 $ret = [];
235 $callback = null;
236 if ( $this->stage <= MIGRATION_WRITE_BOTH ) {
237 $ret[$key] = $user->getId();
238 $ret[$text] = $user->getName();
239 }
240 if ( $this->stage >= MIGRATION_WRITE_BOTH ) {
241 // We need to be able to assign an actor ID if none exists
242 if ( !$user instanceof User && !$user->getActorId() ) {
243 $user = User::newFromAnyId( $user->getId(), $user->getName(), null );
244 }
245 $id = $user->getActorId( $dbw );
246
247 if ( isset( self::$tempTables[$key] ) ) {
248 $func = __METHOD__;
249 $callback = function ( $pk, array $extra ) use ( $dbw, $key, $id, $func ) {
250 $t = self::$tempTables[$key];
251 $set = [ $t['field'] => $id ];
252 foreach ( $t['extra'] as $to => $from ) {
253 if ( !array_key_exists( $from, $extra ) ) {
254 throw new InvalidArgumentException( "$func callback: \$extra[$from] is not provided" );
255 }
256 $set[$to] = $extra[$from];
257 }
258 $dbw->upsert(
259 $t['table'],
260 [ $t['pk'] => $pk ] + $set,
261 [ $t['pk'] ],
262 $set,
263 $func
264 );
265 };
266 } else {
267 $ret[$actor] = $id;
268 $callback = function ( $pk, array $extra ) {
269 };
270 }
271 } elseif ( isset( self::$tempTables[$key] ) ) {
272 $func = __METHOD__;
273 $callback = function ( $pk, array $extra ) use ( $key, $func ) {
274 $t = self::$tempTables[$key];
275 foreach ( $t['extra'] as $to => $from ) {
276 if ( !array_key_exists( $from, $extra ) ) {
277 throw new InvalidArgumentException( "$func callback: \$extra[$from] is not provided" );
278 }
279 }
280 };
281 } else {
282 $callback = function ( $pk, array $extra ) {
283 };
284 }
285 return [ $ret, $callback ];
286 }
287
288 /**
289 * Get WHERE condition for the actor
290 *
291 * @param IDatabase $db Database to use for quoting and list-making
292 * @param string $key A key such as "rev_user" identifying the actor
293 * field being fetched.
294 * @param UserIdentity|UserIdentity[] $users Users to test for
295 * @param bool $useId If false, don't try to query by the user ID.
296 * Intended for use with rc_user since it has an index on
297 * (rc_user_text,rc_timestamp) but not (rc_user,rc_timestamp).
298 * @return array With three keys:
299 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
300 * - conds: (string) to include in the `$cond` to `IDatabase->select()`
301 * - orconds: (array[]) array of alternatives in case a union of multiple
302 * queries would be more efficient than a query with OR. May have keys
303 * 'actor', 'userid', 'username'.
304 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
305 * All tables and joins are aliased, so `+` is safe to use.
306 */
307 public function getWhere( IDatabase $db, $key, $users, $useId = true ) {
308 $tables = [];
309 $conds = [];
310 $joins = [];
311
312 if ( $users instanceof UserIdentity ) {
313 $users = [ $users ];
314 }
315
316 // Get information about all the passed users
317 $ids = [];
318 $names = [];
319 $actors = [];
320 foreach ( $users as $user ) {
321 if ( $useId && $user->getId() ) {
322 $ids[] = $user->getId();
323 } else {
324 $names[] = $user->getName();
325 }
326 $actorId = $user->getActorId();
327 if ( $actorId ) {
328 $actors[] = $actorId;
329 }
330 }
331
332 list( $text, $actor ) = self::getFieldNames( $key );
333
334 // Combine data into conditions to be ORed together
335 $actorNotEmpty = [];
336 if ( $this->stage === MIGRATION_OLD ) {
337 $actors = [];
338 $actorEmpty = [];
339 } elseif ( isset( self::$tempTables[$key] ) ) {
340 $t = self::$tempTables[$key];
341 $alias = "temp_$key";
342 $tables[$alias] = $t['table'];
343 $joins[$alias] = [
344 $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN',
345 "{$alias}.{$t['pk']} = {$t['joinPK']}"
346 ];
347 $joinField = "{$alias}.{$t['field']}";
348 $actorEmpty = [ $joinField => null ];
349 if ( $this->stage !== MIGRATION_NEW ) {
350 // Otherwise the resulting test can evaluate to NULL, and
351 // NOT(NULL) is NULL rather than true.
352 $actorNotEmpty = [ "$joinField IS NOT NULL" ];
353 }
354 } else {
355 $joinField = $actor;
356 $actorEmpty = [ $joinField => 0 ];
357 }
358
359 if ( $actors ) {
360 $conds['actor'] = $db->makeList(
361 $actorNotEmpty + [ $joinField => $actors ], IDatabase::LIST_AND
362 );
363 }
364 if ( $this->stage < MIGRATION_NEW && $ids ) {
365 $conds['userid'] = $db->makeList(
366 $actorEmpty + [ $key => $ids ], IDatabase::LIST_AND
367 );
368 }
369 if ( $this->stage < MIGRATION_NEW && $names ) {
370 $conds['username'] = $db->makeList(
371 $actorEmpty + [ $text => $names ], IDatabase::LIST_AND
372 );
373 }
374
375 return [
376 'tables' => $tables,
377 'conds' => $conds ? $db->makeList( array_values( $conds ), IDatabase::LIST_OR ) : '1=0',
378 'orconds' => $conds,
379 'joins' => $joins,
380 ];
381 }
382
383 }