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