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