-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathICS.php
More file actions
322 lines (275 loc) · 8.74 KB
/
Copy pathICS.php
File metadata and controls
322 lines (275 loc) · 8.74 KB
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
<?php
namespace ICSGen;
// @see https://gist.github.com/jakebellacera/635416
// This version includes improvements:
// - added support for multiple events (ICSEvent class)
// - added support for DateTime objects
// - added line break conversion for description (literal \n)
// - added line length limit (75 characters)
// - respects DateTimeZone of DateTime
// - ability to set timezone for string dates (defaults to system timezone)
// - all dates will be converted to UTC (Z timestamp)
// Output can be validated here: https://icalendar.org/validator.html
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*
* ICS.php
* =============================================================================
* Use this class to create an .ics file.
*
*
* Usage
* -----------------------------------------------------------------------------
* Basic usage - generate ics file contents (see below for available properties):
* $ics = new ICS($props);
* $ics_file_contents = $ics->to_string();
*
* Setting properties after instantiation
* $ics = new ICS();
* $ics->set('summary', 'My awesome event');
*
* You can also set multiple properties at the same time by using an array:
* $ics->set(array(
* 'dtstart' => 'now + 30 minutes',
* 'dtend' => 'now + 1 hour'
* ));
*
* Available properties
* -----------------------------------------------------------------------------
* description
* String description of the event.
* dtend
* A date/time stamp designating the end of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* dtstart
* A date/time stamp designating the start of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* location
* String address or description of the location of the event.
* summary
* String short summary of the event - usually used as the title.
* url
* A url to attach to the the event. Make sure to add the protocol (http://
* or https://).
*/
class ICS {
public $events;
public function __construct(iterable $events = []) {
$this->events = array();
foreach ($events as $event) {
$this->events[] = new ICSEvent($event);
}
}
public function to_string() {
$rows = $this->build_ics();
return implode("\r\n", $rows);
}
private function build_ics() {
// ICS header
$ics_out = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN',
'CALSCALE:GREGORIAN',
);
// ICS events
foreach ($this->events as $event) {
$event_out = $event->build_ics();
$ics_out = array_merge($ics_out, $event_out);
}
// ICS footer
$ics_out[] = 'END:VCALENDAR';
return $ics_out;
}
}
class ICSEvent {
/**
* Mapping known properties to sanitizers
* Simple solution for different Value Data Types
* @see https://datatracker.ietf.org/doc/html/rfc5545#section-3.6.1
* @see https://datatracker.ietf.org/doc/html/rfc5545#section-8.3.4
*/
const PROPERTIES = [
'UID' => 'text',
'DTSTAMP' => 'timestamp',
'DTSTART' => 'timestamp',
'DTEND' => 'timestamp',
'DURATION' => 'text',
'SUMMARY' => 'text',
'DESCRIPTION' => 'longtext',
'LOCATION' => 'text',
'URL' => 'uri',
'LAST-MODIFIED' => 'timestamp',
'RECURRENCE-ID' => 'timestamp',
'CREATED' => 'timestamp',
'PRIORITY' => 'integer',
'SEQUENCE' => 'integer',
'CLASS' => 'text',
'STATUS' => 'text',
'TRANSP' => 'text',
'RESOURCES' => 'rawtext',
'RRULE' => 'rawtext',
'GEO' => 'rawtext',
'ORGANIZER' => 'email',
];
const DT_FORMAT = 'Ymd\THis\Z';
protected $timezone;
protected $properties = array();
public function __construct($event) {
$this->timezone = isset($event['timezone']) ? $event['timezone'] : null;
$this->set($event);
}
/**
* @param array|string $key
* @param DateTime|string $val
*/
protected function set($key, $val = null) {
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($k, $v);
}
return;
} else if ($val === null) return;
$key = strtoupper($key);
if (in_array($key, array_keys(ICSEvent::PROPERTIES))) {
$this->properties[$key] = sanitize_val($val, $key, $this->timezone);
} else if (substr($key, 0, 2) === "X-") {
$this->properties[$key] = $val;
}
}
public function build_ics() {
if (!isset($this->properties['DTSTART'])) {
throw new \InvalidArgumentException('DTSTART is required');
}
$ics_out = array(
'BEGIN:VEVENT'
);
// default properties
$props = array(
'DTSTAMP' => format_timestamp('now', $this->timezone),
'UID' => uniqid('', true) . '@icsgenerator',
);
foreach ($this->properties as $k => $v) {
$propkey = format_property($k);
$props[$propkey] = $v;
}
// Append properties
foreach ($props as $k => $v) {
$ics_out[] = "$k:$v";
}
$ics_out[] = 'END:VEVENT';
return $ics_out;
}
}
/**
* @param DateTime|string $val
* @param string $key
* @param \DateTimeZone|null $timezone
*/
function sanitize_val($val, string $key, $timezone = null) {
$type = ICSEvent::PROPERTIES[$key];
switch ($type) {
case 'timestamp':
return format_timestamp($val, $timezone);
case 'longtext':
// convert description line breaks to "\\n"
// (the file actually has to contain the literal string \n)
$val = preg_replace("/\r\n?|\n/", "\\n", $val);
// limit line length to 75 chars
return ical_split($key, $val);
case 'email':
// if no ":" is present, prepend "mailto:".
// otherwise, take the rawtext to support content like
// ORGANIZER;CN=John Smith:MAILTO:jsmith@host1.com
return (strpos($val, ':') !== false)
? $val
: 'mailto:' . $val;
case 'rawtext':
case 'uri':
return $val;
default:
return escape_string($val);
}
}
/**
* Some properties may have comma-seperated parameters
*/
function format_property($key) {
$property = array($key);
$type = ICSEvent::PROPERTIES[$key];
switch ($type) {
case 'url':
$property[] = 'VALUE=URI';
break;
}
return implode(';', $property);
}
/**
* @param DateTime|string $dt
* @param \DateTimeZone|null $timezone
*/
function format_timestamp($dt, $timezone = null) {
$dt = ($dt instanceof \DateTime) ? $dt : new \DateTime($dt, $timezone);
$dt->setTimeZone(new \DateTimeZone('UTC'));
return $dt->format(ICSEvent::DT_FORMAT);
}
function escape_string(string $str) {
return preg_replace('/([\,;])/', '\\\$1', $str);
}
/**
* @see https://gist.github.com/hugowetterberg/81747
*/
function ical_split(string $preamble, string $value) {
if (!extension_loaded('mbstring')) {
throw new \RuntimeException('mbstring extension required for ICS line folding');
}
$value = trim($value);
$value = strip_tags($value);
$value = preg_replace('/\n+/', ' ', $value);
$value = preg_replace('/\s{2,}/', ' ', $value);
$preamble_len = strlen($preamble) + 1; // "key:"
$lines = array();
while (strlen($value) > (75 - $preamble_len)) {
$space = (75 - $preamble_len);
$mbcc = $space;
while ($mbcc) {
$line = mb_strcut($value, 0, $mbcc);
$oct = strlen($line);
if ($oct > $space) {
$mbcc -= $oct - $space;
} else {
$lines[] = $line;
$preamble_len = 1; // Still take the tab into account
$value = mb_strcut($value, $mbcc);
break;
}
}
}
if (!empty($value)) {
$lines[] = $value;
}
return implode("\r\n\t", $lines);
}