summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticResultFormats/src/iCalendar/iCalendarFileExportPrinter.php
blob: e13e243aefde923b07b42932f9c1cca90330bcb9 (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
<?php

namespace SRF\iCalendar;

use SMW\Query\Result\ResultArray;
use SMWDataValueFactory as DataValueFactory;
use SMWExportPrinter as FileExportPrinter;
use SMWQuery as Query;
use SMWQueryProcessor as QueryProcessor;
use SMWQueryResult as QueryResult;
use SMWTimeValue as TimeValue;
use WikiPage;

/**
 * Printer class for iCalendar exports
 *
 * @see https://en.wikipedia.org/wiki/ICalendar
 * @see https://tools.ietf.org/html/rfc5545
 *
 * @license GNU GPL v2+
 * @since 1.5
 *
 * @author Markus Krötzsch
 * @author Denny Vrandecic
 * @author Jeroen De Dauw
 */
class iCalendarFileExportPrinter extends FileExportPrinter {

	/**
	 * @var string
	 */
	private $title;

	/**
	 * @var string
	 */
	private $description;

	/**
	 * @var IcalTimezoneFormatter
	 */
	private $icalTimezoneFormatter;

	/**
	 * @see ResultPrinter::getName
	 *
	 * @since 1.8
	 *
	 * {@inheritDoc}
	 */
	public function getName() {
		return wfMessage( 'srf_printername_icalendar' )->text();
	}

	/**
	 * @see FileExportPrinter::getMimeType
	 *
	 * @since 1.8
	 *
	 * {@inheritDoc}
	 */
	public function getMimeType( QueryResult $queryResult ) {
		return 'text/calendar';
	}

	/**
	 * @see FileExportPrinter::getFileName
	 *
	 * @since 1.8
	 *
	 * {@inheritDoc}
	 */
	public function getFileName( QueryResult $queryResult ) {

		if ( $this->title != '' ) {
			return str_replace( ' ', '_', $this->title ) . '.ics';
		}

		return 'iCalendar.ics';
	}

	/**
	 * @see FileExportPrinter::getQueryMode
	 *
	 * @since 1.8
	 *
	 * {@inheritDoc}
	 */
	public function getQueryMode( $context ) {
		return ( $context == QueryProcessor::SPECIAL_PAGE ) ? Query::MODE_INSTANCES : Query::MODE_NONE;
	}

	/**
	 * @see ResultPrinter::getParamDefinitions
	 *
	 * @since 1.8
	 *
	 * {@inheritDoc}
	 */
	public function getParamDefinitions( array $definitions ) {
		$params = parent::getParamDefinitions( $definitions );

		$params['title'] = [
			'default' => '',
			'message' => 'srf_paramdesc_icalendartitle',
		];

		$params['description'] = [
			'default' => '',
			'message' => 'srf_paramdesc_icalendardescription',
		];

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

		return $params;
	}

	/**
	 * @see ResultPrinter::handleParameters
	 *
	 * {@inheritDoc}
	 */
	protected function handleParameters( array $params, $outputMode ) {
		parent::handleParameters( $params, $outputMode );

		$this->title = trim( $params['title'] );
		$this->description = trim( $params['description'] );
	}

	/**
	 * @see ResultPrinter::getResultText
	 *
	 * {@inheritDoc}
	 */
	protected function getResultText( QueryResult $res, $outputMode ) {

		if ( $outputMode == SMW_OUTPUT_FILE ) {
			return $this->getIcal( $res );
		}

		return $this->getIcalLink( $res, $outputMode );
	}

	/**
	 * Returns the query result in iCal.
	 */
	private function getIcal( QueryResult $res ) {

		$this->icalTimezoneFormatter = new IcalTimezoneFormatter();

		$this->icalTimezoneFormatter->setLocalTimezones(
			isset( $this->params['timezone'] ) ? $this->params['timezone'] : []
		);

		$result = '';

		if ( $this->title == '' ) {
			$this->title = $GLOBALS['wgSitename'];
		}

		$result .= "BEGIN:VCALENDAR\r\n";
		$result .= "PRODID:-//SMW Project//Semantic Result Formats\r\n";
		$result .= "VERSION:2.0\r\n";
		$result .= "METHOD:PUBLISH\r\n";
		$result .= "X-WR-CALNAME:" . $this->title . "\r\n";

		if ( $this->description !== '' ) {
			$result .= "X-WR-CALDESC:" . $this->description . "\r\n";
		}

		$events = '';

		while ( $row = $res->getNext() ) {
			$events .= $this->getIcalForItem( $row );
		}

		$result .= $this->icalTimezoneFormatter->getTransitions();
		$result .= $events;
		$result .= "END:VCALENDAR\r\n";

		return $result;
	}

	/**
	 * Returns html for a link to a query that returns the iCal.
	 */
	private function getIcalLink( QueryResult $res, $outputMode ) {

		if ( $this->getSearchLabel( $outputMode ) ) {
			$label = $this->getSearchLabel( $outputMode );
		} else {
			$label = wfMessage( 'srf_icalendar_link' )->inContentLanguage()->text();
		}

		$link = $res->getQueryLink( $label );
		$link->setParameter( 'icalendar', 'format' );

		if ( $this->title !== '' ) {
			$link->setParameter( $this->title, 'title' );
		}

		if ( $this->description !== '' ) {
			$link->setParameter( $this->description, 'description' );
		}

		if ( array_key_exists( 'limit', $this->params ) ) {
			$link->setParameter( $this->params['limit'], 'limit' );
		} else { // use a reasonable default limit
			$link->setParameter( 20, 'limit' );
		}

		// yes, our code can be viewed as HTML if requested, no more parsing needed
		$this->isHTML = ( $outputMode == SMW_OUTPUT_HTML );

		return $link->getText( $outputMode, $this->mLinker );
	}

	/**
	 * Returns the iCal for a single item.
	 *
	 * @param ResultArray[] $row
	 *
	 * @return string
	 * @throws \MWException
	 */
	private function getIcalForItem( array $row ) {
		$result = '';

		$subjectDI = $row[0]->getResultSubject(); // get the object
		$subjectDV = DataValueFactory::getInstance()->newDataValueByItem( $subjectDI, null );

		$params = [
			'summary' => $subjectDV->getShortWikiText()
		];

		$from = null;
		$to = null;
		foreach ( $row as /* SMWResultArray */
				  $field ) {
			// later we may add more things like a generic
			// mechanism to add whatever you want :)
			// could include funny things like geo, description etc. though
			$req = $field->getPrintRequest();
			$label = strtolower( $req->getLabel() );

			switch ( $label ) {
				case 'start':
				case 'end':
					if ( $req->getTypeID() == '_dat' ) {
						$dataValue = $field->getNextDataValue();

						if ( $dataValue === false ) {
							unset( $params[$label] );
						} else {
							$params[$label] = $this->parsedate( $dataValue, $label == 'end' );

							$timestamp = strtotime( $params[$label] );
							if ( $from === null || $timestamp < $from ) {
								$from = $timestamp;
							}
							if ( $to === null || $timestamp > $to ) {
								$to = $timestamp;
							}
						}
					}
					break;
				case 'location':
				case 'description':
				case 'summary':
					$value = $field->getNextDataValue();
					if ( $value !== false ) {
						$params[$label] = $value->getShortWikiText();
					}
					break;
			}
		}

		$this->icalTimezoneFormatter->calcTransitions( $from, $to );

		$title = $subjectDI->getTitle();
		$timestamp = WikiPage::factory( $title )->getTimestamp();
		$url = $title->getFullURL();

		$result .= "BEGIN:VEVENT\r\n";
		$result .= "SUMMARY:" . $this->escape( $params['summary'] ) . "\r\n";
		$result .= "URL:$url\r\n";
		$result .= "UID:$url\r\n";

		if ( array_key_exists( 'start', $params ) ) {
			$result .= "DTSTART:" . $params['start'] . "\r\n";
		}

		if ( array_key_exists( 'end', $params ) ) {
			$result .= "DTEND:" . $params['end'] . "\r\n";
		}

		if ( array_key_exists( 'location', $params ) ) {
			$result .= "LOCATION:" . $this->escape( $params['location'] ) . "\r\n";
		}

		if ( array_key_exists( 'description', $params ) ) {
			$result .= "DESCRIPTION:" . $this->escape( $params['description'] ) . "\r\n";
		}

		$t = strtotime( str_replace( 'T', ' ', $timestamp ) );
		$result .= "DTSTAMP:" . date( "Ymd", $t ) . "T" . date( "His", $t ) . "\r\n";
		$result .= "SEQUENCE:" . $title->getLatestRevID() . "\r\n";
		$result .= "END:VEVENT\r\n";

		return $result;
	}

	/**
	 * Extract a date string formatted for iCalendar from a SMWTimeValue object.
	 */
	private function parsedate( TimeValue $dv, $isend = false ) {
		$year = $dv->getYear();

		// ISO range is limited to four digits
		if ( ( $year > 9999 ) || ( $year < -9998 ) ) {
			return '';
		}

		$year = number_format( $year, 0, '.', '' );
		$time = str_replace( ':', '', $dv->getTimeString( false ) );

		// increment by one day, compute date to cover leap years etc.
		if ( ( $time == false ) && ( $isend ) ) {
			$dv = DataValueFactoryg::getInstance()->newDataValueByType(
				'_dat',
				$dv->getWikiValue() . 'T00:00:00-24:00'
			);
		}

		$month = $dv->getMonth();

		if ( strlen( $month ) == 1 ) {
			$month = '0' . $month;
		}

		$day = $dv->getDay();

		if ( strlen( $day ) == 1 ) {
			$day = '0' . $day;
		}

		$result = $year . $month . $day;

		if ( $time != false ) {
			$result .= "T$time";
		}

		return $result;
	}

	/**
	 * Implements esaping of special characters for iCalendar properties of type
	 * TEXT. This is defined in RFC2445 Section 4.3.11.
	 */
	private function escape( $text ) {
		// Note that \\ is a PHP escaped single \ here
		return str_replace( [ "\\", "\n", ";", "," ], [ "\\\\", "\\n", "\\;", "\\," ], $text );
	}

}