Debian Codegraph @

extensions/TextExtracts/includes/ApiQueryExtracts.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\TextExtracts;
4
5 use MediaWiki\Api\ApiBase;
6 use MediaWiki\Api\ApiQuery;
7 use MediaWiki\Api\ApiQueryBase;
8 use MediaWiki\Api\ApiUsageException;
9 use MediaWiki\Config\Config;
10 use MediaWiki\Config\ConfigFactory;
11 use MediaWiki\Languages\LanguageConverterFactory;
12 use MediaWiki\Logger\LoggerFactory;
13 use MediaWiki\MediaWikiServices;
14 use MediaWiki\Page\PageIdentity;
15 use MediaWiki\Page\WikiPageFactory;
16 use MediaWiki\Parser\ParserOptions;
17 use MediaWiki\Title\TitleFormatter;
18 use Wikimedia\ObjectCache\WANObjectCache;
19 use Wikimedia\ParamValidator\ParamValidator;
20 use WikiPage;
21
22 /**
23 * @license GPL-2.0-or-later
24 */
25 class ApiQueryExtracts extends ApiQueryBase {
26
27 /**
28 * Bump when memcache needs clearing
29 */
30 private const CACHE_VERSION = 2;
31
32 private const PREFIX = 'ex';
33
34 /**
35 * @var array
36 */
37 private $params;
38
39 /**
40 * @var Config
41 */
42 private $config;
43 /**
44 * @var WANObjectCache
45 */
46 private $cache;
47 /**
48 * @var LanguageConverterFactory
49 */
50 private $langConvFactory;
51 /**
52 * @var WikiPageFactory
53 */
54 private $wikiPageFactory;
55 private TitleFormatter $titleFormatter;
56
57 // TODO: Allow extensions to hook into this to opt-in.
58 // This is partly for security reasons; see T107170.
59 /**
60 * @var string[]
61 */
62 private $supportedContentModels = [ 'wikitext' ];
63
64 /**
65 * @param ApiQuery $query API query module object
66 * @param string $moduleName Name of this query module
67 * @param ConfigFactory $configFactory
68 * @param WANObjectCache $cache
69 * @param LanguageConverterFactory $langConvFactory
70 * @param WikiPageFactory $wikiPageFactory
71 * @param TitleFormatter $titleFormatter
72 */
73 public function __construct(
74 $query,
75 $moduleName,
76 ConfigFactory $configFactory,
77 WANObjectCache $cache,
78 LanguageConverterFactory $langConvFactory,
79 WikiPageFactory $wikiPageFactory,
80 TitleFormatter $titleFormatter
81 ) {
82 parent::__construct( $query, $moduleName, self::PREFIX );
83 $this->config = $configFactory->makeConfig( 'textextracts' );
84 $this->cache = $cache;
85 $this->langConvFactory = $langConvFactory;
86 $this->wikiPageFactory = $wikiPageFactory;
87 $this->titleFormatter = $titleFormatter;
88 }
89
90 /**
91 * Evaluates the parameters, performs the requested extraction of text,
92 * and sets up the result
93 */
94 public function execute() {
95 $titles = $this->getPageSet()->getGoodPages();
96 if ( $titles === [] ) {
97 return;
98 }
99 $isXml = $this->getMain()->isInternalMode()
100 || $this->getMain()->getPrinter()->getFormat() == 'XML';
101 foreach ( $titles as $id => $t ) {
102 if ( !$this->getAuthority()->authorizeRead( 'read', $t ) ) {
103 $this->addWarning( [
104 'apierror-cannotviewtitle',
105 wfEscapeWikiText( $this->titleFormatter->getPrefixedText( $t ) )
106 ] );
107 unset( $titles[$id] );
108 }
109 }
110 $result = $this->getResult();
111 $params = $this->params = $this->extractRequestParams();
112 $this->requireMaxOneParameter( $params, 'chars', 'sentences' );
113 $continue = 0;
114 $limit = intval( $params['limit'] );
115 if ( $limit > 1 && !$params['intro'] && count( $titles ) > 1 ) {
116 $limit = 1;
117 $this->addWarning( [ 'apiwarn-textextracts-limit', $limit ] );
118 }
119 if ( isset( $params['continue'] ) ) {
120 $continue = intval( $params['continue'] );
121 $this->dieContinueUsageIf( $continue < 0 || $continue > count( $titles ) );
122 $titles = array_slice( $titles, $continue, null, true );
123 }
124 $count = 0;
125 $titleInFileNamespace = false;
126 /** @var PageIdentity $t */
127 foreach ( $titles as $id => $t ) {
128 if ( ++$count > $limit ) {
129 $this->setContinueEnumParameter( 'continue', $continue + $count - 1 );
130 break;
131 }
132
133 if ( $t->getNamespace() === NS_FILE ) {
134 $text = '';
135 $titleInFileNamespace = true;
136 } else {
137 $params = $this->params;
138 $text = $this->getExtract( $t );
139 $text = $this->truncate( $text );
140 if ( $params['plaintext'] ) {
141 $text = $this->doSections( $text );
142 } else {
143 if ( $params['sentences'] ) {
144 $this->addWarning( $this->msg( 'apiwarn-textextracts-sentences-and-html', self::PREFIX ) );
145 }
146 $this->addWarning( 'apiwarn-textextracts-malformed-html' );
147 }
148 }
149
150 if ( $isXml ) {
151 $fit = $result->addValue( [ 'query', 'pages', $id ], 'extract', [ '*' => $text ] );
152 } else {
153 $fit = $result->addValue( [ 'query', 'pages', $id ], 'extract', $text );
154 }
155 if ( !$fit ) {
156 $this->setContinueEnumParameter( 'continue', $continue + $count - 1 );
157 break;
158 }
159 }
160 if ( $titleInFileNamespace ) {
161 $this->addWarning( 'apiwarn-textextracts-title-in-file-namespace' );
162 }
163 }
164
165 /**
166 * @param array $params Ignored parameters
167 * @return string
168 */
169 public function getCacheMode( $params ) {
170 return 'public';
171 }
172
173 /**
174 * Returns a processed, but not trimmed extract
175 * @param PageIdentity $title
176 * @return string
177 */
178 private function getExtract( PageIdentity $title ) {
179 $page = $this->wikiPageFactory->newFromTitle( $title );
180
181 $contentModel = $page->getContentModel();
182 if ( !in_array( $contentModel, $this->supportedContentModels, true ) ) {
183 $this->addWarning( [
184 'apiwarn-textextracts-unsupportedmodel',
185 wfEscapeWikiText( $this->titleFormatter->getPrefixedText( $title ) ),
186 $contentModel
187 ] );
188 return '';
189 }
190
191 $introOnly = $this->params['intro'];
192 $text = $this->getFromCache( $page, $introOnly );
193 // if we need just first section, try retrieving full page and getting first section out of it
194 if ( $text === false && $introOnly ) {
195 $text = $this->getFromCache( $page, false );
196 if ( $text !== false ) {
197 $text = $this->getFirstSection( $text, $this->params['plaintext'] );
198 }
199 }
200 if ( $text === false ) {
201 $text = $this->parse( $page );
202 $text = $this->convertText( $text );
203 $this->setCache( $page, $text );
204 }
205 return $text;
206 }
207
208 /**
209 * @param WANObjectCache $cache
210 * @param WikiPage $page
211 * @param bool $introOnly
212 * @return string
213 */
214 private function cacheKey( WANObjectCache $cache, WikiPage $page, $introOnly ) {
215 $langConv = $this->langConvFactory->getLanguageConverter( $page->getTitle()->getPageLanguage() );
216 return $cache->makeKey( 'textextracts', self::CACHE_VERSION,
217 $page->getId(), $page->getTouched(),
218 $langConv->getPreferredVariant(),
219 $this->params['plaintext'] ? 'plaintext' : 'html',
220 $introOnly ? 'intro' : 'full'
221 );
222 }
223
224 /**
225 * @param WikiPage $page
226 * @param bool $introOnly
227 * @return string|false
228 */
229 private function getFromCache( WikiPage $page, $introOnly ) {
230 $cache = $this->cache;
231 // @TODO: replace with getWithSetCallback()
232 $key = $this->cacheKey( $cache, $page, $introOnly );
233 return $cache->get( $key );
234 }
235
236 /**
237 * @param WikiPage $page
238 * @param string $text
239 */
240 private function setCache( WikiPage $page, $text ) {
241 $cache = $this->cache;
242 // @TODO: replace with getWithSetCallback()
243 $key = $this->cacheKey( $cache, $page, $this->params['intro'] );
244 $cache->set( $key, $text, $this->getConfig()->get( 'ParserCacheExpireTime' ) );
245 }
246
247 /**
248 * @param string $text
249 * @param bool $plainText
250 * @return string
251 */
252 private function getFirstSection( $text, $plainText ) {
253 if ( $plainText ) {
254 $regexp = '/^.*?(?=' . ExtractFormatter::SECTION_MARKER_START .
255 '(?!.' . ExtractFormatter::SECTION_MARKER_END . '<h2 id="mw-toc-heading"))/s';
256 } else {
257 $regexp = '/^.*?(?=<h[1-6]\b(?! id="mw-toc-heading"))/s';
258 }
259 if ( preg_match( $regexp, $text, $matches ) ) {
260 $text = $matches[0];
261 }
262 return $text;
263 }
264
265 /**
266 * Returns page HTML
267 * @param WikiPage $page
268 * @return string
269 * @throws ApiUsageException
270 */
271 private function parse( WikiPage $page ) {
272 $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
273 $status = $parserOutputAccess->getParserOutput(
274 $page->toPageRecord(),
275 ParserOptions::newFromAnon()
276 );
277 if ( $status->isOK() ) {
278 $pout = $status->getValue();
279 $text = $pout->getText( [ 'unwrap' => true ] );
280 if ( $this->params['intro'] ) {
281 $text = $this->getFirstSection( $text, false );
282 }
283 return $text;
284 } else {
285 LoggerFactory::getInstance( 'textextracts' )->warning(
286 'Parse attempt failed while generating text extract', [
287 'title' => $page->getTitle()->getFullText(),
288 'url' => $this->getRequest()->getFullRequestURL(),
289 'reason' => $status->getWikiText( false, false, 'en' )
290 ] );
291 $this->dieStatus( $status );
292 }
293 }
294
295 /**
296 * Converts page HTML into an extract
297 * @param string $text
298 * @return string
299 */
300 private function convertText( $text ) {
301 $fmt = new ExtractFormatter( $text, $this->params['plaintext'] );
302 $fmt->remove( $this->config->get( 'ExtractsRemoveClasses' ) );
303 $text = $fmt->getText();
304 return $text;
305 }
306
307 /**
308 * Truncate the given text to a certain number of characters or sentences
309 * @param string $text The text to truncate
310 * @return string
311 */
312 private function truncate( $text ) {
313 $useTidy = !$this->params['plaintext'];
314 $truncator = new TextTruncator( $useTidy );
315
316 if ( $this->params['chars'] ) {
317 $truncatedText = $truncator->getFirstChars( $text, $this->params['chars'] );
318 if ( $truncatedText !== $text ) {
319 $text = $truncatedText . $this->msg( 'ellipsis' )->text();
320 }
321 } elseif ( $this->params['sentences'] ) {
322 $text = $truncator->getFirstSentences( $text, $this->params['sentences'] );
323 }
324 return $text;
325 }
326
327 /**
328 * @param string $text
329 * @return string
330 */
331 private function doSections( $text ) {
332 $pattern = '/' .
333 ExtractFormatter::SECTION_MARKER_START . '(\d)' .
334 ExtractFormatter::SECTION_MARKER_END . '(.*)/';
335
336 switch ( $this->params['sectionformat'] ) {
337 case 'raw':
338 return $text;
339
340 case 'wiki':
341 return preg_replace_callback( $pattern, static function ( $matches ) {
342 $bars = str_repeat( '=', $matches[1] );
343 return "\n$bars " . trim( $matches[2] ) . " $bars";
344 }, $text );
345
346 case 'plain':
347 return preg_replace_callback( $pattern, static function ( $matches ) {
348 return "\n" . trim( $matches[2] );
349 }, $text );
350
351 default:
352 throw new \LogicException( 'Invalid sectionformat' );
353 }
354 }
355
356 /**
357 * @inheritDoc
358 */
359 public function getAllowedParams() {
360 return [
361 'chars' => [
362 ApiBase::PARAM_TYPE => 'integer',
363 ApiBase::PARAM_MIN => 1,
364 ApiBase::PARAM_MAX => 1200,
365 ],
366 'sentences' => [
367 ApiBase::PARAM_TYPE => 'integer',
368 ApiBase::PARAM_MIN => 1,
369 ApiBase::PARAM_MAX => 10,
370 ],
371 'limit' => [
372 ParamValidator::PARAM_DEFAULT => 20,
373 ApiBase::PARAM_TYPE => 'limit',
374 ApiBase::PARAM_MIN => 1,
375 ApiBase::PARAM_MAX => 20,
376 ApiBase::PARAM_MAX2 => 20,
377 ],
378 'intro' => false,
379 'plaintext' => false,
380 'sectionformat' => [
381 ApiBase::PARAM_TYPE => [ 'plain', 'wiki', 'raw' ],
382 ParamValidator::PARAM_DEFAULT => 'wiki',
383 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
384 ],
385 'continue' => [
386 ApiBase::PARAM_TYPE => 'integer',
387 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
388 ],
389 ];
390 }
391
392 /**
393 * @inheritDoc
394 */
395 protected function getExamplesMessages() {
396 return [
397 'action=query&prop=extracts&exchars=175&titles=Therion'
398 => 'apihelp-query+extracts-example-1',
399 ];
400 }
401
402 /**
403 * @inheritDoc
404 */
405 public function getHelpUrls() {
406 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:TextExtracts#API';
407 }
408
409 }