MediaWiki  master
ApiQueryDeletedRevisions.php
Go to the documentation of this file.
1 <?php
41 
48 
49  private RevisionStore $revisionStore;
50  private NameTableStore $changeTagDefStore;
51  private LinkBatchFactory $linkBatchFactory;
52 
68  public function __construct(
69  ApiQuery $query,
70  $moduleName,
71  RevisionStore $revisionStore,
72  IContentHandlerFactory $contentHandlerFactory,
73  ParserFactory $parserFactory,
74  SlotRoleRegistry $slotRoleRegistry,
75  NameTableStore $changeTagDefStore,
76  LinkBatchFactory $linkBatchFactory,
77  ContentRenderer $contentRenderer,
78  ContentTransformer $contentTransformer,
79  CommentFormatter $commentFormatter,
80  TempUserCreator $tempUserCreator,
81  UserFactory $userFactory
82  ) {
83  parent::__construct(
84  $query,
85  $moduleName,
86  'drv',
87  $revisionStore,
88  $contentHandlerFactory,
89  $parserFactory,
90  $slotRoleRegistry,
91  $contentRenderer,
92  $contentTransformer,
93  $commentFormatter,
94  $tempUserCreator,
95  $userFactory
96  );
97  $this->revisionStore = $revisionStore;
98  $this->changeTagDefStore = $changeTagDefStore;
99  $this->linkBatchFactory = $linkBatchFactory;
100  }
101 
102  protected function run( ApiPageSet $resultPageSet = null ) {
103  $pageSet = $this->getPageSet();
104  $pageMap = $pageSet->getGoodAndMissingTitlesByNamespace();
105  $pageCount = count( $pageSet->getGoodAndMissingPages() );
106  $revCount = $pageSet->getRevisionCount();
107  if ( $revCount === 0 && $pageCount === 0 ) {
108  // Nothing to do
109  return;
110  }
111  if ( $revCount !== 0 && count( $pageSet->getDeletedRevisionIDs() ) === 0 ) {
112  // Nothing to do, revisions were supplied but none are deleted
113  return;
114  }
115 
116  $params = $this->extractRequestParams( false );
117 
118  $db = $this->getDB();
119 
120  $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
121 
122  if ( $resultPageSet === null ) {
123  $this->parseParameters( $params );
124  $arQuery = $this->revisionStore->getArchiveQueryInfo();
125  $this->addTables( $arQuery['tables'] );
126  $this->addFields( $arQuery['fields'] );
127  $this->addJoinConds( $arQuery['joins'] );
128  $this->addFields( [ 'ar_title', 'ar_namespace' ] );
129  } else {
130  $this->limit = $this->getParameter( 'limit' ) ?: 10;
131  $this->addTables( 'archive' );
132  $this->addFields( [ 'ar_title', 'ar_namespace', 'ar_timestamp', 'ar_rev_id', 'ar_id' ] );
133  }
134 
135  if ( $this->fld_tags ) {
136  $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'archive' ) ] );
137  }
138 
139  if ( $params['tag'] !== null ) {
140  $this->addTables( 'change_tag' );
141  $this->addJoinConds(
142  [ 'change_tag' => [ 'JOIN', [ 'ar_rev_id=ct_rev_id' ] ] ]
143  );
144  try {
145  $this->addWhereFld( 'ct_tag_id', $this->changeTagDefStore->getId( $params['tag'] ) );
146  } catch ( NameTableAccessException $exception ) {
147  // Return nothing.
148  $this->addWhere( '1=0' );
149  }
150  }
151 
152  // This means stricter restrictions
153  if ( ( $this->fld_comment || $this->fld_parsedcomment ) &&
154  !$this->getAuthority()->isAllowed( 'deletedhistory' )
155  ) {
156  $this->dieWithError( 'apierror-cantview-deleted-comment', 'permissiondenied' );
157  }
158  if ( $this->fetchContent && !$this->getAuthority()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
159  $this->dieWithError( 'apierror-cantview-deleted-revision-content', 'permissiondenied' );
160  }
161 
162  $dir = $params['dir'];
163 
164  if ( $revCount !== 0 ) {
165  $this->addWhere( [
166  'ar_rev_id' => array_keys( $pageSet->getDeletedRevisionIDs() )
167  ] );
168  } else {
169  // We need a custom WHERE clause that matches all titles.
170  $lb = $this->linkBatchFactory->newLinkBatch( $pageSet->getGoodAndMissingPages() );
171  $where = $lb->constructSet( 'ar', $db );
172  $this->addWhere( $where );
173  }
174 
175  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
176  // In the non-generator case, the actor join will already be present.
177  if ( $resultPageSet !== null ) {
178  $this->addTables( 'actor' );
179  $this->addJoinConds( [ 'actor' => [ 'JOIN', 'actor_id=ar_actor' ] ] );
180  }
181  if ( $params['user'] !== null ) {
182  $this->addWhereFld( 'actor_name', $params['user'] );
183  } elseif ( $params['excludeuser'] !== null ) {
184  $this->addWhere( 'actor_name<>' . $db->addQuotes( $params['excludeuser'] ) );
185  }
186  }
187 
188  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
189  // Paranoia: avoid brute force searches (T19342)
190  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
191  $bitmask = RevisionRecord::DELETED_USER;
192  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
193  $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
194  } else {
195  $bitmask = 0;
196  }
197  if ( $bitmask ) {
198  $this->addWhere( $db->bitAnd( 'ar_deleted', $bitmask ) . " != $bitmask" );
199  }
200  }
201 
202  if ( $params['continue'] !== null ) {
203  $op = ( $dir == 'newer' ? '>=' : '<=' );
204  if ( $revCount !== 0 ) {
205  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'int' ] );
206  $this->addWhere( $db->buildComparison( $op, [
207  'ar_rev_id' => $cont[0],
208  'ar_id' => $cont[1],
209  ] ) );
210  } else {
211  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string', 'timestamp', 'int' ] );
212  $this->addWhere( $db->buildComparison( $op, [
213  'ar_namespace' => $cont[0],
214  'ar_title' => $cont[1],
215  'ar_timestamp' => $db->timestamp( $cont[2] ),
216  'ar_id' => $cont[3],
217  ] ) );
218  }
219  }
220 
221  $this->addOption( 'LIMIT', $this->limit + 1 );
222 
223  if ( $revCount !== 0 ) {
224  // Sort by ar_rev_id when querying by ar_rev_id
225  $this->addWhereRange( 'ar_rev_id', $dir, null, null );
226  } else {
227  // Sort by ns and title in the same order as timestamp for efficiency
228  // But only when not already unique in the query
229  if ( count( $pageMap ) > 1 ) {
230  $this->addWhereRange( 'ar_namespace', $dir, null, null );
231  }
232  $oneTitle = key( reset( $pageMap ) );
233  foreach ( $pageMap as $pages ) {
234  if ( count( $pages ) > 1 || key( $pages ) !== $oneTitle ) {
235  $this->addWhereRange( 'ar_title', $dir, null, null );
236  break;
237  }
238  }
239  $this->addTimestampWhereRange( 'ar_timestamp', $dir, $params['start'], $params['end'] );
240  }
241  // Include in ORDER BY for uniqueness
242  $this->addWhereRange( 'ar_id', $dir, null, null );
243 
244  $res = $this->select( __METHOD__ );
245  $count = 0;
246  $generated = [];
247  foreach ( $res as $row ) {
248  if ( ++$count > $this->limit ) {
249  // We've had enough
250  $this->setContinueEnumParameter( 'continue',
251  $revCount
252  ? "$row->ar_rev_id|$row->ar_id"
253  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
254  );
255  break;
256  }
257 
258  if ( $resultPageSet !== null ) {
259  $generated[] = $row->ar_rev_id;
260  } else {
261  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
262  // Was it converted?
263  $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
264  $converted = $pageSet->getConvertedTitles();
265  if ( $title && isset( $converted[$title->getPrefixedText()] ) ) {
266  $title = Title::newFromText( $converted[$title->getPrefixedText()] );
267  if ( $title && isset( $pageMap[$title->getNamespace()][$title->getDBkey()] ) ) {
268  $pageMap[$row->ar_namespace][$row->ar_title] =
269  $pageMap[$title->getNamespace()][$title->getDBkey()];
270  }
271  }
272  }
273  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
275  __METHOD__,
276  "Found row in archive (ar_id={$row->ar_id}) that didn't get processed by ApiPageSet"
277  );
278  }
279 
280  $fit = $this->addPageSubItem(
281  $pageMap[$row->ar_namespace][$row->ar_title],
282  $this->extractRevisionInfo( $this->revisionStore->newRevisionFromArchiveRow( $row ), $row ),
283  'rev'
284  );
285  if ( !$fit ) {
286  $this->setContinueEnumParameter( 'continue',
287  $revCount
288  ? "$row->ar_rev_id|$row->ar_id"
289  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
290  );
291  break;
292  }
293  }
294  }
295 
296  if ( $resultPageSet !== null ) {
297  $resultPageSet->populateFromRevisionIDs( $generated );
298  }
299  }
300 
301  public function getAllowedParams() {
302  return parent::getAllowedParams() + [
303  'start' => [
304  ParamValidator::PARAM_TYPE => 'timestamp',
305  ],
306  'end' => [
307  ParamValidator::PARAM_TYPE => 'timestamp',
308  ],
309  'dir' => [
310  ParamValidator::PARAM_TYPE => [
311  'newer',
312  'older'
313  ],
314  ParamValidator::PARAM_DEFAULT => 'older',
315  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
317  'newer' => 'api-help-paramvalue-direction-newer',
318  'older' => 'api-help-paramvalue-direction-older',
319  ],
320  ],
321  'tag' => null,
322  'user' => [
323  ParamValidator::PARAM_TYPE => 'user',
324  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
325  ],
326  'excludeuser' => [
327  ParamValidator::PARAM_TYPE => 'user',
328  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
329  ],
330  'continue' => [
331  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
332  ],
333  ];
334  }
335 
336  protected function getExamplesMessages() {
337  $title = Title::newMainPage();
338  $talkTitle = $title->getTalkPageIfDefined();
339  $examples = [];
340 
341  if ( $talkTitle ) {
342  $title = rawurlencode( $title->getPrefixedText() );
343  $talkTitle = rawurlencode( $talkTitle->getPrefixedText() );
344  $examples = [
345  "action=query&prop=deletedrevisions&titles={$title}|{$talkTitle}&" .
346  'drvslots=*&drvprop=user|comment|content'
347  => 'apihelp-query+deletedrevisions-example-titles',
348  ];
349  }
350 
351  return array_merge( $examples, [
352  'action=query&prop=deletedrevisions&revids=123456'
353  => 'apihelp-query+deletedrevisions-example-revids',
354  ] );
355  }
356 
357  public function getHelpUrls() {
358  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Deletedrevisions';
359  }
360 }
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1516
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:930
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1771
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1718
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition: ApiBase.php:210
requireMaxOneParameter( $params,... $required)
Dies if more than one parameter from a certain set of parameters are set and not false.
Definition: ApiBase.php:982
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:808
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:170
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:55
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
addFields( $value)
Add a set of fields to select to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Query module to enumerate deleted revisions for pages.
getExamplesMessages()
Returns usage examples for this module.
__construct(ApiQuery $query, $moduleName, RevisionStore $revisionStore, IContentHandlerFactory $contentHandlerFactory, ParserFactory $parserFactory, SlotRoleRegistry $slotRoleRegistry, NameTableStore $changeTagDefStore, LinkBatchFactory $linkBatchFactory, ContentRenderer $contentRenderer, ContentTransformer $contentTransformer, CommentFormatter $commentFormatter, TempUserCreator $tempUserCreator, UserFactory $userFactory)
getAllowedParams()
@stable to override
getHelpUrls()
Return links to more detailed help pages about the module.
run(ApiPageSet $resultPageSet=null)
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getPageSet()
Get the PageSet object to work on.
A base class for functions common to producing a list of revisions.
parseParameters( $params)
Parse the parameters into the various instance fields.
This is the main query class.
Definition: ApiQuery.php:43
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
Definition: ChangeTags.php:664
This is the main service interface for converting single-line comments from various DB comment fields...
Page revision base class.
Service for looking up page revisions.
A registry service for SlotRoleHandlers, used to define which slot roles are available on which page.
Exception representing a failure to look up a row from a name table.
Represents a title within MediaWiki.
Definition: Title.php:76
Service for temporary user creation.
Creates User objects.
Definition: UserFactory.php:41
Service for formatting and validating API parameters.