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