Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
65.57% covered (warning)
65.57%
120 / 183
20.00% covered (danger)
20.00%
1 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryAllRevisions
65.93% covered (warning)
65.93%
120 / 182
20.00% covered (danger)
20.00%
1 / 5
111.74
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 run
54.78% covered (warning)
54.78%
63 / 115
0.00% covered (danger)
0.00%
0 / 1
163.57
 getAllowedParams
93.48% covered (success)
93.48%
43 / 46
0.00% covered (danger)
0.00%
0 / 1
2.00
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Copyright © 2015 Wikimedia Foundation and contributors
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use MediaWiki\ChangeTags\ChangeTagsStore;
12use MediaWiki\CommentFormatter\CommentFormatter;
13use MediaWiki\Content\IContentHandlerFactory;
14use MediaWiki\Content\Renderer\ContentRenderer;
15use MediaWiki\Content\Transform\ContentTransformer;
16use MediaWiki\MainConfigNames;
17use MediaWiki\ParamValidator\TypeDef\UserDef;
18use MediaWiki\Parser\ParserFactory;
19use MediaWiki\Revision\RevisionRecord;
20use MediaWiki\Revision\RevisionStore;
21use MediaWiki\Revision\SlotRoleRegistry;
22use MediaWiki\Title\NamespaceInfo;
23use MediaWiki\Title\Title;
24use MediaWiki\User\ActorMigration;
25use MediaWiki\User\TempUser\TempUserCreator;
26use MediaWiki\User\UserFactory;
27use Wikimedia\ParamValidator\ParamValidator;
28
29/**
30 * Query module to enumerate all revisions.
31 *
32 * @ingroup API
33 * @since 1.27
34 */
35class ApiQueryAllRevisions extends ApiQueryRevisionsBase {
36
37    public function __construct(
38        ApiQuery $query,
39        string $moduleName,
40        private readonly RevisionStore $revisionStore,
41        IContentHandlerFactory $contentHandlerFactory,
42        ParserFactory $parserFactory,
43        SlotRoleRegistry $slotRoleRegistry,
44        private readonly ActorMigration $actorMigration,
45        private readonly NamespaceInfo $namespaceInfo,
46        private readonly ChangeTagsStore $changeTagsStore,
47        ContentRenderer $contentRenderer,
48        ContentTransformer $contentTransformer,
49        CommentFormatter $commentFormatter,
50        TempUserCreator $tempUserCreator,
51        UserFactory $userFactory,
52    ) {
53        parent::__construct(
54            $query,
55            $moduleName,
56            'arv',
57            $revisionStore,
58            $contentHandlerFactory,
59            $parserFactory,
60            $slotRoleRegistry,
61            $contentRenderer,
62            $contentTransformer,
63            $commentFormatter,
64            $tempUserCreator,
65            $userFactory
66        );
67    }
68
69    /**
70     * @param ApiPageSet|null $resultPageSet
71     * @return void
72     */
73    protected function run( ?ApiPageSet $resultPageSet = null ) {
74        $db = $this->getDB();
75        $params = $this->extractRequestParams( false );
76
77        $result = $this->getResult();
78
79        $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
80
81        $tsField = 'rev_timestamp';
82        $idField = 'rev_id';
83        $pageField = 'rev_page';
84
85        // Namespace check is likely to be desired, but can't be done
86        // efficiently in SQL.
87        $miser_ns = null;
88        $needPageTable = false;
89        if ( $params['namespace'] !== null ) {
90            $params['namespace'] = array_unique( $params['namespace'] );
91            sort( $params['namespace'] );
92            if ( $params['namespace'] != $this->namespaceInfo->getValidNamespaces() ) {
93                $needPageTable = true;
94                if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
95                    $miser_ns = $params['namespace'];
96                } else {
97                    $this->addWhere( [ 'page_namespace' => $params['namespace'] ] );
98                }
99            }
100        }
101
102        if ( $resultPageSet === null ) {
103            $this->parseParameters( $params );
104            $queryBuilder = $this->revisionStore->newSelectQueryBuilder( $db )
105                ->joinComment()
106                ->joinPage();
107            $this->getQueryBuilder()->merge( $queryBuilder );
108        } else {
109            $this->limit = $this->getParameter( 'limit' ) ?: 10;
110            $this->addTables( [ 'revision' ] );
111            $this->addFields( [ 'rev_timestamp', 'rev_id' ] );
112
113            if ( $params['generatetitles'] ) {
114                $this->addFields( [ 'rev_page' ] );
115            }
116
117            if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
118                $this->getQueryBuilder()->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' );
119            }
120
121            if ( $needPageTable ) {
122                $this->getQueryBuilder()->join( 'page', null, [ "$pageField = page_id" ] );
123                if ( (bool)$miser_ns ) {
124                    $this->addFields( [ 'page_namespace' ] );
125                }
126            }
127        }
128
129        // Seems to be needed to avoid a planner bug (T113901)
130        $this->addOption( 'STRAIGHT_JOIN' );
131
132        $dir = $params['dir'];
133        $this->addTimestampWhereRange( $tsField, $dir, $params['start'], $params['end'] );
134
135        if ( $this->fld_tags ) {
136            $this->addFields( [
137                'ts_tags' => $this->changeTagsStore->makeTagSummarySubquery( 'revision', $this->getAuthority() )
138            ] );
139        }
140
141        if ( $params['user'] !== null ) {
142            $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['user'] );
143            $this->addWhere( $actorQuery['conds'] );
144        } elseif ( $params['excludeuser'] !== null ) {
145            $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['excludeuser'] );
146            $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
147        }
148
149        if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
150            // Paranoia: avoid brute force searches (T19342)
151            if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
152                $bitmask = RevisionRecord::DELETED_USER;
153            } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
154                $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
155            } else {
156                $bitmask = 0;
157            }
158            if ( $bitmask ) {
159                $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
160            }
161        }
162
163        if ( $params['continue'] !== null ) {
164            $op = ( $dir == 'newer' ? '>=' : '<=' );
165            $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
166            $this->addWhere( $db->buildComparison( $op, [
167                $tsField => $db->timestamp( $cont[0] ),
168                $idField => $cont[1],
169            ] ) );
170        }
171
172        $this->addOption( 'LIMIT', $this->limit + 1 );
173
174        $sort = ( $dir == 'newer' ? '' : ' DESC' );
175        $orderby = [];
176        // Targeting index rev_timestamp, user_timestamp, usertext_timestamp, or actor_timestamp.
177        // But 'user' is always constant for the latter three, so it doesn't matter here.
178        $orderby[] = "rev_timestamp $sort";
179        $orderby[] = "rev_id $sort";
180        $this->addOption( 'ORDER BY', $orderby );
181
182        $hookData = [];
183        $res = $this->select( __METHOD__, [], $hookData );
184
185        if ( $resultPageSet === null ) {
186            $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
187        }
188
189        $pageMap = []; // Maps rev_page to array index
190        $count = 0;
191        $nextIndex = 0;
192        $generated = [];
193        foreach ( $res as $row ) {
194            if ( $count === 0 && $resultPageSet !== null ) {
195                // Set the non-continue since the list of all revisions is
196                // prone to having entries added at the start frequently.
197                $this->getContinuationManager()->addGeneratorNonContinueParam(
198                    $this, 'continue', "$row->rev_timestamp|$row->rev_id"
199                );
200            }
201            if ( ++$count > $this->limit ) {
202                // We've had enough
203                $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
204                break;
205            }
206
207            // Miser mode namespace check
208            if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
209                continue;
210            }
211
212            if ( $resultPageSet !== null ) {
213                if ( $params['generatetitles'] ) {
214                    $generated[$row->rev_page] = $row->rev_page;
215                } else {
216                    $generated[] = $row->rev_id;
217                }
218            } else {
219                $revision = $this->revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
220                $rev = $this->extractRevisionInfo( $revision, $row );
221
222                if ( !isset( $pageMap[$row->rev_page] ) ) {
223                    $index = $nextIndex++;
224                    $pageMap[$row->rev_page] = $index;
225                    $title = Title::newFromPageIdentity( $revision->getPage() );
226                    $a = [
227                        'pageid' => $title->getArticleID(),
228                        'revisions' => [ $rev ],
229                    ];
230                    ApiResult::setIndexedTagName( $a['revisions'], 'rev' );
231                    ApiQueryBase::addTitleInfo( $a, $title );
232                    $fit = $this->processRow( $row, $a['revisions'][0], $hookData ) &&
233                        $result->addValue( [ 'query', $this->getModuleName() ], $index, $a );
234                } else {
235                    $index = $pageMap[$row->rev_page];
236                    $fit = $this->processRow( $row, $rev, $hookData ) &&
237                        $result->addValue( [ 'query', $this->getModuleName(), $index, 'revisions' ], null, $rev );
238                }
239                if ( !$fit ) {
240                    $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
241                    break;
242                }
243            }
244        }
245
246        if ( $resultPageSet !== null ) {
247            if ( $params['generatetitles'] ) {
248                $resultPageSet->populateFromPageIDs( $generated );
249            } else {
250                $resultPageSet->populateFromRevisionIDs( $generated );
251            }
252        } else {
253            $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
254        }
255    }
256
257    /** @inheritDoc */
258    public function getAllowedParams() {
259        $ret = parent::getAllowedParams() + [
260            'user' => [
261                ParamValidator::PARAM_TYPE => 'user',
262                UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'id', 'interwiki' ],
263                UserDef::PARAM_RETURN_OBJECT => true,
264            ],
265            'namespace' => [
266                ParamValidator::PARAM_ISMULTI => true,
267                ParamValidator::PARAM_TYPE => 'namespace',
268                ParamValidator::PARAM_DEFAULT => null,
269            ],
270            'start' => [
271                ParamValidator::PARAM_TYPE => 'timestamp',
272            ],
273            'end' => [
274                ParamValidator::PARAM_TYPE => 'timestamp',
275            ],
276            'dir' => [
277                ParamValidator::PARAM_TYPE => [
278                    'newer',
279                    'older'
280                ],
281                ParamValidator::PARAM_DEFAULT => 'older',
282                ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
283                ApiBase::PARAM_HELP_MSG_PER_VALUE => [
284                    'newer' => 'api-help-paramvalue-direction-newer',
285                    'older' => 'api-help-paramvalue-direction-older',
286                ],
287            ],
288            'excludeuser' => [
289                ParamValidator::PARAM_TYPE => 'user',
290                UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'id', 'interwiki' ],
291                UserDef::PARAM_RETURN_OBJECT => true,
292            ],
293            'continue' => [
294                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
295            ],
296            'generatetitles' => [
297                ParamValidator::PARAM_DEFAULT => false,
298            ],
299        ];
300
301        if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
302            $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
303                'api-help-param-limited-in-miser-mode',
304            ];
305        }
306
307        return $ret;
308    }
309
310    /** @inheritDoc */
311    protected function getExamplesMessages() {
312        return [
313            'action=query&list=allrevisions&arvuser=Example&arvlimit=50'
314                => 'apihelp-query+allrevisions-example-user',
315            'action=query&list=allrevisions&arvdir=newer&arvlimit=50'
316                => 'apihelp-query+allrevisions-example-ns-any',
317        ];
318    }
319
320    /** @inheritDoc */
321    public function getHelpUrls() {
322        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allrevisions';
323    }
324}
325
326/** @deprecated class alias since 1.43 */
327class_alias( ApiQueryAllRevisions::class, 'ApiQueryAllRevisions' );