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