MediaWiki REL1_39
ApiQueryLinks.php
Go to the documentation of this file.
1<?php
28
35
36 private const LINKS = 'links';
37 private const TEMPLATES = 'templates';
38
39 private $table, $prefix, $titlesParam, $helpUrl;
40
42 private $linkBatchFactory;
43
45 private $linksMigration;
46
53 public function __construct(
54 ApiQuery $query,
55 $moduleName,
56 LinkBatchFactory $linkBatchFactory,
57 LinksMigration $linksMigration
58 ) {
59 switch ( $moduleName ) {
60 case self::LINKS:
61 $this->table = 'pagelinks';
62 $this->prefix = 'pl';
63 $this->titlesParam = 'titles';
64 $this->helpUrl = 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Links';
65 break;
66 case self::TEMPLATES:
67 $this->table = 'templatelinks';
68 $this->prefix = 'tl';
69 $this->titlesParam = 'templates';
70 $this->helpUrl = 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Templates';
71 break;
72 default:
73 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
74 }
75
76 parent::__construct( $query, $moduleName, $this->prefix );
77 $this->linkBatchFactory = $linkBatchFactory;
78 $this->linksMigration = $linksMigration;
79 }
80
81 public function execute() {
82 $this->run();
83 }
84
85 public function getCacheMode( $params ) {
86 return 'public';
87 }
88
89 public function executeGenerator( $resultPageSet ) {
90 $this->run( $resultPageSet );
91 }
92
96 private function run( $resultPageSet = null ) {
97 $pages = $this->getPageSet()->getGoodPages();
98 if ( $pages === [] ) {
99 return; // nothing to do
100 }
101
102 $params = $this->extractRequestParams();
103
104 if ( isset( $this->linksMigration::$mapping[$this->table] ) ) {
105 list( $nsField, $titleField ) = $this->linksMigration->getTitleFields( $this->table );
106 $queryInfo = $this->linksMigration->getQueryInfo( $this->table );
107 $this->addTables( $queryInfo['tables'] );
108 $this->addJoinConds( $queryInfo['joins'] );
109 } else {
110 $this->addTables( $this->table );
111 $nsField = $this->prefix . '_namespace';
112 $titleField = $this->prefix . '_title';
113 }
114
115 $this->addFields( [
116 'pl_from' => $this->prefix . '_from',
117 'pl_namespace' => $nsField,
118 'pl_title' => $titleField,
119 ] );
120
121 $this->addWhereFld( $this->prefix . '_from', array_keys( $pages ) );
122
123 $multiNS = true;
124 $multiTitle = true;
125 if ( $params[$this->titlesParam] ) {
126 // Filter the titles in PHP so our ORDER BY bug avoidance below works right.
127 $filterNS = $params['namespace'] ? array_fill_keys( $params['namespace'], true ) : false;
128
129 $lb = $this->linkBatchFactory->newLinkBatch();
130 foreach ( $params[$this->titlesParam] as $t ) {
132 if ( !$title || $title->isExternal() ) {
133 $this->addWarning( [ 'apiwarn-invalidtitle', wfEscapeWikiText( $t ) ] );
134 } elseif ( !$filterNS || isset( $filterNS[$title->getNamespace()] ) ) {
135 $lb->addObj( $title );
136 }
137 }
138 $cond = $lb->constructSet( $this->prefix, $this->getDB() );
139 if ( $cond ) {
140 $this->addWhere( $cond );
141 $multiNS = count( $lb->data ) !== 1;
142 $multiTitle = count( array_merge( ...$lb->data ) ) !== 1;
143 } else {
144 // No titles so no results
145 return;
146 }
147 } elseif ( $params['namespace'] ) {
148 $this->addWhereFld( $nsField, $params['namespace'] );
149 $multiNS = $params['namespace'] === null || count( $params['namespace'] ) !== 1;
150 }
151
152 if ( $params['continue'] !== null ) {
153 $cont = explode( '|', $params['continue'] );
154 $this->dieContinueUsageIf( count( $cont ) != 3 );
155 $op = $params['dir'] == 'descending' ? '<' : '>';
156 $plfrom = (int)$cont[0];
157 $plns = (int)$cont[1];
158 $pltitle = $this->getDB()->addQuotes( $cont[2] );
159 $this->addWhere(
160 "{$this->prefix}_from $op $plfrom OR " .
161 "({$this->prefix}_from = $plfrom AND " .
162 "($nsField $op $plns OR " .
163 "($nsField = $plns AND " .
164 "$titleField $op= $pltitle)))"
165 );
166 }
167
168 $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
169 // Here's some MySQL craziness going on: if you use WHERE foo='bar'
170 // and later ORDER BY foo MySQL doesn't notice the ORDER BY is pointless
171 // but instead goes and filesorts, because the index for foo was used
172 // already. To work around this, we drop constant fields in the WHERE
173 // clause from the ORDER BY clause
174 $order = [];
175 if ( count( $pages ) !== 1 ) {
176 $order[] = $this->prefix . '_from' . $sort;
177 }
178 if ( $multiNS ) {
179 $order[] = $nsField . $sort;
180 }
181 if ( $multiTitle ) {
182 $order[] = $titleField . $sort;
183 }
184 if ( $order ) {
185 $this->addOption( 'ORDER BY', $order );
186 }
187 $this->addOption( 'LIMIT', $params['limit'] + 1 );
188
189 $res = $this->select( __METHOD__ );
190
191 if ( $resultPageSet === null ) {
192 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__, 'pl' );
193
194 $count = 0;
195 foreach ( $res as $row ) {
196 if ( ++$count > $params['limit'] ) {
197 // We've reached the one extra which shows that
198 // there are additional pages to be had. Stop here...
199 $this->setContinueEnumParameter( 'continue',
200 "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
201 break;
202 }
203 $vals = [];
204 ApiQueryBase::addTitleInfo( $vals, Title::makeTitle( $row->pl_namespace, $row->pl_title ) );
205 $fit = $this->addPageSubItem( $row->pl_from, $vals );
206 if ( !$fit ) {
207 $this->setContinueEnumParameter( 'continue',
208 "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
209 break;
210 }
211 }
212 } else {
213 $titles = [];
214 $count = 0;
215 foreach ( $res as $row ) {
216 if ( ++$count > $params['limit'] ) {
217 // We've reached the one extra which shows that
218 // there are additional pages to be had. Stop here...
219 $this->setContinueEnumParameter( 'continue',
220 "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
221 break;
222 }
223 $titles[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
224 }
225 $resultPageSet->populateFromTitles( $titles );
226 }
227 }
228
229 public function getAllowedParams() {
230 return [
231 'namespace' => [
232 ParamValidator::PARAM_TYPE => 'namespace',
233 ParamValidator::PARAM_ISMULTI => true,
234 NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
235 ],
236 'limit' => [
237 ParamValidator::PARAM_DEFAULT => 10,
238 ParamValidator::PARAM_TYPE => 'limit',
239 IntegerDef::PARAM_MIN => 1,
240 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
241 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
242 ],
243 'continue' => [
244 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
245 ],
246 $this->titlesParam => [
247 ParamValidator::PARAM_ISMULTI => true,
248 ],
249 'dir' => [
250 ParamValidator::PARAM_DEFAULT => 'ascending',
251 ParamValidator::PARAM_TYPE => [
252 'ascending',
253 'descending'
254 ]
255 ],
256 ];
257 }
258
259 protected function getExamplesMessages() {
260 $name = $this->getModuleName();
261 $path = $this->getModulePath();
262 $title = Title::newMainPage()->getPrefixedText();
263 $mp = rawurlencode( $title );
264
265 return [
266 "action=query&prop={$name}&titles={$mp}"
267 => "apihelp-{$path}-example-simple",
268 "action=query&generator={$name}&titles={$mp}&prop=info"
269 => "apihelp-{$path}-example-generator",
270 "action=query&prop={$name}&titles={$mp}&{$this->prefix}namespace=2|10"
271 => "apihelp-{$path}-example-namespaces",
272 ];
273 }
274
275 public function getHelpUrls() {
276 return $this->helpUrl;
277 }
278}
const NS_SPECIAL
Definition Defines.php:53
const NS_MEDIA
Definition Defines.php:52
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1643
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1656
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:221
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:765
getModulePath()
Get the path to this module.
Definition ApiBase.php:573
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:163
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1372
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:498
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.
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.
getDB()
Get the Query database connection (read-only)
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
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.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getPageSet()
Get the PageSet object to work on.
This is the main query class.
Definition ApiQuery.php:41
Service for compat reading of links tables.
Type definition for namespace types.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition Title.php:370
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition Title.php:638
Service for formatting and validating API parameters.
Type definition for integer types.