summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticResultFormats/formats/dygraphs/SRF_Dygraphs.php
blob: 28a9150822fac47b9a021a68af238daa01527689 (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
<?php

/**
 * A query printer that uses the dygraphs JavaScript library
 *
 * @see http://www.semantic-mediawiki.org/wiki/Help:Flot_timeseries_chart
 * @licence GNU GPL v2 or later
 *
 * @since 1.8
 *
 * @author mwjames
 */
class SRFDygraphs extends SMWResultPrinter {

	/**
	 * @see SMWResultPrinter::getName
	 * @return string
	 */
	public function getName() {
		return wfMessage( 'srf-printername-dygraphs' )->text();
	}

	/**
	 * @see SMWResultPrinter::getResultText
	 *
	 * @param SMWQueryResult $result
	 * @param $outputMode
	 *
	 * @return string
	 */
	protected function getResultText( SMWQueryResult $result, $outputMode ) {

		// Output mode is fixed
		$outputMode = SMW_OUTPUT_HTML;

		// Data processing
		$data = $this->getResultData( $result, $outputMode );

		// Post-data processing check
		if ( $data === [] ) {
			return $result->addErrors( [ wfMessage( 'srf-warn-empy-chart' )->inContentLanguage()->text() ] );
		} else {
			$options['sask'] = SRFUtils::htmlQueryResultLink( $this->getLink( $result, SMW_OUTPUT_HTML ) );
			return $this->getFormatOutput( $data, $options );
		}
	}

	/**
	 * Returns an array with numerical data
	 *
	 * @since 1.8
	 *
	 * @param SMWQueryResult $result
	 * @param $outputMode
	 *
	 * @return array
	 */
	protected function getResultData( SMWQueryResult $result, $outputMode ) {
		$aggregatedValues = [];

		while ( $rows = $result->getNext() ) { // Objects (pages)
			$annotation = [];
			$dataSource = false;

			/**
			 * @var SMWResultArray $field
			 * @var SMWDataValue $dataValue
			 */
			foreach ( $rows as $field ) {

				// Use the subject marker to identify a possible data file
				$subject = $field->getResultSubject();
				if ( $this->params['datasource'] === 'file' && $subject->getTitle()->getNamespace(
					) === NS_FILE && !$dataSource ) {
					$aggregatedValues['subject'] = $this->makePageFromTitle( $subject->getTitle() )->getLongHTMLText(
						$this->getLinker( $field->getResultSubject() )
					);
					$aggregatedValues['url'] = wfFindFile( $subject->getTitle() )->getUrl();
					$dataSource = true;
				}

				// Proceed only where a label is known otherwise items are of no use
				// for being a potential object identifier
				if ( $field->getPrintRequest()->getLabel() !== '' ) {
					$propertyLabel = $field->getPrintRequest()->getLabel();
				} else {
					continue;
				}

				while ( ( $dataValue = $field->getNextDataValue() ) !== false ) { // Data values

					// Jump the column (indicated by continue) because we don't want the data source being part of the annotation array
					if ( $dataValue->getDataItem()->getDIType(
						) == SMWDataItem::TYPE_WIKIPAGE && $this->params['datasource'] === 'raw' && !$dataSource ) {
						// Support data source = raw which pulls the url from a wikipage in raw format
						$aggregatedValues['subject'] = $this->makePageFromTitle(
							$dataValue->getTitle()
						)->getLongHTMLText( $this->getLinker( $field->getResultSubject() ) );
						$aggregatedValues['url'] = $dataValue->getTitle()->getLocalURL( 'action=raw' );
						$dataSource = true;
						continue;
					} elseif ( $dataValue->getDataItem()->getDIType(
						) == SMWDataItem::TYPE_WIKIPAGE && $this->params['datasource'] === 'file' && $dataValue->getTitle(
						)->getNamespace() === NS_FILE && !$dataSource ) {
						// Support data source = file which pulls the url from a uploaded file
						$aggregatedValues['subject'] = $this->makePageFromTitle(
							$dataValue->getTitle()
						)->getLongHTMLText( $this->getLinker( $field->getResultSubject() ) );
						$aggregatedValues['url'] = wfFindFile( $dataValue->getTitle() )->getUrl();
						$dataSource = true;
						continue;
					} elseif ( $dataValue->getDataItem()->getDIType(
						) == SMWDataItem::TYPE_URI && $this->params['datasource'] === 'url' && !$dataSource ) {
						// Support data source = url, pointing to an url data source
						$aggregatedValues['link'] = $dataValue->getShortHTMLText( $this->getLinker( false ) );
						$aggregatedValues['url'] = $dataValue->getURL();
						$dataSource = true;
						continue;
					}

					// The annotation should adhere outlined conventions as the label identifies the array object key
					// series -> Required The name of the series to which the annotated point belongs
					// x -> Required The x value of the point
					// shortText -> Text that will appear as annotation flag
					// text -> A longer description of the annotation
					// @see  http://dygraphs.com/annotations.html
					if ( in_array( $propertyLabel, [ 'series', 'x', 'shortText', 'text' ] ) ) {
						if ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_NUMBER ) {
							// Set unit if available
							$dataValue->setOutputFormat( $this->params['unit'] );
							// Check if unit is available
							$annotation[$propertyLabel] = $dataValue->getUnit() !== '' ? $dataValue->getShortWikiText(
							) : $dataValue->getNumber();
						} else {
							$annotation[$propertyLabel] = $dataValue->getWikiValue();
						}
					}
				}
			}
			// Sum-up collected row items in a single array
			if ( $annotation !== [] ) {
				$aggregatedValues['annotation'][] = $annotation;
			}
		}
		return $aggregatedValues;
	}

	private function makePageFromTitle( \Title $title ) {
		$dataValue = new SMWWikiPageValue( '_wpg' );
		$dataItem = SMWDIWikiPage::newFromTitle( $title );
		$dataValue->setDataItem( $dataItem );
		return $dataValue;
	}

	/**
	 * Prepare data for the output
	 *
	 * @since 1.8
	 *
	 * @param array $data
	 *
	 * @return string
	 */
	protected function getFormatOutput( $data, $options ) {

		// Object count
		static $statNr = 0;
		$chartID = 'srf-dygraphs-' . ++$statNr;

		$this->isHTML = true;

		// Reorganize the raw data
		if ( $this->params['datasource'] === 'page' ) {
			foreach ( $data as $key => $values ) {
				$dataObject[] = [ 'label' => $key, 'data' => $values ];
			}
		} else {
			$dataObject['source'] = $data;
		}

		// Prepare transfer array
		$chartData = [
			'data' => $dataObject,
			'sask' => $options['sask'],
			'parameters' => [
				'width' => $this->params['width'],
				'height' => $this->params['height'],
				'xlabel' => $this->params['xlabel'],
				'ylabel' => $this->params['ylabel'],
				'charttitle' => $this->params['charttitle'],
				'charttext' => $this->params['charttext'],
				'infotext' => $this->params['infotext'],
				'datasource' => $this->params['datasource'],
				'rollerperiod' => $this->params['mavg'],
				'gridview' => $this->params['gridview'],
				'errorbar' => $this->params['errorbar'],
			]
		];

		// Array encoding and output
		$requireHeadItem = [ $chartID => FormatJson::encode( $chartData ) ];
		SMWOutputs::requireHeadItem( $chartID, Skin::makeVariablesScript( $requireHeadItem ) );

		SMWOutputs::requireResource( 'ext.srf.dygraphs' );

		if ( $this->params['gridview'] === 'tabs' ) {
			SMWOutputs::requireResource( 'ext.srf.util.grid' );
		}

		// Chart/graph placeholder
		$chart = Html::rawElement(
			'div',
			[ 'id' => $chartID, 'class' => 'container', 'style' => "display:none;" ],
			null
		);

		// Processing/loading image
		$processing = SRFUtils::htmlProcessingElement( $this->isHTML );

		// Beautify class selector
		$class = $this->params['class'] ? ' ' . $this->params['class'] : ' dygraphs-common';

		// General output marker
		return Html::rawElement(
			'div',
			[ 'class' => 'srf-dygraphs' . $class ],
			$processing . $chart
		);
	}

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

		$params['datasource'] = [
			'message' => 'srf-paramdesc-datasource',
			'default' => 'file',
			'values' => [ 'file', 'raw', 'url' ],
		];

		$params['errorbar'] = [
			'message' => 'srf-paramdesc-errorbar',
			'default' => '',
			'values' => [ 'fraction', 'sigma', 'range' ],
		];

		$params['min'] = [
			'type' => 'integer',
			'message' => 'srf-paramdesc-minvalue',
			'default' => '',
		];

		$params['mavg'] = [
			'type' => 'integer',
			'message' => 'srf-paramdesc-movingaverage',
			'default' => 14,
			'lowerbound' => 0,
		];

		$params['gridview'] = [
			'message' => 'srf-paramdesc-gridview',
			'default' => 'none',
			'values' => [ 'none', 'tabs' ],
		];

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

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

		$params['height'] = [
			'type' => 'integer',
			'message' => 'srf_paramdesc_chartheight',
			'default' => 400,
			'lowerbound' => 1,
		];

		$params['width'] = [
			'message' => 'srf_paramdesc_chartwidth',
			'default' => '100%',
		];

		$params['charttitle'] = [
			'message' => 'srf_paramdesc_charttitle',
			'default' => '',
		];

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

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

		$params['ylabel'] = [
			'message' => 'srf-paramdesc-yaxislabel',
			'default' => '',
		];

		$params['xlabel'] = [
			'message' => 'srf-paramdesc-xaxislabel',
			'default' => '',
		];

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

		return $params;
	}
}