Debian Codegraph @

includes/Rest/Handler/PageHistoryHandler.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Rest\Handler;
4
5 use ChangeTags;
6 use MediaWiki\Page\ExistingPageRecord;
7 use MediaWiki\Page\PageLookup;
8 use MediaWiki\Permissions\GroupPermissionsLookup;
9 use MediaWiki\Rest\Handler\Helper\PageRedirectHelper;
10 use MediaWiki\Rest\Handler\Helper\PageRestHelperFactory;
11 use MediaWiki\Rest\LocalizedHttpException;
12 use MediaWiki\Rest\Response;
13 use MediaWiki\Rest\SimpleHandler;
14 use MediaWiki\Revision\RevisionRecord;
15 use MediaWiki\Revision\RevisionStore;
16 use MediaWiki\Storage\NameTableAccessException;
17 use MediaWiki\Storage\NameTableStore;
18 use MediaWiki\Storage\NameTableStoreFactory;
19 use MediaWiki\Title\TitleFormatter;
20 use Wikimedia\Message\MessageValue;
21 use Wikimedia\Message\ParamType;
22 use Wikimedia\Message\ScalarParam;
23 use Wikimedia\ParamValidator\ParamValidator;
24 use Wikimedia\Rdbms\IConnectionProvider;
25 use Wikimedia\Rdbms\IDBAccessObject;
26 use Wikimedia\Rdbms\IResultWrapper;
27 use Wikimedia\Rdbms\RawSQLExpression;
28
29 /**
30 * Handler class for Core REST API endpoints that perform operations on revisions
31 */
32 class PageHistoryHandler extends SimpleHandler {
33
34 private const REVISIONS_RETURN_LIMIT = 20;
35 private const ALLOWED_FILTER_TYPES = [ 'anonymous', 'bot', 'reverted', 'minor' ];
36
37 private RevisionStore $revisionStore;
38 private NameTableStore $changeTagDefStore;
39 private GroupPermissionsLookup $groupPermissionsLookup;
40 private IConnectionProvider $dbProvider;
41 private PageLookup $pageLookup;
42 private TitleFormatter $titleFormatter;
43 private PageRestHelperFactory $helperFactory;
44
45 /**
46 * @var ExistingPageRecord|false|null
47 */
48 private $page = false;
49
50 /**
51 * RevisionStore $revisionStore
52 *
53 * @param RevisionStore $revisionStore
54 * @param NameTableStoreFactory $nameTableStoreFactory
55 * @param GroupPermissionsLookup $groupPermissionsLookup
56 * @param IConnectionProvider $dbProvider
57 * @param PageLookup $pageLookup
58 * @param TitleFormatter $titleFormatter
59 * @param PageRestHelperFactory $helperFactory
60 */
61 public function __construct(
62 RevisionStore $revisionStore,
63 NameTableStoreFactory $nameTableStoreFactory,
64 GroupPermissionsLookup $groupPermissionsLookup,
65 IConnectionProvider $dbProvider,
66 PageLookup $pageLookup,
67 TitleFormatter $titleFormatter,
68 PageRestHelperFactory $helperFactory
69 ) {
70 $this->revisionStore = $revisionStore;
71 $this->changeTagDefStore = $nameTableStoreFactory->getChangeTagDef();
72 $this->groupPermissionsLookup = $groupPermissionsLookup;
73 $this->dbProvider = $dbProvider;
74 $this->pageLookup = $pageLookup;
75 $this->titleFormatter = $titleFormatter;
76 $this->helperFactory = $helperFactory;
77 }
78
79 private function getRedirectHelper(): PageRedirectHelper {
80 return $this->helperFactory->newPageRedirectHelper(
81 $this->getResponseFactory(),
82 $this->getRouter(),
83 $this->getPath(),
84 $this->getRequest()
85 );
86 }
87
88 /**
89 * @return ExistingPageRecord|null
90 */
91 private function getPage(): ?ExistingPageRecord {
92 if ( $this->page === false ) {
93 $this->page = $this->pageLookup->getExistingPageByText(
94 $this->getValidatedParams()['title']
95 );
96 }
97 return $this->page;
98 }
99
100 /**
101 * At most one of older_than and newer_than may be specified. Keep in mind that revision ids
102 * are not monotonically increasing, so a revision may be older than another but have a
103 * higher revision id.
104 *
105 * @param string $title
106 * @return Response
107 * @throws LocalizedHttpException
108 */
109 public function run( $title ) {
110 $params = $this->getValidatedParams();
111 if ( $params['older_than'] !== null && $params['newer_than'] !== null ) {
112 throw new LocalizedHttpException(
113 new MessageValue( 'rest-pagehistory-incompatible-params' ), 400 );
114 }
115
116 if ( ( $params['older_than'] !== null && $params['older_than'] < 1 ) ||
117 ( $params['newer_than'] !== null && $params['newer_than'] < 1 )
118 ) {
119 throw new LocalizedHttpException(
120 new MessageValue( 'rest-pagehistory-param-range-error' ), 400 );
121 }
122
123 $tagIds = [];
124 if ( $params['filter'] === 'reverted' ) {
125 foreach ( ChangeTags::REVERT_TAGS as $tagName ) {
126 try {
127 $tagIds[] = $this->changeTagDefStore->getId( $tagName );
128 } catch ( NameTableAccessException $exception ) {
129 // If no revisions are tagged with a name, no tag id will be present
130 }
131 }
132 }
133
134 $page = $this->getPage();
135
136 if ( !$page ) {
137 throw new LocalizedHttpException(
138 new MessageValue( 'rest-nonexistent-title',
139 [ new ScalarParam( ParamType::PLAINTEXT, $title ) ]
140 ),
141 404
142 );
143 }
144 if ( !$this->getAuthority()->authorizeRead( 'read', $page ) ) {
145 throw new LocalizedHttpException(
146 new MessageValue( 'rest-permission-denied-title',
147 [ new ScalarParam( ParamType::PLAINTEXT, $title ) ] ),
148 403
149 );
150 }
151
152 '@phan-var \MediaWiki\Page\ExistingPageRecord $page';
153 $redirectResponse = $this->getRedirectHelper()->createNormalizationRedirectResponseIfNeeded(
154 $page,
155 $params['title'] ?? null
156 );
157
158 if ( $redirectResponse !== null ) {
159 return $redirectResponse;
160 }
161
162 $relativeRevId = $params['older_than'] ?? $params['newer_than'] ?? 0;
163 if ( $relativeRevId ) {
164 // Confirm the relative revision exists for this page. If so, get its timestamp.
165 $rev = $this->revisionStore->getRevisionByPageId(
166 $page->getId(),
167 $relativeRevId
168 );
169 if ( !$rev ) {
170 throw new LocalizedHttpException(
171 new MessageValue( 'rest-nonexistent-title-revision',
172 [ $relativeRevId, new ScalarParam( ParamType::PLAINTEXT, $title ) ]
173 ),
174 404
175 );
176 }
177 $ts = $rev->getTimestamp();
178 if ( $ts === null ) {
179 throw new LocalizedHttpException(
180 new MessageValue( 'rest-pagehistory-timestamp-error',
181 [ $relativeRevId ]
182 ),
183 500
184 );
185 }
186 } else {
187 $ts = 0;
188 }
189
190 $res = $this->getDbResults( $page, $params, $relativeRevId, $ts, $tagIds );
191 $response = $this->processDbResults( $res, $page, $params );
192 return $this->getResponseFactory()->createJson( $response );
193 }
194
195 /**
196 * @param ExistingPageRecord $page object identifying the page to load history for
197 * @param array $params request parameters
198 * @param int $relativeRevId relative revision id for paging, or zero if none
199 * @param int $ts timestamp for paging, or zero if none
200 * @param array $tagIds validated tags ids, or empty array if not needed for this query
201 * @return IResultWrapper|bool the results, or false if no query was executed
202 */
203 private function getDbResults( ExistingPageRecord $page, array $params, $relativeRevId, $ts, $tagIds ) {
204 $dbr = $this->dbProvider->getReplicaDatabase();
205 $queryBuilder = $this->revisionStore->newSelectQueryBuilder( $dbr )
206 ->joinComment()
207 ->where( [ 'rev_page' => $page->getId() ] )
208 // Select one more than the return limit, to learn if there are additional revisions.
209 ->limit( self::REVISIONS_RETURN_LIMIT + 1 );
210
211 if ( $params['filter'] ) {
212 // The validator ensures this value, if present, is one of the expected values
213 switch ( $params['filter'] ) {
214 case 'bot':
215 $subquery = $queryBuilder->newSubquery()
216 ->select( '1' )
217 ->from( 'user_groups' )
218 ->where( [
219 'actor_rev_user.actor_user = ug_user',
220 'ug_group' => $this->groupPermissionsLookup->getGroupsWithPermission( 'bot' ),
221 $dbr->expr( 'ug_expiry', '=', null )->or( 'ug_expiry', '>=', $dbr->timestamp() )
222 ] );
223 $queryBuilder->andWhere( new RawSQLExpression( 'EXISTS(' . $subquery->getSQL() . ')' ) );
224 $bitmask = $this->getBitmask();
225 if ( $bitmask ) {
226 $queryBuilder->andWhere( $dbr->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
227 }
228 break;
229
230 case 'anonymous':
231 $queryBuilder->andWhere( [ 'actor_user' => null ] );
232 $bitmask = $this->getBitmask();
233 if ( $bitmask ) {
234 $queryBuilder->andWhere( $dbr->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
235 }
236 break;
237
238 case 'reverted':
239 if ( !$tagIds ) {
240 return false;
241 }
242 $subquery = $queryBuilder->newSubquery()
243 ->select( '1' )
244 ->from( 'change_tag' )
245 ->where( [ 'ct_rev_id = rev_id', 'ct_tag_id' => $tagIds ] );
246 $queryBuilder->andWhere( new RawSQLExpression( 'EXISTS(' . $subquery->getSQL() . ')' ) );
247 break;
248
249 case 'minor':
250 $queryBuilder->andWhere( $dbr->expr( 'rev_minor_edit', '!=', 0 ) );
251 break;
252 }
253 }
254
255 if ( $relativeRevId ) {
256 $op = $params['older_than'] ? '<' : '>';
257 $sort = $params['older_than'] ? 'DESC' : 'ASC';
258 $queryBuilder->andWhere( $dbr->buildComparison( $op, [
259 'rev_timestamp' => $dbr->timestamp( $ts ),
260 'rev_id' => $relativeRevId,
261 ] ) );
262 $queryBuilder->orderBy( [ 'rev_timestamp', 'rev_id' ], $sort );
263 } else {
264 $queryBuilder->orderBy( [ 'rev_timestamp', 'rev_id' ], 'DESC' );
265 }
266
267 return $queryBuilder->caller( __METHOD__ )->fetchResultSet();
268 }
269
270 /**
271 * Helper function for rev_deleted/user rights query conditions
272 *
273 * @todo Factor out rev_deleted logic per T233222
274 *
275 * @return int
276 */
277 private function getBitmask() {
278 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
279 $bitmask = RevisionRecord::DELETED_USER;
280 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
281 $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
282 } else {
283 $bitmask = 0;
284 }
285 return $bitmask;
286 }
287
288 /**
289 * @param IResultWrapper|bool $res database results, or false if no query was executed
290 * @param ExistingPageRecord $page object identifying the page to load history for
291 * @param array $params request parameters
292 * @return array response data
293 */
294 private function processDbResults( $res, $page, $params ) {
295 $revisions = [];
296
297 if ( $res ) {
298 $sizes = [];
299 foreach ( $res as $row ) {
300 $rev = $this->revisionStore->newRevisionFromRow(
301 $row,
302 IDBAccessObject::READ_NORMAL,
303 $page
304 );
305 if ( !$revisions ) {
306 $firstRevId = $row->rev_id;
307 }
308 $lastRevId = $row->rev_id;
309
310 $revision = [
311 'id' => $rev->getId(),
312 'timestamp' => wfTimestamp( TS_ISO_8601, $rev->getTimestamp() ),
313 'minor' => $rev->isMinor(),
314 'size' => $rev->getSize()
315 ];
316
317 // Remember revision sizes and parent ids for calculating deltas. If a revision's
318 // parent id is unknown, we will be unable to supply the delta for that revision.
319 $sizes[$rev->getId()] = $rev->getSize();
320 $parentId = $rev->getParentId();
321 if ( $parentId ) {
322 $revision['parent_id'] = $parentId;
323 }
324
325 $comment = $rev->getComment( RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
326 $revision['comment'] = $comment ? $comment->text : null;
327
328 $revUser = $rev->getUser( RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
329 if ( $revUser ) {
330 $revision['user'] = [
331 'id' => $revUser->isRegistered() ? $revUser->getId() : null,
332 'name' => $revUser->getName()
333 ];
334 } else {
335 $revision['user'] = null;
336 }
337
338 $revisions[] = $revision;
339
340 // Break manually at the return limit. We may have more results than we can return.
341 if ( count( $revisions ) == self::REVISIONS_RETURN_LIMIT ) {
342 break;
343 }
344 }
345
346 // Request any parent sizes that we do not already know, then calculate deltas
347 $unknownSizes = [];
348 foreach ( $revisions as $revision ) {
349 if ( isset( $revision['parent_id'] ) && !isset( $sizes[$revision['parent_id']] ) ) {
350 $unknownSizes[] = $revision['parent_id'];
351 }
352 }
353 if ( $unknownSizes ) {
354 $sizes += $this->revisionStore->getRevisionSizes( $unknownSizes );
355 }
356 foreach ( $revisions as &$revision ) {
357 $revision['delta'] = null;
358 if ( isset( $revision['parent_id'] ) ) {
359 if ( isset( $sizes[$revision['parent_id']] ) ) {
360 $revision['delta'] = $revision['size'] - $sizes[$revision['parent_id']];
361 }
362
363 // We only remembered this for delta calculations. We do not want to return it.
364 unset( $revision['parent_id'] );
365 }
366 }
367
368 if ( $revisions && $params['newer_than'] ) {
369 $revisions = array_reverse( $revisions );
370 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
371 // $lastRevId is declared because $res has one element
372 $temp = $lastRevId;
373 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
374 // $firstRevId is declared because $res has one element
375 $lastRevId = $firstRevId;
376 $firstRevId = $temp;
377 }
378 }
379
380 $response = [
381 'revisions' => $revisions
382 ];
383
384 // Omit newer/older if there are no additional corresponding revisions.
385 // This facilitates clients doing "paging" style api operations.
386 if ( $revisions ) {
387 if ( $params['newer_than'] || $res->numRows() > self::REVISIONS_RETURN_LIMIT ) {
388 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
389 // $lastRevId is declared because $res has one element
390 $older = $lastRevId;
391 }
392 if ( $params['older_than'] ||
393 ( $params['newer_than'] && $res->numRows() > self::REVISIONS_RETURN_LIMIT )
394 ) {
395 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
396 // $firstRevId is declared because $res has one element
397 $newer = $firstRevId;
398 }
399 }
400
401 $queryParts = [];
402
403 if ( isset( $params['filter'] ) ) {
404 $queryParts['filter'] = $params['filter'];
405 }
406
407 $pathParams = [ 'title' => $this->titleFormatter->getPrefixedDBkey( $page ) ];
408
409 $response['latest'] = $this->getRouteUrl( $pathParams, $queryParts );
410
411 if ( isset( $older ) ) {
412 $response['older'] =
413 $this->getRouteUrl( $pathParams, $queryParts + [ 'older_than' => $older ] );
414 }
415 if ( isset( $newer ) ) {
416 $response['newer'] =
417 $this->getRouteUrl( $pathParams, $queryParts + [ 'newer_than' => $newer ] );
418 }
419
420 return $response;
421 }
422
423 public function needsWriteAccess() {
424 return false;
425 }
426
427 public function getParamSettings() {
428 return [
429 'title' => [
430 self::PARAM_SOURCE => 'path',
431 ParamValidator::PARAM_TYPE => 'string',
432 ParamValidator::PARAM_REQUIRED => true,
433 ],
434 'older_than' => [
435 self::PARAM_SOURCE => 'query',
436 ParamValidator::PARAM_TYPE => 'integer',
437 ParamValidator::PARAM_REQUIRED => false,
438 ],
439 'newer_than' => [
440 self::PARAM_SOURCE => 'query',
441 ParamValidator::PARAM_TYPE => 'integer',
442 ParamValidator::PARAM_REQUIRED => false,
443 ],
444 'filter' => [
445 self::PARAM_SOURCE => 'query',
446 ParamValidator::PARAM_TYPE => self::ALLOWED_FILTER_TYPES,
447 ParamValidator::PARAM_REQUIRED => false,
448 ],
449 ];
450 }
451
452 /**
453 * Returns an ETag representing a page's latest revision.
454 *
455 * @return string|null
456 */
457 protected function getETag(): ?string {
458 $page = $this->getPage();
459 if ( !$page ) {
460 return null;
461 }
462
463 return '"' . $page->getLatest() . '"';
464 }
465
466 /**
467 * Returns the time of the last change to the page.
468 *
469 * @return string|null
470 */
471 protected function getLastModified(): ?string {
472 $page = $this->getPage();
473 if ( !$page ) {
474 return null;
475 }
476
477 $rev = $this->revisionStore->getKnownCurrentRevision( $page );
478 return $rev->getTimestamp();
479 }
480
481 /**
482 * @return bool
483 */
484 protected function hasRepresentation() {
485 return (bool)$this->getPage();
486 }
487
488 public function getResponseBodySchemaFileName( string $method ): ?string {
489 return 'includes/Rest/Handler/Schema/PageHistory.json';
490 }
491 }