File: ApiQueryExtracts.php

package info (click to toggle)
mediawiki 1%3A1.35.13-1%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 274,932 kB
  • sloc: php: 677,563; javascript: 572,709; sql: 11,565; python: 4,447; xml: 3,145; sh: 892; perl: 788; ruby: 496; pascal: 365; makefile: 128
file content (400 lines) | stat: -rw-r--r-- 11,099 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
<?php

namespace TextExtracts;

use ApiBase;
use ApiMain;
use ApiQueryBase;
use ApiUsageException;
use Config;
use FauxRequest;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MediaWikiServices;
use ParserOptions;
use Title;
use User;
use WANObjectCache;
use WikiPage;

/**
 * @license GPL-2.0-or-later
 */
class ApiQueryExtracts extends ApiQueryBase {

	/**
	 * Bump when memcache needs clearing
	 */
	private const CACHE_VERSION = 2;

	private const PREFIX = 'ex';

	private $params;
	/**
	 * @var Config
	 */
	private $config;
	/**
	 * @var WANObjectCache
	 */
	private $cache;

	// TODO: Allow extensions to hook into this to opt-in.
	// This is partly for security reasons; see T107170.
	/**
	 * @var array
	 */
	private $supportedContentModels = [ 'wikitext' ];

	/**
	 * @param \ApiQuery $query API query module object
	 * @param string $moduleName Name of this query module
	 * @param Config $conf MediaWiki configuration
	 * @param WANObjectCache $cache
	 */
	public function __construct( $query, $moduleName, Config $conf, WANObjectCache $cache ) {
		parent::__construct( $query, $moduleName, self::PREFIX );
		$this->config = $conf;
		$this->cache = $cache;
	}

	/**
	 * Evaluates the parameters, performs the requested extraction of text,
	 * and sets up the result
	 * @return null
	 */
	public function execute() {
		$titles = $this->getPageSet()->getGoodTitles();
		if ( $titles === [] ) {
			return;
		}
		$isXml = $this->getMain()->isInternalMode()
			|| $this->getMain()->getPrinter()->getFormat() == 'XML';
		$result = $this->getResult();
		$params = $this->params = $this->extractRequestParams();
		$this->requireMaxOneParameter( $params, 'chars', 'sentences' );
		$continue = 0;
		$limit = intval( $params['limit'] );
		if ( $limit > 1 && !$params['intro'] && count( $titles ) > 1 ) {
			$limit = 1;
			$this->addWarning( [ 'apiwarn-textextracts-limit', $limit ] );
		}
		if ( isset( $params['continue'] ) ) {
			$continue = intval( $params['continue'] );
			$this->dieContinueUsageIf( $continue < 0 || $continue > count( $titles ) );
			$titles = array_slice( $titles, $continue, null, true );
		}
		$count = 0;
		$titleInFileNamespace = false;
		/** @var Title $t */
		foreach ( $titles as $id => $t ) {
			if ( ++$count > $limit ) {
				$this->setContinueEnumParameter( 'continue', $continue + $count - 1 );
				break;
			}

			if ( $t->inNamespace( NS_FILE ) ) {
				$text = '';
				$titleInFileNamespace = true;
			} else {
				$params = $this->params;
				$text = $this->getExtract( $t );
				$text = $this->truncate( $text );
				if ( $params['plaintext'] ) {
					$text = $this->doSections( $text );
				} else {
					if ( $params['sentences'] ) {
						$this->addWarning( $this->msg( 'apiwarn-textextracts-sentences-and-html', self::PREFIX ) );
					}
					$this->addWarning( 'apiwarn-textextracts-malformed-html' );
				}
			}

			if ( $isXml ) {
				$fit = $result->addValue( [ 'query', 'pages', $id ], 'extract', [ '*' => $text ] );
			} else {
				$fit = $result->addValue( [ 'query', 'pages', $id ], 'extract', $text );
			}
			if ( !$fit ) {
				$this->setContinueEnumParameter( 'continue', $continue + $count - 1 );
				break;
			}
		}
		if ( $titleInFileNamespace ) {
			$this->addWarning( 'apiwarn-textextracts-title-in-file-namespace' );
		}
	}

	/**
	 * @param array $params Ignored parameters
	 * @return string
	 */
	public function getCacheMode( $params ) {
		return 'public';
	}

	/**
	 * Returns a processed, but not trimmed extract
	 * @param Title $title
	 * @return string
	 */
	private function getExtract( Title $title ) {
		$contentModel = $title->getContentModel();
		if ( !in_array( $contentModel, $this->supportedContentModels, true ) ) {
			$this->addWarning( [
				'apiwarn-textextracts-unsupportedmodel',
				wfEscapeWikiText( $title->getPrefixedText() ),
				$contentModel
			] );
			return '';
		}

		$page = WikiPage::factory( $title );

		$introOnly = $this->params['intro'];
		$text = $this->getFromCache( $page, $introOnly );
		// if we need just first section, try retrieving full page and getting first section out of it
		if ( $text === false && $introOnly ) {
			$text = $this->getFromCache( $page, false );
			if ( $text !== false ) {
				$text = $this->getFirstSection( $text, $this->params['plaintext'] );
			}
		}
		if ( $text === false ) {
			$text = $this->parse( $page );
			$text = $this->convertText( $text );
			$this->setCache( $page, $text );
		}
		return $text;
	}

	private function cacheKey( WANObjectCache $cache, WikiPage $page, $introOnly ) {
		return $cache->makeKey( 'textextracts', self::CACHE_VERSION,
			$page->getId(), $page->getTouched(),
			$page->getTitle()->getPageLanguage()->getPreferredVariant(),
			$this->params['plaintext'] ? 'plaintext' : 'html',
			$introOnly ? 'intro' : 'full'
		);
	}

	private function getFromCache( WikiPage $page, $introOnly ) {
		$cache = $this->cache;
		// @TODO: replace with getWithSetCallback()
		$key = $this->cacheKey( $cache, $page, $introOnly );
		return $cache->get( $key );
	}

	private function setCache( WikiPage $page, $text ) {
		$cache = $this->cache;
		// @TODO: replace with getWithSetCallback()
		$key = $this->cacheKey( $cache, $page, $this->params['intro'] );
		$cache->set( $key, $text, $this->getConfig()->get( 'ParserCacheExpireTime' ) );
	}

	private function getFirstSection( $text, $plainText ) {
		if ( $plainText ) {
			$regexp = '/^(.*?)(?=' . ExtractFormatter::SECTION_MARKER_START . ')/s';
		} else {
			$regexp = '/^(.*?)(?=<h[1-6]\b)/s';
		}
		if ( preg_match( $regexp, $text, $matches ) ) {
			$text = $matches[0];
		}
		return $text;
	}

	/**
	 * Returns page HTML
	 * @param WikiPage $page
	 * @return string|null
	 * @throws ApiUsageException
	 */
	private function parse( WikiPage $page ) {
		$apiException = null;
		$parserOptions = new ParserOptions( new User() );

		// first try finding full page in parser cache
		if ( $page->shouldCheckParserCache( $parserOptions, 0 ) ) {
			$pout = MediaWikiServices::getInstance()->getParserCache()->get( $page, $parserOptions );
			if ( $pout ) {
				$text = $pout->getText( [ 'unwrap' => true ] );
				if ( $this->params['intro'] ) {
					$text = $this->getFirstSection( $text, false );
				}
				return $text;
			}
		}
		$request = [
			'action' => 'parse',
			'page' => $page->getTitle()->getPrefixedText(),
			'prop' => 'text',
			// Invokes special handling when using partial wikitext (T168743)
			'sectionpreview' => 1,
			'wrapoutputclass' => '',
		];
		if ( $this->params['intro'] ) {
			$request['section'] = 0;
		}
		// in case of cache miss, render just the needed section
		$api = new ApiMain( new FauxRequest( $request ) );
		try {
			$api->execute();
			$data = $api->getResult()->getResultData( null, [
				'BC' => [],
				'Types' => [],
			] );
		} catch ( ApiUsageException $e ) {
			$apiException = $e->__toString();
			if ( $e->getStatusValue()->hasMessage( 'apierror-nosuchsection' ) ) {
				// Looks like we tried to get the intro to a page without
				// sections!  Lets just grab what we can get.
				unset( $request['section'] );
				$api = new ApiMain( new FauxRequest( $request ) );
				$api->execute();
				$data = $api->getResult()->getResultData( null, [
					'BC' => [],
					'Types' => [],
				] );
			} else {
				// Some other unexpected error - lets just report it to the user
				// on the off chance that is the right thing.
				throw $e;
			}
		}
		if ( !array_key_exists( 'parse', $data ) ) {
			LoggerFactory::getInstance( 'textextracts' )->warning(
				'API Parse request failed while generating text extract', [
					'title' => $page->getTitle()->getFullText(),
					'url' => $this->getRequest()->getFullRequestURL(),
					'exception' => $apiException,
					'request' => $request
			] );
			return null;
		}

		return $data['parse']['text']['*'];
	}

	/**
	 * @param \ApiQuery $query API query module
	 * @param string $name Name of this query module
	 * @return ApiQueryExtracts
	 */
	public static function factory( $query, $name ) {
		$config = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'textextracts' );
		$cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
		return new self( $query, $name, $config, $cache );
	}

	/**
	 * Converts page HTML into an extract
	 * @param string $text
	 * @return string
	 */
	private function convertText( $text ) {
		$fmt = new ExtractFormatter( $text, $this->params['plaintext'] );
		$fmt->remove( $this->config->get( 'ExtractsRemoveClasses' ) );
		$text = $fmt->getText();
		return $text;
	}

	/**
	 * Truncate the given text to a certain number of characters or sentences
	 * @param string $text The text to truncate
	 * @return string
	 */
	private function truncate( $text ) {
		if ( !$this->params['plaintext'] ) {
			$truncator = new TextTruncator( true );
		} else {
			$truncator = new TextTruncator( false );
		}

		if ( $this->params['chars'] ) {
			$text = $truncator->getFirstChars( $text, $this->params['chars'] ) .
				$this->msg( 'ellipsis' )->text();
		} elseif ( $this->params['sentences'] ) {
			$text = $truncator->getFirstSentences( $text, $this->params['sentences'] );
		}
		return $text;
	}

	private function doSections( $text ) {
		$pattern = '/' .
			ExtractFormatter::SECTION_MARKER_START . '(\d)' .
			ExtractFormatter::SECTION_MARKER_END . '(.*)/';

		switch ( $this->params['sectionformat'] ) {
			case 'raw':
				return $text;

			case 'wiki':
				return preg_replace_callback( $pattern, function ( $matches ) {
					$bars = str_repeat( '=', $matches[1] );
					return "\n$bars " . trim( $matches[2] ) . " $bars";
				}, $text );

			case 'plain':
				return preg_replace_callback( $pattern, function ( $matches ) {
					return "\n" . trim( $matches[2] );
				}, $text );

			default:
				throw new \LogicException( 'Invalid sectionformat' );
		}
	}

	/**
	 * Return an array describing all possible parameters to this module
	 * @return array
	 */
	public function getAllowedParams() {
		return [
			'chars' => [
				ApiBase::PARAM_TYPE => 'integer',
				ApiBase::PARAM_MIN => 1,
				ApiBase::PARAM_MAX => 1200,
			],
			'sentences' => [
				ApiBase::PARAM_TYPE => 'integer',
				ApiBase::PARAM_MIN => 1,
				ApiBase::PARAM_MAX => 10,
			],
			'limit' => [
				ApiBase::PARAM_DFLT => 20,
				ApiBase::PARAM_TYPE => 'limit',
				ApiBase::PARAM_MIN => 1,
				ApiBase::PARAM_MAX => 20,
				ApiBase::PARAM_MAX2 => 20,
			],
			'intro' => false,
			'plaintext' => false,
			'sectionformat' => [
				ApiBase::PARAM_TYPE => [ 'plain', 'wiki', 'raw' ],
				ApiBase::PARAM_DFLT => 'wiki',
			],
			'continue' => [
				ApiBase::PARAM_TYPE => 'integer',
				ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
			],
		];
	}

	/**
	 * @see ApiBase::getExamplesMessages()
	 * @return array
	 */
	protected function getExamplesMessages() {
		return [
			'action=query&prop=extracts&exchars=175&titles=Therion'
				=> 'apihelp-query+extracts-example-1',
		];
	}

	/**
	 * @see ApiBase::getHelpUrls()
	 * @return string
	 */
	public function getHelpUrls() {
		return 'https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:TextExtracts#API';
	}
}