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