MediaWiki  master
ApiQueryDeletedRevisions.php
Go to the documentation of this file.
1 <?php
37 
44 
46  private $revisionStore;
47 
49  private $changeTagDefStore;
50 
52  private $linkBatchFactory;
53 
66  public function __construct(
67  ApiQuery $query,
68  $moduleName,
69  RevisionStore $revisionStore,
70  IContentHandlerFactory $contentHandlerFactory,
71  ParserFactory $parserFactory,
72  SlotRoleRegistry $slotRoleRegistry,
73  NameTableStore $changeTagDefStore,
74  LinkBatchFactory $linkBatchFactory,
75  ContentRenderer $contentRenderer,
76  ContentTransformer $contentTransformer
77  ) {
78  parent::__construct(
79  $query,
80  $moduleName,
81  'drv',
82  $revisionStore,
83  $contentHandlerFactory,
84  $parserFactory,
85  $slotRoleRegistry,
86  $contentRenderer,
87  $contentTransformer
88  );
89  $this->revisionStore = $revisionStore;
90  $this->changeTagDefStore = $changeTagDefStore;
91  $this->linkBatchFactory = $linkBatchFactory;
92  }
93 
94  protected function run( ApiPageSet $resultPageSet = null ) {
95  $pageSet = $this->getPageSet();
96  $pageMap = $pageSet->getGoodAndMissingTitlesByNamespace();
97  $pageCount = count( $pageSet->getGoodAndMissingPages() );
98  $revCount = $pageSet->getRevisionCount();
99  if ( $revCount === 0 && $pageCount === 0 ) {
100  // Nothing to do
101  return;
102  }
103  if ( $revCount !== 0 && count( $pageSet->getDeletedRevisionIDs() ) === 0 ) {
104  // Nothing to do, revisions were supplied but none are deleted
105  return;
106  }
107 
108  $params = $this->extractRequestParams( false );
109 
110  $db = $this->getDB();
111 
112  $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
113 
114  if ( $resultPageSet === null ) {
115  $this->parseParameters( $params );
116  $arQuery = $this->revisionStore->getArchiveQueryInfo();
117  $this->addTables( $arQuery['tables'] );
118  $this->addFields( $arQuery['fields'] );
119  $this->addJoinConds( $arQuery['joins'] );
120  $this->addFields( [ 'ar_title', 'ar_namespace' ] );
121  } else {
122  $this->limit = $this->getParameter( 'limit' ) ?: 10;
123  $this->addTables( 'archive' );
124  $this->addFields( [ 'ar_title', 'ar_namespace', 'ar_timestamp', 'ar_rev_id', 'ar_id' ] );
125  }
126 
127  if ( $this->fld_tags ) {
128  $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'archive' ) ] );
129  }
130 
131  if ( $params['tag'] !== null ) {
132  $this->addTables( 'change_tag' );
133  $this->addJoinConds(
134  [ 'change_tag' => [ 'JOIN', [ 'ar_rev_id=ct_rev_id' ] ] ]
135  );
136  try {
137  $this->addWhereFld( 'ct_tag_id', $this->changeTagDefStore->getId( $params['tag'] ) );
138  } catch ( NameTableAccessException $exception ) {
139  // Return nothing.
140  $this->addWhere( '1=0' );
141  }
142  }
143 
144  // This means stricter restrictions
145  if ( ( $this->fld_comment || $this->fld_parsedcomment ) &&
146  !$this->getAuthority()->isAllowed( 'deletedhistory' )
147  ) {
148  $this->dieWithError( 'apierror-cantview-deleted-comment', 'permissiondenied' );
149  }
150  if ( $this->fetchContent && !$this->getAuthority()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
151  $this->dieWithError( 'apierror-cantview-deleted-revision-content', 'permissiondenied' );
152  }
153 
154  $dir = $params['dir'];
155 
156  if ( $revCount !== 0 ) {
157  $this->addWhere( [
158  'ar_rev_id' => array_keys( $pageSet->getDeletedRevisionIDs() )
159  ] );
160  } else {
161  // We need a custom WHERE clause that matches all titles.
162  $lb = $this->linkBatchFactory->newLinkBatch( $pageSet->getGoodAndMissingPages() );
163  $where = $lb->constructSet( 'ar', $db );
164  $this->addWhere( $where );
165  }
166 
167  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
168  // In the non-generator case, the actor join will already be present.
169  if ( $resultPageSet !== null ) {
170  $this->addTables( 'actor' );
171  $this->addJoinConds( [ 'actor' => [ 'JOIN', 'actor_id=ar_actor' ] ] );
172  }
173  if ( $params['user'] !== null ) {
174  $this->addWhereFld( 'actor_name', $params['user'] );
175  } elseif ( $params['excludeuser'] !== null ) {
176  $this->addWhere( 'actor_name<>' . $db->addQuotes( $params['excludeuser'] ) );
177  }
178  }
179 
180  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
181  // Paranoia: avoid brute force searches (T19342)
182  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
183  $bitmask = RevisionRecord::DELETED_USER;
184  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
185  $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
186  } else {
187  $bitmask = 0;
188  }
189  if ( $bitmask ) {
190  $this->addWhere( $db->bitAnd( 'ar_deleted', $bitmask ) . " != $bitmask" );
191  }
192  }
193 
194  if ( $params['continue'] !== null ) {
195  $op = ( $dir == 'newer' ? '>=' : '<=' );
196  if ( $revCount !== 0 ) {
197  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'int' ] );
198  $this->addWhere( $db->buildComparison( $op, [
199  'ar_rev_id' => $cont[0],
200  'ar_id' => $cont[1],
201  ] ) );
202  } else {
203  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string', 'timestamp', 'int' ] );
204  $this->addWhere( $db->buildComparison( $op, [
205  'ar_namespace' => $cont[0],
206  'ar_title' => $cont[1],
207  'ar_timestamp' => $db->timestamp( $cont[2] ),
208  'ar_id' => $cont[3],
209  ] ) );
210  }
211  }
212 
213  $this->addOption( 'LIMIT', $this->limit + 1 );
214 
215  if ( $revCount !== 0 ) {
216  // Sort by ar_rev_id when querying by ar_rev_id
217  $this->addWhereRange( 'ar_rev_id', $dir, null, null );
218  } else {
219  // Sort by ns and title in the same order as timestamp for efficiency
220  // But only when not already unique in the query
221  if ( count( $pageMap ) > 1 ) {
222  $this->addWhereRange( 'ar_namespace', $dir, null, null );
223  }
224  $oneTitle = key( reset( $pageMap ) );
225  foreach ( $pageMap as $pages ) {
226  if ( count( $pages ) > 1 || key( $pages ) !== $oneTitle ) {
227  $this->addWhereRange( 'ar_title', $dir, null, null );
228  break;
229  }
230  }
231  $this->addTimestampWhereRange( 'ar_timestamp', $dir, $params['start'], $params['end'] );
232  }
233  // Include in ORDER BY for uniqueness
234  $this->addWhereRange( 'ar_id', $dir, null, null );
235 
236  $res = $this->select( __METHOD__ );
237  $count = 0;
238  $generated = [];
239  foreach ( $res as $row ) {
240  if ( ++$count > $this->limit ) {
241  // We've had enough
242  $this->setContinueEnumParameter( 'continue',
243  $revCount
244  ? "$row->ar_rev_id|$row->ar_id"
245  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
246  );
247  break;
248  }
249 
250  if ( $resultPageSet !== null ) {
251  $generated[] = $row->ar_rev_id;
252  } else {
253  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
254  // Was it converted?
255  $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
256  $converted = $pageSet->getConvertedTitles();
257  if ( $title && isset( $converted[$title->getPrefixedText()] ) ) {
258  $title = Title::newFromText( $converted[$title->getPrefixedText()] );
259  if ( $title && isset( $pageMap[$title->getNamespace()][$title->getDBkey()] ) ) {
260  $pageMap[$row->ar_namespace][$row->ar_title] =
261  $pageMap[$title->getNamespace()][$title->getDBkey()];
262  }
263  }
264  }
265  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
267  __METHOD__,
268  "Found row in archive (ar_id={$row->ar_id}) that didn't get processed by ApiPageSet"
269  );
270  }
271 
272  $fit = $this->addPageSubItem(
273  $pageMap[$row->ar_namespace][$row->ar_title],
274  $this->extractRevisionInfo( $this->revisionStore->newRevisionFromArchiveRow( $row ), $row ),
275  'rev'
276  );
277  if ( !$fit ) {
278  $this->setContinueEnumParameter( 'continue',
279  $revCount
280  ? "$row->ar_rev_id|$row->ar_id"
281  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
282  );
283  break;
284  }
285  }
286  }
287 
288  if ( $resultPageSet !== null ) {
289  $resultPageSet->populateFromRevisionIDs( $generated );
290  }
291  }
292 
293  public function getAllowedParams() {
294  return parent::getAllowedParams() + [
295  'start' => [
296  ParamValidator::PARAM_TYPE => 'timestamp',
297  ],
298  'end' => [
299  ParamValidator::PARAM_TYPE => 'timestamp',
300  ],
301  'dir' => [
302  ParamValidator::PARAM_TYPE => [
303  'newer',
304  'older'
305  ],
306  ParamValidator::PARAM_DEFAULT => 'older',
307  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
308  ],
309  'tag' => null,
310  'user' => [
311  ParamValidator::PARAM_TYPE => 'user',
312  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
313  ],
314  'excludeuser' => [
315  ParamValidator::PARAM_TYPE => 'user',
316  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
317  ],
318  'continue' => [
319  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
320  ],
321  ];
322  }
323 
324  protected function getExamplesMessages() {
325  return [
326  'action=query&prop=deletedrevisions&titles=Main%20Page|Talk:Main%20Page&' .
327  'drvslots=*&drvprop=user|comment|content'
328  => 'apihelp-query+deletedrevisions-example-titles',
329  'action=query&prop=deletedrevisions&revids=123456'
330  => 'apihelp-query+deletedrevisions-example-revids',
331  ];
332  }
333 
334  public function getHelpUrls() {
335  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Deletedrevisions';
336  }
337 }
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1455
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:887
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1696
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1644
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:939
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:766
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:164
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:52
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.
__construct(ApiQuery $query, $moduleName, RevisionStore $revisionStore, IContentHandlerFactory $contentHandlerFactory, ParserFactory $parserFactory, SlotRoleRegistry $slotRoleRegistry, NameTableStore $changeTagDefStore, LinkBatchFactory $linkBatchFactory, ContentRenderer $contentRenderer, ContentTransformer $contentTransformer)
getExamplesMessages()
Returns usage examples for this module.
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:41
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
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.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:373
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
Service for formatting and validating API parameters.