MediaWiki REL1_34
ApiQueryBacklinks.php
Go to the documentation of this file.
1<?php
32
36 private $rootTitle;
37
38 private $params;
40 private $cont;
41 private $redirect;
43
45 private $helpUrl;
46
52 private $pageMap = [];
53 private $resultArr;
54
55 private $redirTitles = [];
56 private $continueStr = null;
57
58 // output element name, database column field prefix, database table
60 'backlinks' => [
61 'code' => 'bl',
62 'prefix' => 'pl',
63 'linktbl' => 'pagelinks',
64 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Backlinks',
65 ],
66 'embeddedin' => [
67 'code' => 'ei',
68 'prefix' => 'tl',
69 'linktbl' => 'templatelinks',
70 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Embeddedin',
71 ],
72 'imageusage' => [
73 'code' => 'iu',
74 'prefix' => 'il',
75 'linktbl' => 'imagelinks',
76 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageusage',
77 ]
78 ];
79
80 public function __construct( ApiQuery $query, $moduleName ) {
81 $settings = $this->backlinksSettings[$moduleName];
82 $prefix = $settings['prefix'];
83 $code = $settings['code'];
84 $this->resultArr = [];
85
86 parent::__construct( $query, $moduleName, $code );
87 $this->bl_ns = $prefix . '_namespace';
88 $this->bl_from = $prefix . '_from';
89 $this->bl_from_ns = $prefix . '_from_namespace';
90 $this->bl_table = $settings['linktbl'];
91 $this->bl_code = $code;
92 $this->helpUrl = $settings['helpurl'];
93
94 $this->hasNS = $moduleName !== 'imageusage';
95 if ( $this->hasNS ) {
96 $this->bl_title = $prefix . '_title';
97 $this->bl_fields = [
100 ];
101 } else {
102 $this->bl_title = $prefix . '_to';
103 $this->bl_fields = [
105 ];
106 }
107 }
108
109 public function execute() {
110 $this->run();
111 }
112
113 public function getCacheMode( $params ) {
114 return 'public';
115 }
116
117 public function executeGenerator( $resultPageSet ) {
118 $this->run( $resultPageSet );
119 }
120
125 private function runFirstQuery( $resultPageSet = null ) {
126 $this->addTables( [ $this->bl_table, 'page' ] );
127 $this->addWhere( "{$this->bl_from}=page_id" );
128 if ( is_null( $resultPageSet ) ) {
129 $this->addFields( [ 'page_id', 'page_title', 'page_namespace' ] );
130 } else {
131 $this->addFields( $resultPageSet->getPageTableFields() );
132 }
133 $this->addFields( [ 'page_is_redirect', 'from_ns' => 'page_namespace' ] );
134
135 $this->addWhereFld( $this->bl_title, $this->rootTitle->getDBkey() );
136 if ( $this->hasNS ) {
137 $this->addWhereFld( $this->bl_ns, $this->rootTitle->getNamespace() );
138 }
139 $this->addWhereFld( $this->bl_from_ns, $this->params['namespace'] );
140
141 if ( count( $this->cont ) >= 2 ) {
142 $op = $this->params['dir'] == 'descending' ? '<' : '>';
143 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
144 $this->addWhere(
145 "{$this->bl_from_ns} $op {$this->cont[0]} OR " .
146 "({$this->bl_from_ns} = {$this->cont[0]} AND " .
147 "{$this->bl_from} $op= {$this->cont[1]})"
148 );
149 } else {
150 $this->addWhere( "{$this->bl_from} $op= {$this->cont[1]}" );
151 }
152 }
153
154 if ( $this->params['filterredir'] == 'redirects' ) {
155 $this->addWhereFld( 'page_is_redirect', 1 );
156 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
157 // T24245 - Check for !redirect, as filtering nonredirects, when
158 // getting what links to them is contradictory
159 $this->addWhereFld( 'page_is_redirect', 0 );
160 }
161
162 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
163 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
164 $orderBy = [];
165 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
166 $orderBy[] = $this->bl_from_ns . $sort;
167 }
168 $orderBy[] = $this->bl_from . $sort;
169 $this->addOption( 'ORDER BY', $orderBy );
170 $this->addOption( 'STRAIGHT_JOIN' );
171
172 $res = $this->select( __METHOD__ );
173 $count = 0;
174 foreach ( $res as $row ) {
175 if ( ++$count > $this->params['limit'] ) {
176 // We've reached the one extra which shows that there are
177 // additional pages to be had. Stop here...
178 // Continue string may be overridden at a later step
179 $this->continueStr = "{$row->from_ns}|{$row->page_id}";
180 break;
181 }
182
183 // Fill in continuation fields for later steps
184 if ( count( $this->cont ) < 2 ) {
185 $this->cont[] = $row->from_ns;
186 $this->cont[] = $row->page_id;
187 }
188
189 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
190 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
191 if ( $row->page_is_redirect ) {
192 $this->redirTitles[] = $t;
193 }
194
195 if ( is_null( $resultPageSet ) ) {
196 $a = [ 'pageid' => (int)$row->page_id ];
198 if ( $row->page_is_redirect ) {
199 $a['redirect'] = true;
200 }
201 // Put all the results in an array first
202 $this->resultArr[$a['pageid']] = $a;
203 } else {
204 $resultPageSet->processDbRow( $row );
205 }
206 }
207 }
208
213 private function runSecondQuery( $resultPageSet = null ) {
214 $db = $this->getDB();
215 $this->addTables( [ 'page', $this->bl_table ] );
216 $this->addWhere( "{$this->bl_from}=page_id" );
217
218 if ( is_null( $resultPageSet ) ) {
219 $this->addFields( [ 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ] );
220 } else {
221 $this->addFields( $resultPageSet->getPageTableFields() );
222 }
223
224 $this->addFields( [ $this->bl_title, 'from_ns' => 'page_namespace' ] );
225 if ( $this->hasNS ) {
226 $this->addFields( $this->bl_ns );
227 }
228
229 // We can't use LinkBatch here because $this->hasNS may be false
230 $titleWhere = [];
231 $allRedirNs = [];
232 $allRedirDBkey = [];
234 foreach ( $this->redirTitles as $t ) {
235 $redirNs = $t->getNamespace();
236 $redirDBkey = $t->getDBkey();
237 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
238 ( $this->hasNS ? " AND {$this->bl_ns} = {$redirNs}" : '' );
239 $allRedirNs[$redirNs] = true;
240 $allRedirDBkey[$redirDBkey] = true;
241 }
242 $this->addWhere( $db->makeList( $titleWhere, LIST_OR ) );
243 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
244
245 if ( count( $this->cont ) >= 6 ) {
246 $op = $this->params['dir'] == 'descending' ? '<' : '>';
247
248 $where = "{$this->bl_from} $op= {$this->cont[5]}";
249 // Don't bother with namespace, title, or from_namespace if it's
250 // otherwise constant in the where clause.
251 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
252 $where = "{$this->bl_from_ns} $op {$this->cont[4]} OR " .
253 "({$this->bl_from_ns} = {$this->cont[4]} AND ($where))";
254 }
255 if ( count( $allRedirDBkey ) > 1 ) {
256 $title = $db->addQuotes( $this->cont[3] );
257 $where = "{$this->bl_title} $op $title OR " .
258 "({$this->bl_title} = $title AND ($where))";
259 }
260 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
261 $where = "{$this->bl_ns} $op {$this->cont[2]} OR " .
262 "({$this->bl_ns} = {$this->cont[2]} AND ($where))";
263 }
264
265 $this->addWhere( $where );
266 }
267 if ( $this->params['filterredir'] == 'redirects' ) {
268 $this->addWhereFld( 'page_is_redirect', 1 );
269 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
270 $this->addWhereFld( 'page_is_redirect', 0 );
271 }
272
273 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
274 $orderBy = [];
275 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
276 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
277 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
278 $orderBy[] = $this->bl_ns . $sort;
279 }
280 if ( count( $allRedirDBkey ) > 1 ) {
281 $orderBy[] = $this->bl_title . $sort;
282 }
283 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
284 $orderBy[] = $this->bl_from_ns . $sort;
285 }
286 $orderBy[] = $this->bl_from . $sort;
287 $this->addOption( 'ORDER BY', $orderBy );
288 $this->addOption( 'USE INDEX', [ 'page' => 'PRIMARY' ] );
289
290 $res = $this->select( __METHOD__ );
291 $count = 0;
292 foreach ( $res as $row ) {
293 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_FILE;
294
295 if ( ++$count > $this->params['limit'] ) {
296 // We've reached the one extra which shows that there are
297 // additional pages to be had. Stop here...
298 // Note we must keep the parameters for the first query constant
299 // This may be overridden at a later step
300 $title = $row->{$this->bl_title};
301 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 2 ) ) .
302 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
303 break;
304 }
305
306 // Fill in continuation fields for later steps
307 if ( count( $this->cont ) < 6 ) {
308 $this->cont[] = $ns;
309 $this->cont[] = $row->{$this->bl_title};
310 $this->cont[] = $row->from_ns;
311 $this->cont[] = $row->page_id;
312 }
313
314 if ( is_null( $resultPageSet ) ) {
315 $a = [ 'pageid' => (int)$row->page_id ];
316 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
317 if ( $row->page_is_redirect ) {
318 $a['redirect'] = true;
319 }
320 $parentID = $this->pageMap[$ns][$row->{$this->bl_title}];
321 // Put all the results in an array first
322 $this->resultArr[$parentID]['redirlinks'][$row->page_id] = $a;
323 } else {
324 $resultPageSet->processDbRow( $row );
325 }
326 }
327 }
328
333 private function run( $resultPageSet = null ) {
334 $this->params = $this->extractRequestParams( false );
335 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
336 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
337 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
338
339 $result = $this->getResult();
340
341 if ( $this->params['limit'] == 'max' ) {
342 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
343 $result->addParsedLimit( $this->getModuleName(), $this->params['limit'] );
344 } else {
345 $this->params['limit'] = (int)$this->params['limit'];
346 $this->validateLimit( 'limit', $this->params['limit'], 1, $userMax, $botMax );
347 }
348
349 $this->rootTitle = $this->getTitleFromTitleOrPageId( $this->params );
350
351 // only image titles are allowed for the root in imageinfo mode
352 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
353 $this->dieWithError(
354 [ 'apierror-imageusage-badtitle', $this->getModuleName() ],
355 'bad_image_title'
356 );
357 }
358
359 // Parse and validate continuation parameter
360 $this->cont = [];
361 if ( $this->params['continue'] !== null ) {
362 $cont = explode( '|', $this->params['continue'] );
363
364 switch ( count( $cont ) ) {
365 case 8:
366 // redirect page ID for result adding
367 $this->cont[7] = (int)$cont[7];
368 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont[7] );
369
370 /* Fall through */
371
372 case 7:
373 // top-level page ID for result adding
374 $this->cont[6] = (int)$cont[6];
375 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont[6] );
376
377 /* Fall through */
378
379 case 6:
380 // ns for 2nd query (even for imageusage)
381 $this->cont[2] = (int)$cont[2];
382 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont[2] );
383
384 // title for 2nd query
385 $this->cont[3] = $cont[3];
386
387 // from_ns for 2nd query
388 $this->cont[4] = (int)$cont[4];
389 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont[4] );
390
391 // from_id for 1st query
392 $this->cont[5] = (int)$cont[5];
393 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont[5] );
394
395 /* Fall through */
396
397 case 2:
398 // from_ns for 1st query
399 $this->cont[0] = (int)$cont[0];
400 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont[0] );
401
402 // from_id for 1st query
403 $this->cont[1] = (int)$cont[1];
404 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont[1] );
405
406 break;
407
408 default:
409 $this->dieContinueUsageIf( true );
410 }
411
412 ksort( $this->cont );
413 }
414
415 $this->runFirstQuery( $resultPageSet );
416 if ( $this->redirect && count( $this->redirTitles ) ) {
417 $this->resetQueryParams();
418 $this->runSecondQuery( $resultPageSet );
419 }
420
421 // Fill in any missing fields in case it's needed below
422 $this->cont += [ 0, 0, 0, '', 0, 0, 0 ];
423
424 if ( is_null( $resultPageSet ) ) {
425 // Try to add the result data in one go and pray that it fits
426 $code = $this->bl_code;
427 $data = array_map( function ( $arr ) use ( $code ) {
428 if ( isset( $arr['redirlinks'] ) ) {
429 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
430 ApiResult::setIndexedTagName( $arr['redirlinks'], $code );
431 }
432 return $arr;
433 }, array_values( $this->resultArr ) );
434 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
435 if ( !$fit ) {
436 // It didn't fit. Add elements one by one until the
437 // result is full.
438 ksort( $this->resultArr );
439 if ( count( $this->cont ) >= 7 ) {
440 $startAt = $this->cont[6];
441 } else {
442 reset( $this->resultArr );
443 $startAt = key( $this->resultArr );
444 }
445 $idx = 0;
446 foreach ( $this->resultArr as $pageID => $arr ) {
447 if ( $pageID < $startAt ) {
448 continue;
449 }
450
451 // Add the basic entry without redirlinks first
452 $fit = $result->addValue(
453 [ 'query', $this->getModuleName() ],
454 $idx, array_diff_key( $arr, [ 'redirlinks' => '' ] ) );
455 if ( !$fit ) {
456 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
457 "|$pageID";
458 break;
459 }
460
461 $hasRedirs = false;
462 $redirLinks = isset( $arr['redirlinks'] ) ? (array)$arr['redirlinks'] : [];
463 ksort( $redirLinks );
464 if ( count( $this->cont ) >= 8 && $pageID == $startAt ) {
465 $redirStartAt = $this->cont[7];
466 } else {
467 reset( $redirLinks );
468 $redirStartAt = key( $redirLinks );
469 }
470 foreach ( $redirLinks as $key => $redir ) {
471 if ( $key < $redirStartAt ) {
472 continue;
473 }
474
475 $fit = $result->addValue(
476 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
477 null, $redir );
478 if ( !$fit ) {
479 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
480 "|$pageID|$key";
481 break;
482 }
483 $hasRedirs = true;
484 }
485 if ( $hasRedirs ) {
486 $result->addIndexedTagName(
487 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
488 $this->bl_code );
489 }
490 if ( !$fit ) {
491 break;
492 }
493
494 $idx++;
495 }
496 }
497
498 $result->addIndexedTagName(
499 [ 'query', $this->getModuleName() ],
500 $this->bl_code
501 );
502 }
503 if ( !is_null( $this->continueStr ) ) {
504 $this->setContinueEnumParameter( 'continue', $this->continueStr );
505 }
506 }
507
508 public function getAllowedParams() {
509 $retval = [
510 'title' => [
511 ApiBase::PARAM_TYPE => 'string',
512 ],
513 'pageid' => [
514 ApiBase::PARAM_TYPE => 'integer',
515 ],
516 'continue' => [
517 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
518 ],
519 'namespace' => [
521 ApiBase::PARAM_TYPE => 'namespace'
522 ],
523 'dir' => [
524 ApiBase::PARAM_DFLT => 'ascending',
526 'ascending',
527 'descending'
528 ]
529 ],
530 'filterredir' => [
531 ApiBase::PARAM_DFLT => 'all',
533 'all',
534 'redirects',
535 'nonredirects'
536 ]
537 ],
538 'limit' => [
540 ApiBase::PARAM_TYPE => 'limit',
544 ]
545 ];
546 if ( $this->getModuleName() == 'embeddedin' ) {
547 return $retval;
548 }
549 $retval['redirect'] = false;
550
551 return $retval;
552 }
553
554 protected function getExamplesMessages() {
555 static $examples = [
556 'backlinks' => [
557 'action=query&list=backlinks&bltitle=Main%20Page'
558 => 'apihelp-query+backlinks-example-simple',
559 'action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
560 => 'apihelp-query+backlinks-example-generator',
561 ],
562 'embeddedin' => [
563 'action=query&list=embeddedin&eititle=Template:Stub'
564 => 'apihelp-query+embeddedin-example-simple',
565 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
566 => 'apihelp-query+embeddedin-example-generator',
567 ],
568 'imageusage' => [
569 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
570 => 'apihelp-query+imageusage-example-simple',
571 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
572 => 'apihelp-query+imageusage-example-generator',
573 ]
574 ];
575
576 return $examples[$this->getModuleName()];
577 }
578
579 public function getHelpUrls() {
580 return $this->helpUrl;
581 }
582}
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
Definition ApiBase.php:103
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:97
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:94
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:55
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:106
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:259
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:131
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:261
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:58
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addFields( $value)
Add a set of fields to select to the internal array.
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.
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.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addWhere( $value)
Add a set of WHERE clauses to the internal array.
This is the main query class.
Definition ApiQuery.php:37
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Represents a title within MediaWiki.
Definition Title.php:42
const NS_FILE
Definition Defines.php:75
const LIST_OR
Definition Defines.php:51
$sort