summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Query/Parser/LegacyParser.php
blob: fa3c6096644a4ca1db99d52a3bcedb2beb828ea8 (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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
<?php

namespace SMW\Query\Parser;

use SMW\DataTypeRegistry;
use SMW\DataValueFactory;
use SMW\DIProperty;
use SMW\DIWikiPage;
use SMW\Localizer;
use SMW\Query\DescriptionFactory;
use SMW\Query\Language\ClassDescription;
use SMW\Query\Language\Disjunction;
use SMW\Query\Language\SomeProperty;
use SMW\Query\Parser;
use SMW\Query\QueryToken;
use Title;

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author Markus Krötzsch
 */
class LegacyParser implements Parser {

	/**
	 * @var DescriptionProcessor
	 */
	private $descriptionProcessor;

	/**
	 * @var QueryToken
	 */
	private $queryToken;

	/**
	 * @var Tokenizer
	 */
	private $tokenizer;

	/**
	 * @var DescriptionFactory
	 */
	private $descriptionFactory;

	/**
	 * @var DataTypeRegistry
	 */
	private $dataTypeRegistry;

	/**
	 * Description of the default namespace restriction, or NULL if not used
	 *
	 * @var array|null
	 */
	private $defaultNamespace;

	/**
	 * List of open blocks ("parentheses") that need closing at current step
	 *
	 * @var array
	 */
	private $separatorStack = [];

	/**
	 * Remaining string to be parsed (parsing eats query string from the front)
	 *
	 * @var string
	 */
	private $currentString;

	/**
	 * Cache label of category namespace . ':'
	 *
	 * @var string
	 */
	private $categoryPrefix;

	/**
	 * Cache label of concept namespace . ':'
	 *
	 * @var string
	 */
	private $conceptPrefix;

	/**
	 * Cache canonnical label of category namespace . ':'
	 *
	 * @var string
	 */
	private $categoryPrefixCannonical;

	/**
	 * Cache canonnical label of concept namespace . ':'
	 *
	 * @var string
	 */
	private $conceptPrefixCannonical;

	/**
	 * @var DIWikiPage|null
	 */
	private $contextPage;

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

	/**
	 * @since 3.0
	 *
	 * @param DescriptionProcessor $descriptionProcessor
	 * @param Tokenizer $tokenizer
	 * @param QueryToken $queryToken
	 */
	public function __construct( DescriptionProcessor $descriptionProcessor, Tokenizer $tokenizer, QueryToken $queryToken ) {
		$this->descriptionProcessor = $descriptionProcessor;
		$this->tokenizer = $tokenizer;
		$this->queryToken = $queryToken;
		$this->descriptionFactory = new DescriptionFactory();
		$this->dataTypeRegistry = DataTypeRegistry::getInstance();
		$this->setDefaultPrefix();
	}

	/**
	 * @since 3.0
	 *
	 * @param DIWikiPage|null $contextPage
	 */
	public function setContextPage( DIWikiPage $contextPage = null ) {
		$this->contextPage = $contextPage;
	}

	/**
	 * Provide an array of namespace constants that are used as default restrictions.
	 * If NULL is given, no such default restrictions will be added (faster).
	 *
	 * @since 1.6
	 */
	public function setDefaultNamespaces( $namespaces ) {
		$this->defaultNamespace = null;

		if ( !is_array( $namespaces ) ) {
			return;
		}

		foreach ( $namespaces as $namespace ) {
			$this->defaultNamespace = $this->descriptionProcessor->asOr(
				$this->defaultNamespace,
				$this->descriptionFactory->newNamespaceDescription( $namespace )
			);
		}
	}

	/**
	 * @since 3.0
	 *
	 * @param string|null $languageCode
	 */
	public function setDefaultPrefix( $languageCode = null ) {

		$localizer = Localizer::getInstance();

		if ( $languageCode === null ) {
			$language = $localizer->getContentLanguage();
		} else {
			$language = $localizer->getLanguage( $languageCode );
		}

		$this->categoryPrefix = $language->getNsText( NS_CATEGORY ) . ':';
		$this->conceptPrefix = $language->getNsText( SMW_NS_CONCEPT ) . ':';

		$this->categoryPrefixCannonical = 'Category:';
		$this->conceptPrefixCannonical = 'Concept:';

		$this->tokenizer->setDefaultPattern(
			[
				$this->categoryPrefix,
				$this->conceptPrefix,
				$this->categoryPrefixCannonical,
				$this->conceptPrefixCannonical
			]
		);
	}

	/**
	 * Return array of error messages (possibly empty).
	 *
	 * @return array
	 */
	public function getErrors() {
		return $this->descriptionProcessor->getErrors();
	}

	/**
	 * @since 3.0
	 *
	 * @return boolean
	 */
	public function containsSelfReference() {

		if ( $this->selfReference ) {
			return true;
		}

		return $this->descriptionProcessor->containsSelfReference();
	}

	/**
	 * Return error message or empty string if no error occurred.
	 *
	 * @return string
	 */
	public function getErrorString() {
		throw new \RuntimeException( "Shouldnot be used, remove getErrorString usage!" );
		return smwfEncodeMessages( $this->getErrors() );
	}

	/**
	 * @since 2.5
	 *
	 * @return QueryToken
	 */
	public function getQueryToken() {
		return $this->queryToken;
	}

	/**
	 * @since 3.0
	 *
	 * {@inheritDoc}
	 */
	public function createCondition( $property, $value ) {

		if ( $property instanceOf DIProperty ) {
			$property = $property->getLabel();
		}

		return "[[$property::$value]]";
	}

	/**
	 * Compute an SMWDescription from a query string. Returns whatever descriptions could be
	 * wrestled from the given string (the most general result being SMWThingDescription if
	 * no meaningful condition was extracted).
	 *
	 * @param string $queryString
	 *
	 * @return Description
	 */
	public function getQueryDescription( $queryString ) {

		if ( $queryString === '' ) {
			$this->descriptionProcessor->addErrorWithMsgKey(
				'smw-query-condition-empty'
			);

			return  $this->descriptionFactory->newThingDescription();
		}

		$this->descriptionProcessor->clear();
		$this->descriptionProcessor->setContextPage( $this->contextPage );

		$this->currentString = $queryString;
		$this->separatorStack = [];

		$this->selfReference = false;
		$setNS = false;

		$description = $this->getSubqueryDescription( $setNS );

		// add default namespaces if applicable
		if ( !$setNS ) {
			$description = $this->descriptionProcessor->asAnd(
				$this->defaultNamespace,
				$description
			);
		}

		// parsing went wrong, no default namespaces
		if ( $description === null ) {
			$description = $this->descriptionFactory->newThingDescription();
		}

		return $description;
	}

	/**
	 * Compute an SMWDescription for current part of a query, which should
	 * be a standalone query (the main query or a subquery enclosed within
	 * "\<q\>...\</q\>". Recursively calls similar methods and returns NULL upon error.
	 *
	 * The call-by-ref parameter $setNS is a boolean. Its input specifies whether
	 * the query should set the current default namespace if no namespace restrictions
	 * were given. If false, the calling super-query is happy to set the required
	 * NS-restrictions by itself if needed. Otherwise the subquery has to impose the defaults.
	 * This is so, since outermost queries and subqueries of disjunctions will have to set
	 * their own default restrictions.
	 *
	 * The return value of $setNS specifies whether or not the subquery has a namespace
	 * specification in place. This might happen automatically if the query string imposes
	 * such restrictions. The return value is important for those callers that otherwise
	 * set up their own restrictions.
	 *
	 * Note that $setNS is no means to switch on or off default namespaces in general,
	 * but just controls query generation. For general effect, the default namespaces
	 * should be set to NULL.
	 *
	 * @return Description|null
	 */
	private function getSubqueryDescription( &$setNS ) {

		$conjunction = null;      // used for the current inner conjunction
		$disjuncts = [];     // (disjunctive) array of subquery conjunctions

		$hasNamespaces = false;   // does the current $conjnuction have its own namespace restrictions?
		$mustSetNS = $setNS;      // must NS restrictions be set? (may become true even if $setNS is false)

		$continue = ( $chunk = $this->readChunk() ) !== ''; // skip empty subquery completely, thorwing an error

		while ( $continue ) {
			$setsubNS = false;

			switch ( $chunk ) {
				case '[[': // start new link block
					$ld = $this->getLinkDescription( $setsubNS );

					if ( !is_null( $ld ) ) {
						$conjunction = $this->descriptionProcessor->asAnd( $conjunction, $ld );
					}
				break;
				case 'AND':
				case '<q>': // enter new subquery, currently irrelevant but possible
					$this->pushDelimiter( '</q>' );
					$conjunction = $this->descriptionProcessor->asAnd( $conjunction, $this->getSubqueryDescription( $setsubNS ) );
				break;
				case 'OR':
				case '||':
				case '':
				case '</q>': // finish disjunction and maybe subquery
					if ( !is_null( $this->defaultNamespace ) ) { // possibly add namespace restrictions
						if ( $hasNamespaces && !$mustSetNS ) {
							// add NS restrictions to all earlier conjunctions (all of which did not have them yet)
							$mustSetNS = true; // enforce NS restrictions from now on
							$newdisjuncts = [];

							foreach ( $disjuncts as $conj ) {
								$newdisjuncts[] = $this->descriptionProcessor->asAnd( $conj, $this->defaultNamespace );
							}

							$disjuncts = $newdisjuncts;
						} elseif ( !$hasNamespaces && $mustSetNS ) {
							// add ns restriction to current result
							$conjunction = $this->descriptionProcessor->asAnd( $conjunction, $this->defaultNamespace );
						}
					}

					$disjuncts[] = $conjunction;
					// start anew
					$conjunction = null;
					$hasNamespaces = false;

					// finish subquery?
					if ( $chunk == '</q>' ) {
						if ( $this->popDelimiter( '</q>' ) ) {
							$continue = false; // leave the loop
						} else {
							$this->descriptionProcessor->addErrorWithMsgKey( 'smw_toomanyclosing', $chunk );
							return null;
						}
					} elseif ( $chunk === '' ) {
						$continue = false;
					}
				break;
				case '+': // "... AND true" (ignore)
				break;
				default: // error: unexpected $chunk
					$this->descriptionProcessor->addErrorWithMsgKey( 'smw_unexpectedpart', $chunk );
					// return null; // Try to go on, it can only get better ...
			}

			if ( $setsubNS ) { // namespace restrictions encountered in current conjunct
				$hasNamespaces = true;
			}

			if ( $continue ) { // read on only if $continue remained true
				$chunk = $this->readChunk();
			}
		}

		if ( count( $disjuncts ) > 0 ) { // make disjunctive result
			$result = null;

			foreach ( $disjuncts as $d ) {
				if ( is_null( $d ) ) {
					$this->descriptionProcessor->addErrorWithMsgKey( 'smw_emptysubquery' );
					$setNS = false;
					return null;
				} else {
					$result = $this->descriptionProcessor->asOr( $result, $d );
				}
			}
		} else {
			$this->descriptionProcessor->addErrorWithMsgKey( 'smw_emptysubquery' );
			$setNS = false;
			return null;
		}

		// NOTE: also false if namespaces were given but no default NS descs are available
		$setNS = $mustSetNS;

		return $result;
	}

	/**
	 * Compute an SMWDescription for current part of a query, which should
	 * be the content of "[[ ... ]]". Returns NULL upon error.
	 *
	 * Parameters $setNS has the same use as in getSubqueryDescription().
	 */
	private function getLinkDescription( &$setNS ) {
		// This method is called when we encountered an opening '[['. The following
		// block could be a Category-statement, fixed object, or property statement.

		// NOTE: untrimmed, initial " " escapes prop. chains
		$chunk = $this->readChunk( '', true, false );

		if ( $this->hasClassPrefix( $chunk ) ) {
			return $this->getClassDescription( $setNS, $this->isClass( $chunk ) );
		}

		// fixed subject, namespace restriction, property query, or subquery

		// Do not consume hit, "look ahead"
		$sep = $this->readChunk( '', false );

		if ( ( $sep == '::' ) || ( $sep == ':=' ) ) {
			if ( $chunk{0} != ':' ) { // property statement
				return $this->getPropertyDescription( $chunk, $setNS );
			} else { // escaped article description, read part after :: to get full contents
				$chunk .= $this->readChunk( '\[\[|\]\]|\|\||\|' );
				return $this->getArticleDescription( trim( $chunk ), $setNS );
			}
		}

		 // Fixed article/namespace restriction. $sep should be ]] or ||
		return $this->getArticleDescription( trim( $chunk ), $setNS );
	}

	/**
	 * Parse a category description (the part of an inline query that
	 * is in between "[[Category:" and the closing "]]" and create a
	 * suitable description.
	 */
	private function getClassDescription( &$setNS, $category = true ) {

		// No subqueries allowed here, inline disjunction allowed, wildcards allowed
		$description = null;
		$continue = true;
		$invalidName = false;

		while ( $continue ) {
			$chunk = $this->readChunk();

			if ( $chunk == '+' ) {
				$desc = $this->descriptionFactory->newNamespaceDescription( $category ? NS_CATEGORY : SMW_NS_CONCEPT );
				$description = $this->descriptionProcessor->asOr( $description, $desc );
			} else { // assume category/concept title
				$isNegation = false;

				// [[Category:!Foo]]
				// Only the ElasticStore does actively support this construct
				if ( $chunk{0} === '!' ) {
					$chunk = substr( $chunk, 1 );
					$isNegation = true;
				}

				// We add a prefix to prevent problems with, e.g., [[Category:Template:Test]]
				$prefix = $category ? $this->categoryPrefix : $this->conceptPrefix;
				$title = Title::newFromText( $prefix . $chunk );

				// Something like [[Category::Foo]] doesn't produce any meaningful
				// results
				if ( strpos( $prefix . $chunk, '::' ) !== false ) {
					$invalidName .= "{$prefix}{$chunk}";
				} elseif ( $invalidName ) {
					$invalidName .= "||{$chunk}";
				}

				if ( $title !== null ) {
					$diWikiPage = new DIWikiPage( $title->getDBkey(), $title->getNamespace(), '' );

					if ( !$this->selfReference && $this->contextPage !== null ) {
						$this->selfReference = $diWikiPage->equals( $this->contextPage );
					}

					$desc = $category ? $this->descriptionFactory->newClassDescription( $diWikiPage ) : $this->descriptionFactory->newConceptDescription( $diWikiPage );

					if ( $isNegation ) {
						$desc->isNegation = $isNegation;
					}

					$description = $this->descriptionProcessor->asOr( $description, $desc );
				}
			}

			$chunk = $this->readChunk();

			// Disjunctions only for categories
			$continue = ( $chunk == '||' ) && $category;
		}

		if ( $invalidName ) {
			return $this->descriptionProcessor->addErrorWithMsgKey( 'smw-category-invalid-value-assignment', "[[{$invalidName}]]" );
		}

		return $this->finishLinkDescription( $chunk, false, $description, $setNS );
	}

	/**
	 * Parse a property description (the part of an inline query that
	 * is in between "[[Some property::" and the closing "]]" and create a
	 * suitable description. The "::" is the first chunk on the current
	 * string.
	 */
	private function getPropertyDescription( $propertyName, &$setNS ) {

		// Consume separator ":=" or "::"
		$this->readChunk();
		$dataValueFactory = DataValueFactory::getInstance();

		// First process property chain syntax (e.g. "property1.property2::value"),
		// escaped by initial " ":
		$propertynames = ( $propertyName{0} == ' ' ) ? [ $propertyName ] : explode( '.', $propertyName );
		$propertyValueList = [];

		$typeid = '_wpg';
		$inverse = false;

		// After iteration, $property and $typeid correspond to last value
		foreach ( $propertynames as $name ) {

			// Non-final property in chain was no wikipage: not allowed
			if ( !$this->isPagePropertyType( $typeid ) ) {
				$this->descriptionProcessor->addErrorWithMsgKey( 'smw_valuesubquery', $name );

				// TODO: read some more chunks and try to finish [[ ]]
				return null;
			}

			$propertyValue = $dataValueFactory->newPropertyValueByLabel( $name );

			// Illegal property identifier
			if ( !$propertyValue->isValid() ) {
				$this->descriptionProcessor->addError( $propertyValue->getErrors() );

				// TODO: read some more chunks and try to finish [[ ]]
				return null;
			}

			// Set context to allow evading restriction checks for specific
			// entities that handle the context such as pre-defined properties
			// (Has query, Modification date etc.)
			$propertyValue->setOption( $propertyValue::OPT_QUERY_CONTEXT, true );

			// Check restriction
			if ( $propertyValue->isRestricted() ) {
				$this->descriptionProcessor->addError( $propertyValue->getRestrictionError() );
				return null;
			}

			$property = $propertyValue->getDataItem();
			$propertyValueList[] = $propertyValue;

			$typeid = $property->findPropertyTypeID();
			$inverse = $property->isInverse();
		}

		$innerdesc = null;
		$continue = true;

		while ( $continue ) {
			$chunk = $this->readChunk();

			switch ( $chunk ) {
				// !+
				case '!+':
					$desc = $this->descriptionFactory->newThingDescription();
					$desc->isNegation = true;
					$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $desc );
					$chunk = $this->readChunk();
				break;
				// wildcard, add namespaces for page-type properties
				case '+':
					if ( !is_null( $this->defaultNamespace ) && ( $this->isPagePropertyType( $typeid ) || $inverse ) ) {
						$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->defaultNamespace );
					} else {
						$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->descriptionFactory->newThingDescription() );
					}
					$chunk = $this->readChunk();
				break;
				 // subquery, set default namespaces
				case '<q>':
					if ( $this->isPagePropertyType( $typeid ) || $inverse ) {
						$this->pushDelimiter( '</q>' );
						$setsubNS = true;
						$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->getSubqueryDescription( $setsubNS ) );
					} else { // no subqueries allowed for non-pages
						$this->descriptionProcessor->addErrorWithMsgKey( 'smw_valuesubquery', end( $propertynames ) );
						$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->descriptionFactory->newThingDescription() );
					}
					$chunk = $this->readChunk();
				break;
				// normal object value
				default:
					// read value(s), possibly with inner [[...]]
					$open = 1;
					$value = $chunk;
					$continue2 = true;
					// read value with inner [[, ]], ||
					while ( ( $open > 0 ) && ( $continue2 ) ) {
						$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
						switch ( $chunk ) {
							case '[[': // open new [[ ]]
								$open++;
							break;
							case ']]': // close [[ ]]
								$open--;
							break;
							case '|':
							case '||': // terminates only outermost [[ ]]
								if ( $open == 1 ) {
									$open = 0;
								}
							break;
							case '': ///TODO: report error; this is not good right now
								$continue2 = false;
							break;
						}
						if ( $open != 0 ) {
							$value .= $chunk;
						}
					} ///NOTE: at this point, we normally already read one more chunk behind the value
					$outerDesription = $this->descriptionProcessor->newDescriptionForPropertyObjectValue(
						$propertyValue->getDataItem(),
						$value
					);

					$this->queryToken->addFromDesciption( $outerDesription );
					$innerdesc = $this->descriptionProcessor->asOr(
						$innerdesc,
						$outerDesription
					);

			}
			$continue = ( $chunk == '||' );
		}

		// No description, make a wildcard search
		if ( $innerdesc === null ) {
			if ( $this->defaultNamespace !== null && $this->isPagePropertyType( $typeid ) ) {
				$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->defaultNamespace );
			} else {
				$innerdesc = $this->descriptionProcessor->asOr( $innerdesc, $this->descriptionFactory->newThingDescription() );
			}

			$this->descriptionProcessor->addErrorWithMsgKey( 'smw_propvalueproblem', $propertyValue->getWikiValue() );
		}

		$propertyValueList = array_reverse( $propertyValueList );

		foreach ( $propertyValueList as $propertyValue ) {
			$innerdesc = $this->descriptionFactory->newSomeProperty( $propertyValue->getDataItem(), $innerdesc );
		}

		$result = $innerdesc;

		return $this->finishLinkDescription( $chunk, false, $result, $setNS );
	}

	/**
	 * Parse an article description (the part of an inline query that
	 * is in between "[[" and the closing "]]" assuming it is not specifying
	 * a category or property) and create a suitable description.
	 * The first chunk behind the "[[" has already been read and is
	 * passed as a parameter.
	 */
	private function getArticleDescription( $firstChunk, &$setNS ) {

		$chunk = $firstChunk;
		$description = null;

		$continue = true;
		$localizer = Localizer::getInstance();

		while ( $continue ) {

			 // No subqueries of the form [[<q>...</q>]] (not needed)
			if ( $chunk == '<q>' ) {
				$this->descriptionProcessor->addErrorWithMsgKey( 'smw_misplacedsubquery' );
				return null;
			}

			// ":Category:Foo" "User:bar"  ":baz" ":+"
			$list = preg_split( '/:/', $chunk, 3 );

			if ( ( $list[0] === '' ) && ( count( $list ) == 3 ) ) {
				$list = array_slice( $list, 1 );
			}

			// try namespace restriction
			if ( ( count( $list ) == 2 ) && ( $list[1] == '+' ) ) {

				$idx = $localizer->getNamespaceIndexByName( $list[0] );

				if ( $idx !== false ) {
					$description = $this->descriptionProcessor->asOr(
						$description,
						$this->descriptionFactory->newNamespaceDescription( $idx )
					);
				}
			} else {
				$outerDesription = $this->descriptionProcessor->newDescriptionForWikiPageValueChunk(
					$chunk
				);

				$this->queryToken->addFromDesciption( $outerDesription );

				$description = $this->descriptionProcessor->asOr(
					$description,
					$outerDesription
				);
			}

			$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );

			if ( $chunk == '||' ) {
				$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
				$continue = true;
			} else {
				$continue = false;
			}
		}

		return $this->finishLinkDescription( $chunk, true, $description, $setNS );
	}

	private function finishLinkDescription( $chunk, $hasNamespaces, $description, &$setNS ) {

		if ( is_null( $description ) ) { // no useful information or concrete error found
			$this->descriptionProcessor->addErrorWithMsgKey( 'smw_unexpectedpart', $chunk ); // was smw_badqueryatom
		} elseif ( !$hasNamespaces && $setNS && !is_null( $this->defaultNamespace  ) ) {
			$description = $this->descriptionProcessor->asAnd( $description, $this->defaultNamespace );
			$hasNamespaces = true;
		}

		$setNS = $hasNamespaces;

		if ( $chunk == '|' ) { // skip content after single |, but report a warning
			// Note: Using "|label" in query atoms used to be a way to set the mainlabel in SMW <1.0; no longer supported now
			$chunk = $this->readChunk( '\]\]' );
			$labelpart = '|';
			$hasError = true;

			// Set an individual hierarchy depth
			if ( strpos( $chunk, '+depth=' ) !== false ) {
				list( $k, $depth ) = explode( '=', $chunk, 2 );

				if ( $description instanceOf ClassDescription || $description instanceOf SomeProperty || $description instanceOf Disjunction ) {
					$description->setHierarchyDepth( $depth );
				}

				$chunk = $this->readChunk( '\]\]' );
				$hasError = false;
			}

			if ( $chunk != ']]' ) {
				$labelpart .= $chunk;
				$chunk = $this->readChunk( '\]\]' );
			}

			if ( $hasError ) {
				$this->descriptionProcessor->addErrorWithMsgKey( 'smw_unexpectedpart', $labelpart );
			}
		}

		if ( $chunk != ']]' ) {
			// What happended? We found some chunk that could not be processed as
			// link content (as in [[Category:Test<q>]]), or the closing ]] are
			// just missing entirely.
			if ( $chunk !== '' ) {
				$this->descriptionProcessor->addErrorWithMsgKey( 'smw_misplacedsymbol', $chunk );

				// try to find a later closing ]] to finish this misshaped subpart
				$chunk = $this->readChunk( '\]\]' );

				if ( $chunk != ']]' ) {
					$chunk = $this->readChunk( '\]\]' );
				}
			}
			if ( $chunk === '' ) {
				$this->descriptionProcessor->addErrorWithMsgKey( 'smw_noclosingbrackets' );
			}
		}

		return $description;
	}

	/**
	 * @see Tokenizer::read
	 */
	private function readChunk( $stoppattern = '', $consume = true, $trim = true ) {
		return $this->tokenizer->getToken( $this->currentString, $stoppattern, $consume, $trim );
	}

	/**
	 * Enter a new subblock in the query, which must at some time be terminated by the
	 * given $endstring delimiter calling popDelimiter();
	 */
	private function pushDelimiter( $endstring ) {
		array_push( $this->separatorStack, $endstring );
	}

	/**
	 * Exit a subblock in the query ending with the given delimiter.
	 * If the delimiter does not match the top-most open block, false
	 * will be returned. Otherwise return true.
	 */
	private function popDelimiter( $endstring ) {
		$topdelim = array_pop( $this->separatorStack );
		return ( $topdelim == $endstring );
	}

	private function isPagePropertyType( $typeid ) {
		return $typeid == '_wpg' || $this->dataTypeRegistry->isSubDataType( $typeid );
	}

	private function hasClassPrefix( $chunk ) {
		return in_array( smwfNormalTitleText( $chunk ), [ $this->categoryPrefix, $this->conceptPrefix, $this->categoryPrefixCannonical, $this->conceptPrefixCannonical ] );
	}

	private function isClass( $chunk ) {
		return smwfNormalTitleText( $chunk ) == $this->categoryPrefix || smwfNormalTitleText( $chunk ) == $this->categoryPrefixCannonical;
	}

}