MediaWiki REL1_31
ApiQueryBacklinks.php
Go to the documentation of this file.
1<?php
32
36 private $rootTitle;
37
40
46 private $pageMap = [];
47 private $resultArr;
48
49 private $redirTitles = [];
50 private $continueStr = null;
51
52 // output element name, database column field prefix, database table
54 'backlinks' => [
55 'code' => 'bl',
56 'prefix' => 'pl',
57 'linktbl' => 'pagelinks',
58 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Backlinks',
59 ],
60 'embeddedin' => [
61 'code' => 'ei',
62 'prefix' => 'tl',
63 'linktbl' => 'templatelinks',
64 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Embeddedin',
65 ],
66 'imageusage' => [
67 'code' => 'iu',
68 'prefix' => 'il',
69 'linktbl' => 'imagelinks',
70 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageusage',
71 ]
72 ];
73
74 public function __construct( ApiQuery $query, $moduleName ) {
75 $settings = $this->backlinksSettings[$moduleName];
76 $prefix = $settings['prefix'];
77 $code = $settings['code'];
78 $this->resultArr = [];
79
80 parent::__construct( $query, $moduleName, $code );
81 $this->bl_ns = $prefix . '_namespace';
82 $this->bl_from = $prefix . '_from';
83 $this->bl_from_ns = $prefix . '_from_namespace';
84 $this->bl_table = $settings['linktbl'];
85 $this->bl_code = $code;
86 $this->helpUrl = $settings['helpurl'];
87
88 $this->hasNS = $moduleName !== 'imageusage';
89 if ( $this->hasNS ) {
90 $this->bl_title = $prefix . '_title';
91 $this->bl_fields = [
94 ];
95 } else {
96 $this->bl_title = $prefix . '_to';
97 $this->bl_fields = [
99 ];
100 }
101 }
102
103 public function execute() {
104 $this->run();
105 }
106
107 public function getCacheMode( $params ) {
108 return 'public';
109 }
110
111 public function executeGenerator( $resultPageSet ) {
112 $this->run( $resultPageSet );
113 }
114
119 private function runFirstQuery( $resultPageSet = null ) {
120 $this->addTables( [ $this->bl_table, 'page' ] );
121 $this->addWhere( "{$this->bl_from}=page_id" );
122 if ( is_null( $resultPageSet ) ) {
123 $this->addFields( [ 'page_id', 'page_title', 'page_namespace' ] );
124 } else {
125 $this->addFields( $resultPageSet->getPageTableFields() );
126 }
127 $this->addFields( [ 'page_is_redirect', 'from_ns' => 'page_namespace' ] );
128
129 $this->addWhereFld( $this->bl_title, $this->rootTitle->getDBkey() );
130 if ( $this->hasNS ) {
131 $this->addWhereFld( $this->bl_ns, $this->rootTitle->getNamespace() );
132 }
133 $this->addWhereFld( $this->bl_from_ns, $this->params['namespace'] );
134
135 if ( count( $this->cont ) >= 2 ) {
136 $op = $this->params['dir'] == 'descending' ? '<' : '>';
137 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
138 $this->addWhere(
139 "{$this->bl_from_ns} $op {$this->cont[0]} OR " .
140 "({$this->bl_from_ns} = {$this->cont[0]} AND " .
141 "{$this->bl_from} $op= {$this->cont[1]})"
142 );
143 } else {
144 $this->addWhere( "{$this->bl_from} $op= {$this->cont[1]}" );
145 }
146 }
147
148 if ( $this->params['filterredir'] == 'redirects' ) {
149 $this->addWhereFld( 'page_is_redirect', 1 );
150 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
151 // T24245 - Check for !redirect, as filtering nonredirects, when
152 // getting what links to them is contradictory
153 $this->addWhereFld( 'page_is_redirect', 0 );
154 }
155
156 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
157 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
158 $orderBy = [];
159 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
160 $orderBy[] = $this->bl_from_ns . $sort;
161 }
162 $orderBy[] = $this->bl_from . $sort;
163 $this->addOption( 'ORDER BY', $orderBy );
164 $this->addOption( 'STRAIGHT_JOIN' );
165
166 $res = $this->select( __METHOD__ );
167 $count = 0;
168 foreach ( $res as $row ) {
169 if ( ++$count > $this->params['limit'] ) {
170 // We've reached the one extra which shows that there are
171 // additional pages to be had. Stop here...
172 // Continue string may be overridden at a later step
173 $this->continueStr = "{$row->from_ns}|{$row->page_id}";
174 break;
175 }
176
177 // Fill in continuation fields for later steps
178 if ( count( $this->cont ) < 2 ) {
179 $this->cont[] = $row->from_ns;
180 $this->cont[] = $row->page_id;
181 }
182
183 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
184 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
185 if ( $row->page_is_redirect ) {
186 $this->redirTitles[] = $t;
187 }
188
189 if ( is_null( $resultPageSet ) ) {
190 $a = [ 'pageid' => intval( $row->page_id ) ];
192 if ( $row->page_is_redirect ) {
193 $a['redirect'] = true;
194 }
195 // Put all the results in an array first
196 $this->resultArr[$a['pageid']] = $a;
197 } else {
198 $resultPageSet->processDbRow( $row );
199 }
200 }
201 }
202
207 private function runSecondQuery( $resultPageSet = null ) {
208 $db = $this->getDB();
209 $this->addTables( [ $this->bl_table, 'page' ] );
210 $this->addWhere( "{$this->bl_from}=page_id" );
211
212 if ( is_null( $resultPageSet ) ) {
213 $this->addFields( [ 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ] );
214 } else {
215 $this->addFields( $resultPageSet->getPageTableFields() );
216 }
217
218 $this->addFields( [ $this->bl_title, 'from_ns' => 'page_namespace' ] );
219 if ( $this->hasNS ) {
220 $this->addFields( $this->bl_ns );
221 }
222
223 // We can't use LinkBatch here because $this->hasNS may be false
224 $titleWhere = [];
225 $allRedirNs = [];
226 $allRedirDBkey = [];
228 foreach ( $this->redirTitles as $t ) {
229 $redirNs = $t->getNamespace();
230 $redirDBkey = $t->getDBkey();
231 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
232 ( $this->hasNS ? " AND {$this->bl_ns} = {$redirNs}" : '' );
233 $allRedirNs[$redirNs] = true;
234 $allRedirDBkey[$redirDBkey] = true;
235 }
236 $this->addWhere( $db->makeList( $titleWhere, LIST_OR ) );
237 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
238
239 if ( count( $this->cont ) >= 6 ) {
240 $op = $this->params['dir'] == 'descending' ? '<' : '>';
241
242 $where = "{$this->bl_from} $op= {$this->cont[5]}";
243 // Don't bother with namespace, title, or from_namespace if it's
244 // otherwise constant in the where clause.
245 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
246 $where = "{$this->bl_from_ns} $op {$this->cont[4]} OR " .
247 "({$this->bl_from_ns} = {$this->cont[4]} AND ($where))";
248 }
249 if ( count( $allRedirDBkey ) > 1 ) {
250 $title = $db->addQuotes( $this->cont[3] );
251 $where = "{$this->bl_title} $op $title OR " .
252 "({$this->bl_title} = $title AND ($where))";
253 }
254 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
255 $where = "{$this->bl_ns} $op {$this->cont[2]} OR " .
256 "({$this->bl_ns} = {$this->cont[2]} AND ($where))";
257 }
258
259 $this->addWhere( $where );
260 }
261 if ( $this->params['filterredir'] == 'redirects' ) {
262 $this->addWhereFld( 'page_is_redirect', 1 );
263 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
264 $this->addWhereFld( 'page_is_redirect', 0 );
265 }
266
267 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
268 $orderBy = [];
269 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
270 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
271 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
272 $orderBy[] = $this->bl_ns . $sort;
273 }
274 if ( count( $allRedirDBkey ) > 1 ) {
275 $orderBy[] = $this->bl_title . $sort;
276 }
277 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
278 $orderBy[] = $this->bl_from_ns . $sort;
279 }
280 $orderBy[] = $this->bl_from . $sort;
281 $this->addOption( 'ORDER BY', $orderBy );
282 $this->addOption( 'USE INDEX', [ 'page' => 'PRIMARY' ] );
283 // T290379: Avoid MariaDB deciding to scan all of `page`.
284 $this->addOption( 'STRAIGHT_JOIN' );
285
286 $res = $this->select( __METHOD__ );
287 $count = 0;
288 foreach ( $res as $row ) {
289 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_FILE;
290
291 if ( ++$count > $this->params['limit'] ) {
292 // We've reached the one extra which shows that there are
293 // additional pages to be had. Stop here...
294 // Note we must keep the parameters for the first query constant
295 // This may be overridden at a later step
296 $title = $row->{$this->bl_title};
297 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 2 ) ) .
298 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
299 break;
300 }
301
302 // Fill in continuation fields for later steps
303 if ( count( $this->cont ) < 6 ) {
304 $this->cont[] = $ns;
305 $this->cont[] = $row->{$this->bl_title};
306 $this->cont[] = $row->from_ns;
307 $this->cont[] = $row->page_id;
308 }
309
310 if ( is_null( $resultPageSet ) ) {
311 $a['pageid'] = intval( $row->page_id );
312 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
313 if ( $row->page_is_redirect ) {
314 $a['redirect'] = true;
315 }
316 $parentID = $this->pageMap[$ns][$row->{$this->bl_title}];
317 // Put all the results in an array first
318 $this->resultArr[$parentID]['redirlinks'][$row->page_id] = $a;
319 } else {
320 $resultPageSet->processDbRow( $row );
321 }
322 }
323 }
324
329 private function run( $resultPageSet = null ) {
330 $this->params = $this->extractRequestParams( false );
331 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
332 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
333 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
334
335 $result = $this->getResult();
336
337 if ( $this->params['limit'] == 'max' ) {
338 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
339 $result->addParsedLimit( $this->getModuleName(), $this->params['limit'] );
340 } else {
341 $this->params['limit'] = intval( $this->params['limit'] );
342 $this->validateLimit( 'limit', $this->params['limit'], 1, $userMax, $botMax );
343 }
344
345 $this->rootTitle = $this->getTitleFromTitleOrPageId( $this->params );
346
347 // only image titles are allowed for the root in imageinfo mode
348 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
349 $this->dieWithError(
350 [ 'apierror-imageusage-badtitle', $this->getModuleName() ],
351 'bad_image_title'
352 );
353 }
354
355 // Parse and validate continuation parameter
356 $this->cont = [];
357 if ( $this->params['continue'] !== null ) {
358 $cont = explode( '|', $this->params['continue'] );
359
360 switch ( count( $cont ) ) {
361 case 8:
362 // redirect page ID for result adding
363 $this->cont[7] = (int)$cont[7];
364 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont[7] );
365
366 /* Fall through */
367
368 case 7:
369 // top-level page ID for result adding
370 $this->cont[6] = (int)$cont[6];
371 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont[6] );
372
373 /* Fall through */
374
375 case 6:
376 // ns for 2nd query (even for imageusage)
377 $this->cont[2] = (int)$cont[2];
378 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont[2] );
379
380 // title for 2nd query
381 $this->cont[3] = $cont[3];
382
383 // from_ns for 2nd query
384 $this->cont[4] = (int)$cont[4];
385 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont[4] );
386
387 // from_id for 1st query
388 $this->cont[5] = (int)$cont[5];
389 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont[5] );
390
391 /* Fall through */
392
393 case 2:
394 // from_ns for 1st query
395 $this->cont[0] = (int)$cont[0];
396 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont[0] );
397
398 // from_id for 1st query
399 $this->cont[1] = (int)$cont[1];
400 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont[1] );
401
402 break;
403
404 default:
405 $this->dieContinueUsageIf( true );
406 }
407
408 ksort( $this->cont );
409 }
410
411 $this->runFirstQuery( $resultPageSet );
412 if ( $this->redirect && count( $this->redirTitles ) ) {
413 $this->resetQueryParams();
414 $this->runSecondQuery( $resultPageSet );
415 }
416
417 // Fill in any missing fields in case it's needed below
418 $this->cont += [ 0, 0, 0, '', 0, 0, 0 ];
419
420 if ( is_null( $resultPageSet ) ) {
421 // Try to add the result data in one go and pray that it fits
422 $code = $this->bl_code;
423 $data = array_map( function ( $arr ) use ( $result, $code ) {
424 if ( isset( $arr['redirlinks'] ) ) {
425 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
426 ApiResult::setIndexedTagName( $arr['redirlinks'], $code );
427 }
428 return $arr;
429 }, array_values( $this->resultArr ) );
430 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
431 if ( !$fit ) {
432 // It didn't fit. Add elements one by one until the
433 // result is full.
434 ksort( $this->resultArr );
435 if ( count( $this->cont ) >= 7 ) {
436 $startAt = $this->cont[6];
437 } else {
438 reset( $this->resultArr );
439 $startAt = key( $this->resultArr );
440 }
441 $idx = 0;
442 foreach ( $this->resultArr as $pageID => $arr ) {
443 if ( $pageID < $startAt ) {
444 continue;
445 }
446
447 // Add the basic entry without redirlinks first
448 $fit = $result->addValue(
449 [ 'query', $this->getModuleName() ],
450 $idx, array_diff_key( $arr, [ 'redirlinks' => '' ] ) );
451 if ( !$fit ) {
452 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
453 "|$pageID";
454 break;
455 }
456
457 $hasRedirs = false;
458 $redirLinks = isset( $arr['redirlinks'] ) ? (array)$arr['redirlinks'] : [];
459 ksort( $redirLinks );
460 if ( count( $this->cont ) >= 8 && $pageID == $startAt ) {
461 $redirStartAt = $this->cont[7];
462 } else {
463 reset( $redirLinks );
464 $redirStartAt = key( $redirLinks );
465 }
466 foreach ( $redirLinks as $key => $redir ) {
467 if ( $key < $redirStartAt ) {
468 continue;
469 }
470
471 $fit = $result->addValue(
472 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
473 null, $redir );
474 if ( !$fit ) {
475 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
476 "|$pageID|$key";
477 break;
478 }
479 $hasRedirs = true;
480 }
481 if ( $hasRedirs ) {
482 $result->addIndexedTagName(
483 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
484 $this->bl_code );
485 }
486 if ( !$fit ) {
487 break;
488 }
489
490 $idx++;
491 }
492 }
493
494 $result->addIndexedTagName(
495 [ 'query', $this->getModuleName() ],
496 $this->bl_code
497 );
498 }
499 if ( !is_null( $this->continueStr ) ) {
500 $this->setContinueEnumParameter( 'continue', $this->continueStr );
501 }
502 }
503
504 public function getAllowedParams() {
505 $retval = [
506 'title' => [
507 ApiBase::PARAM_TYPE => 'string',
508 ],
509 'pageid' => [
510 ApiBase::PARAM_TYPE => 'integer',
511 ],
512 'continue' => [
513 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
514 ],
515 'namespace' => [
517 ApiBase::PARAM_TYPE => 'namespace'
518 ],
519 'dir' => [
520 ApiBase::PARAM_DFLT => 'ascending',
522 'ascending',
523 'descending'
524 ]
525 ],
526 'filterredir' => [
527 ApiBase::PARAM_DFLT => 'all',
529 'all',
530 'redirects',
531 'nonredirects'
532 ]
533 ],
534 'limit' => [
536 ApiBase::PARAM_TYPE => 'limit',
540 ]
541 ];
542 if ( $this->getModuleName() == 'embeddedin' ) {
543 return $retval;
544 }
545 $retval['redirect'] = false;
546
547 return $retval;
548 }
549
550 protected function getExamplesMessages() {
551 static $examples = [
552 'backlinks' => [
553 'action=query&list=backlinks&bltitle=Main%20Page'
554 => 'apihelp-query+backlinks-example-simple',
555 'action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
556 => 'apihelp-query+backlinks-example-generator',
557 ],
558 'embeddedin' => [
559 'action=query&list=embeddedin&eititle=Template:Stub'
560 => 'apihelp-query+embeddedin-example-simple',
561 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
562 => 'apihelp-query+embeddedin-example-generator',
563 ],
564 'imageusage' => [
565 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
566 => 'apihelp-query+imageusage-example-simple',
567 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
568 => 'apihelp-query+imageusage-example-generator',
569 ]
570 ];
571
572 return $examples[$this->getModuleName()];
573 }
574
575 public function getHelpUrls() {
576 return $this->helpUrl;
577 }
578}
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second redirect
and give any other recipients of the Program a copy of this License along with the Program You may charge a fee for the physical act of transferring a and you may at your option offer warranty protection in exchange for a fee You may modify your copy or copies of the Program or any portion of thus forming a work based on the and copy and distribute such modifications or work under the terms of Section provided that you also meet all of these that in whole or in part contains or is derived from the Program or any part to be licensed as a whole at no charge to all third parties under the terms of this License c If the modified program normally reads commands interactively when run
Definition COPYING.txt:104
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
Definition ApiBase.php:96
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:90
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:99
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:234
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:124
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:236
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
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)
addWhereFld( $field, $value)
Equivalent to addWhere(array($field => $value))
addWhere( $value)
Add a set of WHERE clauses to the internal array.
This is the main query class.
Definition ApiQuery.php:36
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Represents a title within MediaWiki.
Definition Title.php:39
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
$res
Definition database.txt:21
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition design.txt:26
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:865
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1620
const NS_FILE
Definition Defines.php:80
const LIST_OR
Definition Defines.php:56
$sort