Update git submodules
[mediawiki.git] / includes / api / ApiQueryLinks.php
blob05260ec4ce37700016652c9af93fd4923fa4c7ef
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 use MediaWiki\Cache\LinkBatchFactory;
24 use MediaWiki\Linker\LinksMigration;
25 use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
26 use MediaWiki\Title\Title;
27 use Wikimedia\ParamValidator\ParamValidator;
28 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
30 /**
31 * A query module to list all wiki links on a given set of pages.
33 * @ingroup API
35 class ApiQueryLinks extends ApiQueryGeneratorBase {
37 private const LINKS = 'links';
38 private const TEMPLATES = 'templates';
40 private $table, $prefix, $titlesParam, $helpUrl;
42 private LinkBatchFactory $linkBatchFactory;
43 private LinksMigration $linksMigration;
45 /**
46 * @param ApiQuery $query
47 * @param string $moduleName
48 * @param LinkBatchFactory $linkBatchFactory
49 * @param LinksMigration $linksMigration
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' );
74 parent::__construct( $query, $moduleName, $this->prefix );
75 $this->linkBatchFactory = $linkBatchFactory;
76 $this->linksMigration = $linksMigration;
79 public function execute() {
80 $this->run();
83 public function getCacheMode( $params ) {
84 return 'public';
87 public function executeGenerator( $resultPageSet ) {
88 $this->run( $resultPageSet );
91 /**
92 * @param ApiPageSet|null $resultPageSet
94 private function run( $resultPageSet = null ) {
95 $pages = $this->getPageSet()->getGoodPages();
96 if ( $pages === [] ) {
97 return; // nothing to do
100 $params = $this->extractRequestParams();
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';
113 $this->addFields( [
114 'pl_from' => $this->prefix . '_from',
115 'pl_namespace' => $nsField,
116 'pl_title' => $titleField,
117 ] );
119 $this->addWhereFld( $this->prefix . '_from', array_keys( $pages ) );
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;
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 );
136 if ( $lb->isEmpty() ) {
137 // No titles, no results!
138 return;
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;
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 ] ) );
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;
170 if ( $multiNS ) {
171 $order[] = $nsField . $sort;
173 if ( $multiTitle ) {
174 $order[] = $titleField . $sort;
176 if ( $order ) {
177 $this->addOption( 'ORDER BY', $order );
179 $this->addOption( 'LIMIT', $params['limit'] + 1 );
181 $res = $this->select( __METHOD__ );
183 if ( $resultPageSet === null ) {
184 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__, 'pl' );
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;
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;
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;
215 $titles[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
217 $resultPageSet->populateFromTitles( $titles );
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 ],
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
235 'continue' => [
236 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
238 $this->titlesParam => [
239 ParamValidator::PARAM_ISMULTI => true,
241 'dir' => [
242 ParamValidator::PARAM_DEFAULT => 'ascending',
243 ParamValidator::PARAM_TYPE => [
244 'ascending',
245 'descending'
251 protected function getExamplesMessages() {
252 $name = $this->getModuleName();
253 $path = $this->getModulePath();
254 $title = Title::newMainPage()->getPrefixedText();
255 $mp = rawurlencode( $title );
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",
267 public function getHelpUrls() {
268 return $this->helpUrl;