summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticResultFormats/formats/tree/TreeResultPrinter.php
blob: d29fed80e4b6af196b39fc828ef823450ef39a8b (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
<?php

namespace SRF\Formats\Tree;

/**
 * File holding the Tree class.
 *
 * @author Stephan Gambke
 */

use Exception;
use Html;
use SMW\DIProperty;
use SMW\DIWikiPage;
use SMW\ListResultPrinter;
use SMWQueryResult;
use Title;

/**
 * Result printer that prints query results as a tree (nested html lists).
 *
 * The available formats are 'tree', 'ultree', 'oltree'. 'tree' is an alias of
 * 'ultree'. In an #ask query the parameter 'parent' must be set to contain the
 * name of the property, that gives the parent page of the subject page.
 *
 */
class TreeResultPrinter extends ListResultPrinter {

	private $standardTemplateParameters;

	/**
	 * @var SMWQueryResult | null
	 */
	private $queryResult = null;

	/**
	 * (non-PHPdoc)
	 * @see SMWResultPrinter::getName()
	 */
	public function getName() {
		// Give grep a chance to find the usages:
		// srf-printername-tree, srf-printername-ultree, srf-printername-oltree
		return \Message::newFromKey( 'srf-printername-' . $this->mFormat )->text();
	}

	/**
	 * @return SMWQueryResult
	 * @throws Exception
	 */
	public function getQueryResult() {

		if ( $this->queryResult === null ) {
			throw new Exception( __METHOD__ . ' called outside of ' . __CLASS__ . '::getResultText().' );
		}

		return $this->queryResult;
	}

	/**
	 * @param SMWQueryResult | null $queryResult
	 */
	public function setQueryResult( $queryResult ) {
		$this->queryResult = $queryResult;
	}

	/**
	 * @see ResultPrinter::postProcessParameters()
	 */
	protected function postProcessParameters() {

		parent::postProcessParameters();

		// Don't support pagination in trees
		$this->mSearchlabel = null;

		// Allow "_" for encoding spaces, as documented
		$this->params['sep'] = str_replace( '_', ' ', $this->params['sep'] );

		if ( !ctype_digit( strval( $this->params['start level'] ) ) || $this->params['start level'] < 1 ) {
			$this->params['start level'] = 1;
		}

	}

	/**
	 * Return serialised results in specified format.
	 *
	 * @param SMWQueryResult $queryResult
	 * @param $outputmode
	 *
	 * @return string
	 */
	protected function getResultText( SMWQueryResult $queryResult, $outputmode ) {

		$this->setQueryResult( $queryResult );

		if ( $this->params['parent'] === '' ) {
			$this->addError( 'srf-tree-noparentprop' );
			return '';
		}

		$rootHash = $this->getRootHash();

		if ( $rootHash === false ) {
			$this->addError( 'srf-tree-rootinvalid', $this->params['root'] );
			return '';
		}

		$this->hasTemplates =
			$this->params['introtemplate'] !== '' ||
			$this->params['outrotemplate'] !== '' ||
			$this->params['template'] !== '';

		if ( $this->hasTemplates ) {
			$this->initalizeStandardTemplateParameters();
		}

		$tree = $this->buildTreeFromQueryResult( $rootHash );
		$lines = $this->buildLinesFromTree( $tree );

		// Display default if the result is empty
		if ( count( $lines ) === 0 ) {
			return $this->params['default'];
		}

		// FIXME: Linking to further events ($this->linkFurtherResults())
		// does not make sense for tree format. But maybe display a warning?

		$resultText = join(
			"\n",
			array_merge(
				[ $this->getTemplateCall( $this->params['introtemplate'] ) ],
				$lines,
				[ $this->getTemplateCall( $this->params['outrotemplate'] ) ]
			)
		);

		$this->setQueryResult( null );

		return Html::rawElement( 'div', [ 'class' => 'srf-tree' ], $resultText );
	}

	/**
	 * @param string $templateName
	 * @param string[] $params
	 *
	 * @return string
	 */
	public function getTemplateCall( $templateName, $params = [] ) {

		if ( $templateName === '' ) {
			return '';
		}

		return '{{' . $templateName . '|' . join( '|', $params ) . $this->standardTemplateParameters . '}}';
	}

	/**
	 * @see SMWResultPrinter::getParamDefinitions
	 *
	 * @since 1.8
	 *
	 * @param $definitions array of IParamDefinition
	 *
	 * @return array of IParamDefinition|array
	 * @throws Exception
	 */
	public function getParamDefinitions( array $definitions ) {
		$params = parent::getParamDefinitions( $definitions );

		$params['parent'] = [
			'default' => '',
			'message' => 'srf-paramdesc-tree-parent',
		];

		$params['root'] = [
			'default' => '',
			'message' => 'srf-paramdesc-tree-root',
		];

		$params['start level'] = [
			'default' => 1,
			'message' => 'srf-paramdesc-tree-startlevel',
			'type' => 'integer',
		];

		$params['sep'] = [
			'default' => ', ',
			'message' => 'smw-paramdesc-sep',
		];

		$params['template arguments'] = [
			'default' => '',
			'message' => 'smw-paramdesc-template-arguments',
		];

		return $params;
	}

	/**
	 * @param string $rootHash
	 *
	 * @return TreeNode
	 */
	protected function buildTreeFromQueryResult( $rootHash ) {

		$nodes = $this->getHashOfNodes();

		if ( $rootHash !== '' && !array_key_exists( $rootHash, $nodes ) ) {
			return new TreeNode();
		}

		return $this->buildTreeFromNodeList( $rootHash, $nodes );
	}

	/**
	 * @return string | false
	 */
	protected function getRootHash() {

		if ( $this->params['root'] === '' ) {
			return '';
		}

		// get the title object of the root page
		$rootTitle = Title::newFromText( $this->params['root'] );

		if ( $rootTitle !== null ) {
			return DIWikiPage::newFromTitle( $rootTitle )->getSerialization();
		}

		return false;

	}

	/**
	 * @return TreeNode[]
	 */
	protected function getHashOfNodes() {

		/** @var TreeNode[] $nodes */
		$nodes = [];

		$queryResult = $this->getQueryResult();

		$row = $queryResult->getNext();
		while ( $row !== false ) {
			$node = new TreeNode( $row );
			$nodes[$node->getHash()] = $node;
			$row = $queryResult->getNext();
		}

		return $nodes;
	}

	/**
	 * Returns a linker object for making hyperlinks
	 *
	 * @return \Linker
	 */
	public function getLinker( $firstcol = false ) {
		return $this->mLinker;
	}

	/**
	 * Depending on current linking settings, returns a linker object
	 * for making hyperlinks or NULL if no links should be created.
	 *
	 * @param int $column Column number
	 *
	 * @return \Linker|null
	 */
	public function getLinkerForColumn( $column ) {
		return parent::getLinker( $column === 0 );
	}

	private function initalizeStandardTemplateParameters() {

		$query = $this->getQueryResult()->getQuery();
		$userparam = trim( $this->params[ 'userparam' ] );

		$this->standardTemplateParameters =
			( $userparam !== '' ? ( '|userparam=' . $userparam ) : '' ) .
			'|smw-resultquerycondition=' . $query->getQueryString() .
			'|smw-resultquerylimit=' . $query->getLimit() .
			'|smw-resultqueryoffset=' . $query->getOffset();

	}

	/**
	 * @param string $rootHash
	 * @param TreeNode[] $nodes
	 *
	 * @return TreeNode
	 * @throws \Exception
	 */
	protected function buildTreeFromNodeList( $rootHash, $nodes ) {

		$isRootSpecified = $rootHash !== '';

		$root = new TreeNode();
		if ( $isRootSpecified ) {
			$root->addChild( $nodes[$rootHash] );
		}

		$store = $this->getQueryResult()->getStore();
		$parentPointerProperty = DIProperty::newFromUserLabel( $this->params['parent'] );

		foreach ( $nodes as $hash => $node ) {

			$parents = $store->getPropertyValues(
				$node->getResultSubject(),
				$parentPointerProperty
			);

			if ( empty( $parents ) && !$isRootSpecified ) {

				$root->addChild( $node );

			} else {

				foreach ( $parents as $parent ) {

					$parentHash = $parent->getSerialization();

					try {
						if ( array_key_exists( $parentHash, $nodes ) ) {
							$nodes[$parentHash]->addChild( $node );
						} elseif ( !$isRootSpecified ) {
							$root->addChild( $node );
						}
					}
					catch ( Exception $e ) {
						$this->addError( $e->getMessage(), $node->getResultSubject()->getTitle()->getPrefixedText() );
					}
				}
			}
		}
		return $root;
	}

	/**
	 * @param TreeNode $tree
	 *
	 * @return mixed
	 */
	protected function buildLinesFromTree( $tree ) {
		$nodePrinterConfiguration = [
			'format' => trim( $this->params['format'] ),
			'template' => trim( $this->params['template'] ),
			'headers' => $this->params['headers'],
			'named args' => $this->params['named args'],
			'sep' => $this->params['sep'],
		];

		$visitor = new TreeNodePrinter( $this, $nodePrinterConfiguration );
		$lines = $tree->accept( $visitor );
		return $lines;
	}

	/**
	 * @param string $msgkey
	 * @param string | string[] $params
	 */
	protected function addError( $msgkey, $params = [] ) {

		parent::addError(
			\Message::newFromKey( $msgkey )
				->params( $params )
				->inContentLanguage()->text()
		);
	}

}