summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Parser/InTextAnnotationParser.php
blob: f38ff33e80e79954616eb96ff1d4646b8e4402db (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
451
452
453
454
455
456
457
458
459
460
461
462
<?php

namespace SMW\Parser;

use Hooks;
use SMW\ApplicationFactory;
use SMW\DataValueFactory;
use SMW\Localizer;
use SMW\MediaWiki\MagicWordsFinder;
use SMW\MediaWiki\RedirectTargetFinder;
use SMW\MediaWiki\StripMarkerDecoder;
use SMW\ParserData;
use SMW\Utils\Timer;
use SMWOutputs;
use Title;

/**
 * Class collects all functions for wiki text parsing / processing that are
 * relevant for SMW
 *
 * This class is contains all functions necessary for parsing wiki text before
 * it is displayed or previewed while identifying SMW related annotations.
 *
 * @license GNU GPL v2+
 * @since 1.9
 *
 * @author Markus Krötzsch
 * @author Denny Vrandecic
 * @author mwjames
 */
class InTextAnnotationParser {

	/**
	 * Internal state for switching SMW link annotations off/on during parsing
	 * ([[SMW::on]] and [[SMW:off]])
	 */
	const OFF = '[[SMW::off]]';
	const ON = '[[SMW::on]]';

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

	/**
	 * @var LinksProcessor
	 */
	private $linksProcessor;

	/**
	 * @var MagicWordsFinder
	 */
	private $magicWordsFinder;

	/**
	 * @var RedirectTargetFinder
	 */
	private $redirectTargetFinder;

	/**
	 * @var DataValueFactory
	 */
	private $dataValueFactory = null;

	/**
	 * @var ApplicationFactory
	 */
	private $applicationFactory = null;

	/**
	 * @var StripMarkerDecoder
	 */
	private $stripMarkerDecoder;

	/**
	 * @var boolean
	 */
	protected $isEnabledNamespace;

	/**
	 * Internal state for switching SMW link annotations off/on during parsing
	 * ([[SMW::on]] and [[SMW:off]])
	 * @var boolean
	 */
	protected $isAnnotation = true;

	/**
	 * @var boolean|integer
	 */
	private $isLinksInValues = false;

	/**
	 * @var boolean
	 */
	private $showErrors = true;

	/**
	 * @since 1.9
	 *
	 * @param ParserData $parserData
	 * @param LinksProcessor $linksProcessor
	 * @param MagicWordsFinder $magicWordsFinder
	 * @param RedirectTargetFinder $redirectTargetFinder
	 */
	public function __construct( ParserData $parserData, LinksProcessor $linksProcessor, MagicWordsFinder $magicWordsFinder, RedirectTargetFinder $redirectTargetFinder ) {
		$this->parserData = $parserData;
		$this->linksProcessor = $linksProcessor;
		$this->magicWordsFinder = $magicWordsFinder;
		$this->redirectTargetFinder = $redirectTargetFinder;
		$this->dataValueFactory = DataValueFactory::getInstance();
		$this->applicationFactory = ApplicationFactory::getInstance();
	}

	/**
	 * @since 2.5
	 *
	 * @param boolean $isLinksInValues
	 */
	public function isLinksInValues( $isLinksInValues ) {
		$this->isLinksInValues = $isLinksInValues;
	}

	/**
	 * @since 3.0
	 *
	 * @param boolean $showErrors
	 */
	public function showErrors( $showErrors ) {
		$this->showErrors = (bool)$showErrors;
	}

	/**
	 * Parsing text before an article is displayed or previewed, strip out
	 * semantic properties and add them to the ParserOutput object
	 *
	 * @since 1.9
	 *
	 * @param string &$text
	 */
	public function parse( &$text ) {

		$title = $this->parserData->getTitle();
		Timer::start( __CLASS__ );

		// Identifies the current parser run (especially when called recursively)
		$this->parserData->getSubject()->setContextReference( 'intp:' . uniqid() );

		$this->doStripMagicWordsFromText( $text );

		$this->isEnabledNamespace = $this->isSemanticEnabledForNamespace( $title );

		$this->addRedirectTargetAnnotationFromText(
			$text
		);

		// Obscure [/] to find a set of [[ :: ... ]] while those in-between are left for
		// decoding in a post-processing so that the regex can split the text
		// appropriately
		if ( $this->isLinksInValues ) {
			$text = LinksEncoder::findAndEncodeLinks( $text, $this );
		}

		// No longer used with 3.0 given that the LinksEncoder is safer and faster
		$linksInValuesPcre = false;

		$text = preg_replace_callback(
			$this->getRegexpPattern( $linksInValuesPcre ),
			$linksInValuesPcre ? 'self::process' : 'self::preprocess',
			$text
		);

		// Ensure remaining encoded entities are decoded again
		$text = LinksEncoder::removeLinkObfuscation( $text );

		if ( $this->isEnabledNamespace ) {
			$this->parserData->getOutput()->addModules( $this->getModules() );
			$this->parserData->addExtraParserKey( 'userlang' );
		}

		$this->parserData->pushSemanticDataToParserOutput();

		$this->parserData->addLimitReport(
			'intext-parsertime',
			Timer::getElapsedTime( __CLASS__, 3 )
		);

		SMWOutputs::commitToParserOutput( $this->parserData->getOutput() );
	}

	/**
	 * @since 3.0
	 *
	 * @param string $text
	 *
	 * @return boolean
	 */
	public static function hasMarker( $text ) {
		return strpos( $text, self::OFF ) !== false || strpos( $text, self::ON ) !== false;
	}

	/**
	 * @since 2.4
	 *
	 * @param string $text
	 *
	 * @return text
	 */
	public static function decodeSquareBracket( $text ) {
		return LinksEncoder::decodeSquareBracket( $text );
	}

	/**
	 * @since 2.4
	 *
	 * @param string $text
	 *
	 * @return text
	 */
	public static function obfuscateAnnotation( $text ) {
		return LinksEncoder::obfuscateAnnotation( $text );
	}

	/**
	 * @since 2.4
	 *
	 * @param string $text
	 *
	 * @return text
	 */
	public static function removeAnnotation( $text ) {
		return LinksEncoder::removeAnnotation( $text );
	}

	/**
	 * @since 3.0
	 *
	 * @param StripMarkerDecoder $stripMarkerDecoder
	 */
	public function setStripMarkerDecoder( StripMarkerDecoder $stripMarkerDecoder ) {
		$this->stripMarkerDecoder = $stripMarkerDecoder;
	}

	/**
	 * @since 2.1
	 *
	 * @param Title|null $redirectTarget
	 */
	public function setRedirectTarget( Title $redirectTarget = null ) {
		$this->redirectTargetFinder->setRedirectTarget( $redirectTarget );
	}

	protected function addRedirectTargetAnnotationFromText( $text ) {

		if ( !$this->isEnabledNamespace ) {
			return;
		}

		$this->redirectTargetFinder->findRedirectTargetFromText( $text );

		$propertyAnnotatorFactory = $this->applicationFactory->singleton( 'PropertyAnnotatorFactory' );

		$propertyAnnotator = $propertyAnnotatorFactory->newNullPropertyAnnotator(
			$this->parserData->getSemanticData()
		);

		$redirectPropertyAnnotator = $propertyAnnotatorFactory->newRedirectPropertyAnnotator(
			$propertyAnnotator,
			$this->redirectTargetFinder
		);

		$redirectPropertyAnnotator->addAnnotation();
	}

	/**
	 * Returns required resource modules
	 *
	 * @since 1.9
	 *
	 * @return array
	 */
	protected function getModules() {
		return [
			'ext.smw.style',
			'ext.smw.tooltips'
		];
	}

	/**
	 * @see LinksProcessor::getRegexpPattern
	 * @since 1.9
	 *
	 * @param boolean $linksInValues
	 *
	 * @return string
	 */
	public function getRegexpPattern( $linksInValues = false ) {
		return LinksProcessor::getRegexpPattern( $linksInValues );
	}

	/**
	 * @see linksProcessor::preprocess
	 * @since 1.9
	 *
	 * @param array $semanticLink expects (linktext, properties, value|caption)
	 *
	 * @return string
	 */
	public function preprocess( array $semanticLink ) {

		$semanticLinks = $this->linksProcessor->preprocess( $semanticLink );

		if ( is_string( $semanticLinks ) ) {
			return $semanticLinks;
		}

		return $this->process( $semanticLinks );
	}

	/**
	 * @see linksProcessor::process
	 * @since 1.9
	 *
	 * @param array $semanticLink expects (linktext, properties, value|caption)
	 *
	 * @return string
	 */
	protected function process( array $semanticLink ) {

		$valueCaption = false;
		$property = '';
		$value = '';

		$semanticLinks = $this->linksProcessor->process(
			$semanticLink
		);

		$this->isAnnotation = $this->linksProcessor->isAnnotation();

		if ( is_string( $semanticLinks ) ) {
			return $semanticLinks;
		}

		list( $properties, $value, $valueCaption ) = $semanticLinks;

		$subject = $this->parserData->getSubject();

		if ( ( $propertyLink = $this->getPropertyLink( $subject, $properties, $value, $valueCaption ) ) !== '' ) {
			return $propertyLink;
		}

		return $this->addPropertyValue( $subject, $properties, $value, $valueCaption );
	}

	/**
	 * Adds property values to the ParserOutput instance
	 *
	 * @since 1.9
	 *
	 * @param array $properties
	 *
	 * @return string
	 */
	protected function addPropertyValue( $subject, array $properties, $value, $valueCaption ) {

		$origValue = $value;

		if ( $this->stripMarkerDecoder !== null ) {
			$value = $this->stripMarkerDecoder->decode( $value );
		}

		// Add properties to the semantic container
		foreach ( $properties as $property ) {
			$dataValue = $this->dataValueFactory->newDataValueByText(
				$property,
				$value,
				$valueCaption,
				$subject
			);

			if (
				$this->isEnabledNamespace &&
				$this->isAnnotation &&
				$this->parserData->canUse() ) {
				$this->parserData->addDataValue( $dataValue );
			}
		}

		// Return the wikitext or the unmodified text representation in case of
		// a strip marker in order for the standard Parser to work its magic since
		// we were only interested in the value for the annotation
		if ( $origValue !== $value ) {
			$result = $origValue;
		} else {
			$result = $dataValue->getShortWikitext( true );
		}

		// If necessary add an error text
		if ( ( $this->showErrors &&
			$this->isEnabledNamespace && $this->isAnnotation ) &&
			( !$dataValue->isValid() ) ) {
			// Encode `:` to avoid a comment block and instead of the nowiki tag
			// use &#58; as placeholder
			$result = str_replace( ':', '&#58;', $result ) . $dataValue->getErrorText();
		}

		return $result;
	}

	protected function doStripMagicWordsFromText( &$text ) {

		$words = [];

		$this->magicWordsFinder->setOutput( $this->parserData->getOutput() );

		$magicWords = [
			'SMW_NOFACTBOX',
			'SMW_SHOWFACTBOX'
		];

		Hooks::run( 'SMW::Parser::BeforeMagicWordsFinder', [ &$magicWords ] );

		foreach ( $magicWords as $magicWord ) {
			$words[] = $this->magicWordsFinder->findMagicWordInText( $magicWord, $text );
		}

		$this->magicWordsFinder->pushMagicWordsToParserOutput( $words );

		return $words;
	}

	private function isSemanticEnabledForNamespace( Title $title ) {
		return $this->applicationFactory->getNamespaceExaminer()->isSemanticEnabled( $title->getNamespace() );
	}

	private function getPropertyLink( $subject, $properties, $value, $valueCaption ) {

		// #1855
		if ( substr( $value, 0, 3 ) !== '@@@' ) {
			return '';
		}

		$property = end( $properties );

		$dataValue = $this->dataValueFactory->newPropertyValueByLabel(
			$property,
			$valueCaption,
			$subject
		);

		if ( ( $lang = Localizer::getAnnotatedLanguageCodeFrom( $value ) ) !== false ) {
			$dataValue->setOption( $dataValue::OPT_USER_LANGUAGE, $lang );
			$dataValue->setCaption(
				$valueCaption === false ? $dataValue->getWikiValue() : $valueCaption
			);
		}

		$dataValue->setOption( $dataValue::OPT_HIGHLIGHT_LINKER, true );

		return $dataValue->getShortWikitext( smwfGetLinker() );
	}

}