summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/ParserFunctions/AskParserFunction.php
blob: 6f0b79d323524c538f61364453f5261935aa762f (plain)
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<?php

namespace SMW\ParserFunctions;

use Parser;
use SMW\ApplicationFactory;
use SMW\DIProperty;
use SMW\MessageFormatter;
use SMW\Parser\RecursiveTextProcessor;
use SMW\ParserData;
use SMW\PostProcHandler;
use SMW\ProcessingErrorMsgHandler;
use SMW\Query\Deferred;
use SMW\Utils\CircularReferenceGuard;
use SMWQuery as Query;
use SMWQueryProcessor as QueryProcessor;

/**
 * Provides the {{#ask}} parser function
 *
 * @see http://www.semantic-mediawiki.org/wiki/Help:Ask
 *
 * @license GNU GPL v2+
 * @since 1.9
 *
 * @author Markus Krötzsch
 * @author Jeroen De Dauw
 * @author mwjames
 */
class AskParserFunction {

	/**
	 * Fixed identifier for a deferred query request
	 */
	const DEFERRED_REQUEST = '@deferred';

	/**
	 * Fixed identifier
	 */
	const NO_TRACE = '@notrace';

	/**
	 * Fixed identifier to signal to the PostProcHandler that a post update is
	 * required with the output being used as input value for an annotation.
	 */
	const IS_ANNOTATION = '@annotation';

	/**
	 * @var ParserData
	 */
	private $parserData;

	/**
	 * @var MessageFormatter
	 */
	private $messageFormatter;

	/**
	 * @var CircularReferenceGuard
	 */
	private $circularReferenceGuard;

	/**
	 * @var ExpensiveFuncExecutionWatcher
	 */
	private $expensiveFuncExecutionWatcher;

	/**
	 * @var boolean
	 */
	private $showMode = false;

	/**
	 * @var integer
	 */
	private $context = QueryProcessor::INLINE_QUERY;

	/**
	 * @var PostProcHandler
	 */
	private $postProcHandler;

	/**
	 * @var RecursiveTextProcessor
	 */
	private $recursiveTextProcessor;

	/**
	 * @since 1.9
	 *
	 * @param ParserData $parserData
	 * @param MessageFormatter $messageFormatter
	 * @param CircularReferenceGuard $circularReferenceGuard
	 * @param ExpensiveFuncExecutionWatcher $expensiveFuncExecutionWatcher
	 */
	public function __construct( ParserData $parserData, MessageFormatter $messageFormatter, CircularReferenceGuard $circularReferenceGuard, ExpensiveFuncExecutionWatcher $expensiveFuncExecutionWatcher ) {
		$this->parserData = $parserData;
		$this->messageFormatter = $messageFormatter;
		$this->circularReferenceGuard = $circularReferenceGuard;
		$this->expensiveFuncExecutionWatcher = $expensiveFuncExecutionWatcher;
	}

	/**
	 * @since 3.0
	 *
	 * @param PostProcHandler $postProcHandler
	 */
	public function setPostProcHandler( PostProcHandler $postProcHandler ) {
		$this->postProcHandler = $postProcHandler;
	}

	/**
	 * @since 3.0
	 *
	 * @param RecursiveTextProcessor $recursiveTextProcessor
	 */
	public function setRecursiveTextProcessor( RecursiveTextProcessor $recursiveTextProcessor ) {
		$this->recursiveTextProcessor = $recursiveTextProcessor;
	}

	/**
	 * Enable showMode (normally only invoked by {{#show}})
	 *
	 * @since 1.9
	 *
	 * @return AskParserFunction
	 */
	public function setShowMode( $mode ) {
		$this->showMode = $mode;
		return $this;
	}

	/**
	 * {{#ask}} is disabled (see $smwgQEnabled)
	 *
	 * @since 1.9
	 *
	 * @return string|null
	 */
	public function isQueryDisabled() {
		return $this->messageFormatter->addFromKey( 'smw_iq_disabled' )->getHtml();
	}

	/**
	 * Parse parameters, return results from the query printer and update the
	 * ParserOutput with meta data from the query
	 *
	 * FIXME $rawParams use IParameterFormatter -> QueryParameterFormatter class
	 * Parse parameters and return query results to the ParserOutput
	 * object and output result data from the QueryProcessor
	 *
	 * @todo $rawParams should be of IParameterFormatter
	 * QueryParameterFormatter class
	 *
	 * @since 1.9
	 *
	 * @param array $functionParams
	 *
	 * @return string|null
	 */
	public function parse( array $functionParams ) {

		// Do we still need this?
		// Reference found in SRF_Exhibit.php, SRF_Ploticus.php, SRF_Timeline.php, SRF_JitGraph.php
		$GLOBALS['smwgIQRunningNumber']++;
		$result = '';

		list( $functionParams, $extraKeys ) = $this->prepareFunctionParameters(
			$functionParams
		);

		if ( !isset( $extraKeys[self::NO_TRACE] ) ) {
			$extraKeys[self::NO_TRACE] = $this->parserData->getOption( ParserData::NO_QUERY_DEPENDENCY_TRACE );
		}

		// No trace on queries invoked by special pages
		if ( $this->parserData->getTitle()->getNamespace() === NS_SPECIAL ) {
			$extraKeys[self::NO_TRACE] = true;
		}

		$result = $this->doFetchResultsFromFunctionParameters(
			$functionParams,
			$extraKeys
		);

		if ( $this->context === QueryProcessor::DEFERRED_QUERY ) {
			Deferred::registerResources( $this->parserData->getOutput() );
		}

		$this->parserData->copyToParserOutput();

		// 'userlang' will trigger a cache fragmentation by user language
		$this->parserData->addExtraParserKey( 'userlang' );

		// 'dateformat'  will trigger a cache fragmentation by date preference
		$this->parserData->addExtraParserKey( 'dateformat' );

		return $result;
	}

	private function prepareFunctionParameters( array $functionParams ) {

		// Remove parser object from parameters array
		if( isset( $functionParams[0] ) && $functionParams[0] instanceof Parser ) {
			array_shift( $functionParams );
		}

		$extraKeys = [];
		$previous = false;

		// Filter invalid parameters
		foreach ( $functionParams as $key => $value ) {

			if ( $value === self::DEFERRED_REQUEST ) {
				$this->context = QueryProcessor::DEFERRED_QUERY;
				unset( $functionParams[$key] );
				continue;
			}

			if ( $value === self::NO_TRACE ) {
				$extraKeys[self::NO_TRACE] = true;
				unset( $functionParams[$key] );
				continue;
			}

			if ( $value === self::IS_ANNOTATION ) {
				$extraKeys[self::IS_ANNOTATION] = true;
				unset( $functionParams[$key] );
				continue;
			}

			// @see ParserOptionsRegister hook, use registered `localTime` key
			if ( strpos( $value, '#LOCL#TO' ) !== false ) {
				$this->parserData->addExtraParserKey( 'localTime' );
			}

			// Skip the first (being the condition) and other marked
			// printrequests
			if ( $key == 0 || ( $value !== '' && $value{0} === '?' ) ) {
				continue;
			}

			// The MW parser swallows any `|` char (as it is used as field
			// separator) hence make an educated guess about the condition when
			// it contains `[[`...`]]` and the previous value was empty (expected
			// due to ||) then the string should be concatenated and interpret
			// as [[Foo]] || [[Bar]]
			if (
				( $key > 0 && $previous === '' ) &&
				( strpos( $value, '[[' ) !== false && strpos( $value, ']]' ) !== false ) ) {
				$functionParams[0] .= " || $value";
				unset( $functionParams[$key] );
			}

			// Filter parameters that can not be split into
			// argument=value
			if ( strpos( $value, '=' ) === false ) {
				unset( $functionParams[$key] );
			}

			$previous = $value;
		}

		return [ $functionParams, $extraKeys ];
	}

	private function doFetchResultsFromFunctionParameters( array $functionParams, array $extraKeys ) {

		$contextPage = $this->parserData->getSubject();
		$action = $this->parserData->getOption( 'request.action' );
		$status = [];

		if ( $extraKeys[self::NO_TRACE] === true ) {
			$contextPage = null;
		}

		list( $query, $this->params ) = QueryProcessor::getQueryAndParamsFromFunctionParams(
			$functionParams,
			SMW_OUTPUT_WIKI,
			$this->context,
			$this->showMode,
			$contextPage
		);

		if ( ( $result = $this->hasReachedExpensiveExecutionLimit( $query ) ) !== false ) {
			return $result;
		}

		$query->setOption( Query::PROC_CONTEXT, 'AskParserFunction' );
		$query->setOption( Query::NO_DEPENDENCY_TRACE, $extraKeys[self::NO_TRACE] );
		$query->setOption( 'request.action', $action );

		$queryHash = $query->getHash();

		if ( $this->postProcHandler !== null && isset( $extraKeys[self::IS_ANNOTATION] ) ) {
			$status[] = 100;
			$this->postProcHandler->addUpdate( $query );
		}

		if ( $this->context === QueryProcessor::DEFERRED_QUERY ) {
			$status[] = 200;
		}

		$this->circularReferenceGuard->mark( $queryHash );

		// If we caught in a circular loop (due to a template referencing to itself)
		// then we stop here before the next query execution to avoid an infinite
		// self-reference
		if ( $this->circularReferenceGuard->isCircular( $queryHash ) ) {
			return '';
		}

		// #3230
		// If the query contains a self reference (embedding page is part of the
		// query condition) for a `edit` action then set an extra key so that the
		// parser uses a different parser cache hereby allows for an additional
		// parse on the next GET request to retrieve newly stored values that may
		// have been appended during the `edit`.
		if ( ( $action === 'submit' || $action === 'stashedit' ) && $query->getOption( 'self.reference' ) ) {
			$this->parserData->addExtraParserKey( 'smwq' );
		}

		QueryProcessor::setRecursiveTextProcessor(
			$this->recursiveTextProcessor
		);

		$params = [];

		foreach ( $this->params as $key => $value) {
			$params[$key] = $value->getValue();
		}

		$query->setOption( 'query.params', $params );

		// Only request a result_hash in case the `check-query` is enabled
		if ( $this->postProcHandler !== null ) {
			$query->setOption( 'calc.result_hash', $this->postProcHandler->getOption( 'check-query' ) );
		}

		$result = QueryProcessor::getResultFromQuery(
			$query,
			$this->params,
			SMW_OUTPUT_WIKI,
			$this->context
		);

		if ( $this->postProcHandler !== null && $this->context !== QueryProcessor::DEFERRED_QUERY ) {
			$this->postProcHandler->addCheck( $query );
		}

		$format = $this->params['format']->getValue();

		if ( $this->recursiveTextProcessor !== null ) {
			$this->recursiveTextProcessor->copyData( $this->parserData );
		}

		$this->circularReferenceGuard->unmark( $queryHash );
		$this->expensiveFuncExecutionWatcher->incrementExpensiveCount( $query );

		// In case of an query error add a marker to the subject for discoverability
		// of a failed query, don't bail-out as we can have results and errors
		// at the same time
		$this->addProcessingError( $query->getErrors() );

		$query->setOption( Query::PROC_STATUS_CODE, $status );

		$this->addQueryProfile(
			$query,
			$format,
			$extraKeys
		);

		return $result;
	}

	private function hasReachedExpensiveExecutionLimit( $query ) {

		if ( $this->expensiveFuncExecutionWatcher->hasReachedExpensiveLimit( $query ) === false ) {
			return false;
		}

		// Adding to error in order to be discoverable
		$this->addProcessingError( [ 'smw-parser-function-expensive-execution-limit' ] );

		return $this->messageFormatter->addFromKey( 'smw-parser-function-expensive-execution-limit' )->getHtml();
	}

	private function addQueryProfile( $query, $format, $extraKeys ) {

		$applicationFactory = ApplicationFactory::getInstance();
		$settings = $applicationFactory->getSettings();

		// If the smwgQueryProfiler is marked with FALSE then just don't create a profile.
		if ( $settings->get( 'smwgQueryProfiler' ) === false || $extraKeys[self::NO_TRACE] === true ) {
			return;
		}

		if ( !$settings->isFlagSet( 'smwgQueryProfiler', SMW_QPRFL_DUR ) ) {
			$query->setOption( Query::PROC_QUERY_TIME, 0 );
		}

		if ( $settings->isFlagSet( 'smwgQueryProfiler', SMW_QPRFL_PARAMS ) ) {
			$query->setOption( Query::OPT_PARAMETERS, true );
		}

		$query->setContextPage(
			$this->parserData->getSubject()
		);

		$profileAnnotatorFactory = $applicationFactory->getQueryFactory()->newProfileAnnotatorFactory();

		$profileAnnotator = $profileAnnotatorFactory->newProfileAnnotator(
			$query,
			$format
		);

		$profileAnnotator->pushAnnotationsTo(
			$this->parserData->getSemanticData()
		);
	}

	private function addProcessingError( $errors ) {

		if ( $errors === [] ) {
			return;
		}

		$processingErrorMsgHandler = new ProcessingErrorMsgHandler(
			$this->parserData->getSubject()
		);

		foreach ( $errors as $error ) {

			if ( ( $property = $processingErrorMsgHandler->grepPropertyFromRestrictionErrorMsg( $error ) ) === null ) {
				$property = new DIProperty( '_ASK' );
			}

			$container = $processingErrorMsgHandler->newErrorContainerFromMsg(
				$error,
				$property
			);

			$processingErrorMsgHandler->addToSemanticData(
				$this->parserData->getSemanticData(),
				$container
			);
		}
	}

}