]> git.mxchange.org Git - friendica-addons.git/blob - dav/common/wdcal_edit.inc.php
dac493683ef379d9a92f587c69ed8857c192ecf9
[friendica-addons.git] / dav / common / wdcal_edit.inc.php
1 <?php
2
3 /**
4  * @param wdcal_local $localization
5  * @param string $baseurl
6  * @param int $calendar_id
7  * @param int $uri
8  * @return string
9  */
10 function wdcal_getEditPage_str(&$localization, $baseurl, $calendar_id, $uri)
11 {
12         $server = dav_create_server(true, true, false);
13
14         if ($uri > 0) {
15                 $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE);
16                 if (!$calendar) {
17                         $calendar  = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_READ);
18                         $calendars = array();
19                 } else {
20                         $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE);
21                 }
22
23                 if ($calendar == null) return "Calendar not found";
24
25                 $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($uri);
26
27                 $vObject   = dav_get_current_user_calendarobject($server, $calendar, $obj_uri["uri"], DAV_ACL_WRITE);
28                 $component = dav_get_eventComponent($vObject);
29
30                 if ($component == null) return t('Could not open component for editing');
31
32                 /** @var Sabre_VObject_Property_DateTime $dtstart  */
33                 $dtstart = $component->__get("DTSTART");
34                 $event   = array(
35                         "id"            => IntVal($uri),
36                         "Summary"       => ($component->__get("SUMMARY") ? $component->__get("SUMMARY")->value : null),
37                         "StartTime"     => $dtstart->getDateTime()->getTimeStamp(),
38                         "EndTime"       => Sabre_CalDAV_Backend_Common::getDtEndTimeStamp($component),
39                         "IsAllDayEvent" => (strlen($dtstart->value) == 8),
40                         "Description"   => ($component->__get("DESCRIPTION") ? $component->__get("DESCRIPTION")->value : null),
41                         "Location"      => ($component->__get("LOCATION") ? $component->__get("LOCATION")->value : null),
42                         "Color"         => ($component->__get("X-ANIMEXX-COLOR") ? $component->__get("X-ANIMEXX-COLOR")->value : null),
43                 );
44
45                 $exdates             = $component->select("EXDATE");
46                 $recurrentce_exdates = array();
47                 /** @var Sabre_VObject_Property_MultiDateTime $x */
48                 foreach ($exdates as $x) {
49                         /** @var DateTime $y */
50                         $z = $x->getDateTimes();
51                         foreach ($z as $y) $recurrentce_exdates[] = $y->getTimeStamp();
52                 }
53
54                 $notifications = array();
55                 $alarms = $component->select("VALARM");
56                 foreach ($alarms as $alarm)  {
57                         /** @var Sabre_VObject_Component_VAlarm $alarm */
58                         $action = $alarm->__get("ACTION")->value;
59                         $trigger = $alarm->__get("TRIGGER");
60
61                         if(isset($trigger['VALUE']) && strtoupper($trigger['VALUE']) !== 'DURATION') {
62                                 notice("The notification of this event cannot be parsed");
63                                 continue;
64                         }
65
66                         /** @var DateInterval $triggerDuration  */
67                         $triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($trigger);
68                         $unit = "hour";
69                         $value = 1;
70                         if ($triggerDuration->s > 0) {
71                                 $unit = "second";
72                                 $value = $triggerDuration->s + $triggerDuration->i * 60 + $triggerDuration->h * 3600 + $triggerDuration->d * 3600 * 24; // @TODO support more than days?
73                         } elseif ($triggerDuration->i) {
74                                 $unit = "minute";
75                                 $value = $triggerDuration->i + $triggerDuration->h * 60 + $triggerDuration->d * 60 * 24;
76                         } elseif ($triggerDuration->h) {
77                                 $unit = "hour";
78                                 $value = $triggerDuration->h + $triggerDuration->d * 24;
79                         } elseif ($triggerDuration->d > 0) {
80                                 $unit = "day";
81                                 $value = $triggerDuration->d;
82                         }
83
84                         $rel = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'end' : 'start';
85
86
87                         $notifications[] = array(
88                                 "action" => strtolower($action),
89                                 "rel" => $rel,
90                                 "trigger_unit" => $unit,
91                                 "trigger_value" => $value,
92                         );
93                 }
94
95                 if ($component->select("RRULE")) $recurrence = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID"));
96                 else $recurrence = null;
97
98         } elseif (isset($_REQUEST["start"]) && $_REQUEST["start"] > 0) {
99                 $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE);
100                 //$calendar  = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE);
101
102                 $event = array(
103                         "id"            => 0,
104                         "Summary"       => $_REQUEST["title"],
105                         "StartTime"     => InTVal($_REQUEST["start"]),
106                         "EndTime"       => IntVal($_REQUEST["end"]),
107                         "IsAllDayEvent" => $_REQUEST["isallday"],
108                         "Description"   => "",
109                         "Location"      => "",
110                         "Color"         => null,
111                 );
112                 if ($_REQUEST["isallday"]) {
113                         $notifications = array();
114                 } else {
115                         $notifications = array(array("action" => "email", "rel" => "start", "trigger_unit" => "hour", "trigger_value" => 1));
116                 }
117                 $recurrence          = null;
118                 $recurrentce_exdates = array();
119         } else {
120                 $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE);
121                 //$calendar  = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE);
122
123                 $event               = array(
124                         "id"            => 0,
125                         "Summary"       => "",
126                         "StartTime"     => time(),
127                         "EndTime"       => time() + 3600,
128                         "IsAllDayEvent" => "0",
129                         "Description"   => "",
130                         "Location"      => "",
131                         "Color"         => null,
132                 );
133                 $notifications = array(array("action" => "email", "rel" => "start", "trigger_unit" => "hour", "trigger_value" => 1));
134                 $recurrence          = null;
135                 $recurrentce_exdates = array();
136         }
137
138         $postto = $baseurl . "/dav/wdcal/" . ($uri == 0 ? "new/" : $calendar_id . "/" . $uri . "/edit/");
139
140         $out = "<a href='" . $baseurl . "/dav/wdcal/'>" . t("Go back to the calendar") . "</a><br><br>";
141         $out .= "<form method='POST' action='$postto'>
142                 <input type='hidden' name='form_security_token' value='" . get_form_security_token('caledit') . "'>\n";
143
144         $out .= "<h2>" . t("Event data") . "</h2>";
145
146         $out .= "<label for='calendar' class='block'>" . t("Calendar") . ":</label><select id='calendar' name='calendar' size='1'>";
147         $found   = false;
148         $cal_col = "aaaaaa";
149         foreach ($calendars as $cal) {
150                 $prop = $cal->getProperties(array("id", DAV_DISPLAYNAME, DAV_CALENDARCOLOR));
151                 $out .= "<option value='" . $prop["id"] . "' ";
152                 if ($prop["id"] == $calendar_id) {
153                         $out .= "selected";
154                         $cal_col = $prop[DAV_CALENDARCOLOR];
155                         $found   = true;
156                 } elseif (!$found) $cal_col = $prop[DAV_CALENDARCOLOR];
157                 $out .= ">" . escape_tags($prop[DAV_DISPLAYNAME]) . "</option>\n";
158         }
159
160         $out .= "</select>";
161         $out .= "&nbsp; &nbsp; <label class='plain'><input type='checkbox' name='color_override' id='color_override' ";
162         if (!is_null($event["Color"])) $out .= "checked";
163         $out .= "> " . t("Special color") . ":</label>";
164         $out .= "<span id='cal_color_holder' ";
165         if (is_null($event["Color"])) $out .= "style='display: none;'";
166         $out .= "><input name='color' id='cal_color' value='" . (is_null($event["Color"]) ? "#" . $cal_col : escape_tags($event["Color"])) . "'></span>";
167         $out .= "<br>\n";
168
169         $out .= "<label class='block' for='cal_summary'>" . t("Subject") . ":</label>
170                 <input name='summary' id='cal_summary' value=\"" . escape_tags($event["Summary"]) . "\"><br>\n";
171         $out .= "<label class='block' for='cal_allday'>Is All-Day event:</label><input type='checkbox' name='allday' id='cal_allday' " . ($event["IsAllDayEvent"] ? "checked" : "") . "><br>\n";
172
173         $out .= "<label class='block' for='cal_start_date'>" . t("Starts") . ":</label>";
174         $out .= "<input name='start_date' value='" . $localization->dateformat_datepicker_php($event["StartTime"]) . "' id='cal_start_date'>";
175         $out .= "<input name='start_time' value='" . date("H:i", $event["StartTime"]) . "' id='cal_start_time'>";
176         $out .= "<br>\n";
177
178         $out .= "<label class='block' for='cal_end_date'>" . t("Ends") . ":</label>";
179         $out .= "<input name='end_date' value='" . $localization->dateformat_datepicker_php($event["EndTime"]) . "' id='cal_end_date'>";
180         $out .= "<input name='end_time' value='" . date("H:i", $event["EndTime"]) . "' id='cal_end_time'>";
181         $out .= "<br>\n";
182
183         $out .= "<label class='block' for='cal_location'>" . t("Location") . ":</label><input name='location' id='cal_location' value=\"" . escape_tags($event["Location"]) . "\"><br>\n";
184
185         $out .= "<label class='block' for='event-desc-textarea'>" . t("Description") . ":</label> <textarea id='event-desc-textarea' name='wdcal_desc' style='vertical-align: top; width: 400px; height: 100px;'>" . escape_tags($event["Description"]) . "</textarea>";
186         $out .= "<br style='clear: both;'>";
187
188         $out .= "<h2>" . t("Recurrence") . "</h2>";
189
190         $out .= "<label class='block' for='rec_frequency'>" . t("Frequency") . ":</label> <select id='rec_frequency' name='rec_frequency' size='1'>";
191         $out .= "<option value=''>" . t("None") . "</option>\n";
192         $out .= "<option value='daily' ";
193         if ($recurrence && $recurrence->frequency == "daily") $out .= "selected";
194         $out .= ">" . t("Daily") . "</option>\n";
195         $out .= "<option value='weekly' ";
196         if ($recurrence && $recurrence->frequency == "weekly") $out .= "selected";
197         $out .= ">" . t("Weekly") . "</option>\n";
198         $out .= "<option value='monthly' ";
199         if ($recurrence && $recurrence->frequency == "monthly") $out .= "selected";
200         $out .= ">" . t("Monthly") . "</option>\n";
201         $out .= "<option value='yearly' ";
202         if ($recurrence && $recurrence->frequency == "yearly") $out .= "selected";
203         $out .= ">" . t("Yearly") . "</option>\n";
204         $out .= "</select><br>\n";
205         $out .= "<div id='rec_details'>";
206
207         $select = "<select id='rec_interval' name='rec_interval' size='1'>";
208         for ($i = 1; $i < 50; $i++) {
209                 $select .= "<option value='$i' ";
210                 if ($recurrence && $i == $recurrence->interval) $select .= "selected";
211                 $select .= ">$i</option>\n";
212         }
213         $select .= "</select>";
214         $time = "<span class='rec_daily'>" . t("days") . "</span>";
215         $time .= "<span class='rec_weekly'>" . t("weeks") . "</span>";
216         $time .= "<span class='rec_monthly'>" . t("months") . "</span>";
217         $time .= "<span class='rec_yearly'>" . t("years") . "</span>";
218         $out .= "<label class='block'>" . t("Interval") . ":</label> " . str_replace(array("%select%", "%time%"), array($select, $time), t("All %select% %time%")) . "<br>";
219
220
221         $out .= "<div class='rec_daily'>";
222         $out .= "<label class='block'>" . t("Days") . ":</label>";
223         if ($recurrence && $recurrence->byDay) {
224                 $byday = $recurrence->byDay;
225         } else {
226                 $byday = array("MO", "TU", "WE", "TH", "FR", "SA", "SU");
227         }
228         if ($localization->getFirstDayOfWeek() == 0) {
229                 $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='SU' ";
230                 if (in_array("SU", $byday)) $out .= "checked";
231                 $out .= ">" . t("Sunday") . "</label> &nbsp; ";
232         }
233         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='MO' ";
234         if (in_array("MO", $byday)) $out .= "checked";
235         $out .= ">" . t("Monday") . "</label> &nbsp; ";
236         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='TU' ";
237         if (in_array("TU", $byday)) $out .= "checked";
238         $out .= ">" . t("Tuesday") . "</label> &nbsp; ";
239         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='WE' ";
240         if (in_array("WE", $byday)) $out .= "checked";
241         $out .= ">" . t("Wednesday") . "</label> &nbsp; ";
242         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='TH' ";
243         if (in_array("TH", $byday)) $out .= "checked";
244         $out .= ">" . t("Thursday") . "</label> &nbsp; ";
245         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='FR' ";
246         if (in_array("FR", $byday)) $out .= "checked";
247         $out .= ">" . t("Friday") . "</label> &nbsp; ";
248         $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='SA' ";
249         if (in_array("SA", $byday)) $out .= "checked";
250         $out .= ">" . t("Saturday") . "</label> &nbsp; ";
251         if ($localization->getFirstDayOfWeek() != 0) {
252                 $out .= "<label class='plain'><input class='rec_daily_byday' type='checkbox' name='rec_daily_byday[]' value='SU' ";
253                 if (in_array("SU", $byday)) $out .= "checked";
254                 $out .= ">" . t("Sunday") . "</label> &nbsp; ";
255         }
256         $out .= "</div>";
257
258
259         $out .= "<div class='rec_weekly'>";
260         $out .= "<label class='block'>" . t("Days") . ":</label>";
261         if ($recurrence && $recurrence->byDay) {
262                 $byday = $recurrence->byDay;
263         } else {
264                 $days = array("MO", "TU", "WE", "TH", "FR", "SA", "SU");
265                 $byday = array($days[date("N", $event["StartTime"]) - 1]);
266         }
267         if ($localization->getFirstDayOfWeek() == 0) {
268                 $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='SU' ";
269                 if (in_array("SU", $byday)) $out .= "checked";
270                 $out .= ">" . t("Sunday") . "</label> &nbsp; ";
271         }
272         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='MO' ";
273         if (in_array("MO", $byday)) $out .= "checked";
274         $out .= ">" . t("Monday") . "</label> &nbsp; ";
275         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='TU' ";
276         if (in_array("TU", $byday)) $out .= "checked";
277         $out .= ">" . t("Tuesday") . "</label> &nbsp; ";
278         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='WE' ";
279         if (in_array("WE", $byday)) $out .= "checked";
280         $out .= ">" . t("Wednesday") . "</label> &nbsp; ";
281         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='TH' ";
282         if (in_array("TH", $byday)) $out .= "checked";
283         $out .= ">" . t("Thursday") . "</label> &nbsp; ";
284         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='FR' ";
285         if (in_array("FR", $byday)) $out .= "checked";
286         $out .= ">" . t("Friday") . "</label> &nbsp; ";
287         $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='SA' ";
288         if (in_array("SA", $byday)) $out .= "checked";
289         $out .= ">" . t("Saturday") . "</label> &nbsp; ";
290         if ($localization->getFirstDayOfWeek() != 0) {
291                 $out .= "<label class='plain'><input class='rec_weekly_byday' type='checkbox' name='rec_weekly_byday[]' value='SU' ";
292                 if (in_array("SU", $byday)) $out .= "checked";
293                 $out .= ">" . t("Sunday") . "</label> &nbsp; ";
294         }
295         $out .= "<br>";
296
297         $out .= "<label class='block'>" . t("First day of week:") . "</label>";
298         if ($recurrence && $recurrence->weekStart != "") $wkst = $recurrence->weekStart;
299         else {
300                 if ($localization->getFirstDayOfWeek() == 0) $wkst = "SU";
301                 else $wkst = "MO";
302         }
303         $out .= "<label class='plain'><input type='radio' name='rec_weekly_wkst' value='SU' ";
304         if ($wkst == "SU") $out .= "checked";
305         $out .= ">" . t("Sunday") . "</label> &nbsp; ";
306         $out .= "<label class='plain'><input type='radio' name='rec_weekly_wkst' value='MO' ";
307         if ($wkst == "MO") $out .= "checked";
308         $out .= ">" . t("Monday") . "</label><br>\n";
309
310         $out .= "</div>";
311
312         $monthly_rule = "";
313         if ($recurrence && ($recurrence->frequency == "monthly" || $recurrence->frequency == "yearly")) {
314                 if (is_null($recurrence->byDay) && !is_null($recurrence->byMonthDay) && count($recurrence->byMonthDay) == 1) {
315                         $day = date("j", $event["StartTime"]);
316                         if ($recurrence->byMonthDay[0] == $day) $monthly_rule = "bymonthday";
317                         else {
318                                 $lastday = date("t", $event["StartTime"]);
319                                 if ($recurrence->byMonthDay[0] == -1 * ($lastday - $day + 1)) $monthly_rule = "bymonthday_neg";
320                         }
321                 }
322                 if (is_null($recurrence->byMonthDay) && !is_null($recurrence->byDay) && count($recurrence->byDay) == 1) {
323                         $num = IntVal($recurrence->byDay[0]);
324                         /*
325                         $dayMap = array(
326                                 'SU' => 0,
327                                 'MO' => 1,
328                                 'TU' => 2,
329                                 'WE' => 3,
330                                 'TH' => 4,
331                                 'FR' => 5,
332                                 'SA' => 6,
333                         );
334                         if ($num == 0) {
335                                 $num = 1;
336                                 $weekday = $dayMap[$recurrence->byDay[0]];
337                         } else {
338                                 $weekday = $dayMap[substr($recurrence->byDay[0], strlen($num))];
339                         }
340
341                         echo $num . " - " . $weekday;
342                         */
343                         if ($num > 0) $monthly_rule = "byday";
344                         if ($num < 0) $monthly_rule = "byday_neg";
345                 }
346                 if ($monthly_rule == "") notice("The recurrence of this event cannot be parsed");
347         }
348
349         $out .= "<div class='rec_monthly'>";
350         $out .= "<label class='block' for='rec_monthly_day'>" . t("Day of month") . ":</label>";
351         $out .= "<select id='rec_monthly_day' name='rec_monthly_day' size='1'>";
352         $out .= "<option value='bymonthday' ";
353         if ($monthly_rule == "bymonthday") $out .= "selected";
354         $out .= ">" . t("#num#th of each month") . "</option>\n";
355         $out .= "<option value='bymonthday_neg' ";
356         if ($monthly_rule == "bymonthday_neg") $out .= "selected";
357         $out .= ">" . t("#num#th-last of each month") . "</option>\n";
358         $out .= "<option value='byday' ";
359         if ($monthly_rule == "byday") $out .= "selected";
360         $out .= ">" . t("#num#th #wkday# of each month") . "</option>\n";
361         $out .= "<option value='byday_neg' ";
362         if ($monthly_rule == "byday_neg") $out .= "selected";
363         $out .= ">" . t("#num#th-last #wkday# of each month") . "</option>\n";
364         $out .= "</select>";
365         $out .= "</div>\n";
366
367         if ($recurrence && $recurrence->frequency == "yearly") {
368                 if (count($recurrence->byMonth) != 1 || $recurrence->byMonth[0] != date("n", $event["StartTime"])) notice("The recurrence of this event cannot be parsed!");
369         }
370
371         $out .= "<div class='rec_yearly'>";
372         $out .= "<label class='block'>" . t("Month") . ":</label> <span class='rec_month_name'>#month#</span><br>\n";
373         $out .= "<label class='block' for='rec_yearly_day'>" . t("Day of month") . ":</label>";
374         $out .= "<select id='rec_yearly_day' name='rec_yearly_day' size='1'>";
375         $out .= "<option value='bymonthday' ";
376         if ($monthly_rule == "bymonthday") $out .= "selected";
377         $out .= ">" . t("#num#th of the given month") . "</option>\n";
378         $out .= "<option value='bymonthday_neg' ";
379         if ($monthly_rule == "bymonthday_neg") $out .= "selected";
380         $out .= ">" . t("#num#th-last of the given month") . "</option>\n";
381         $out .= "<option value='byday' ";
382         if ($monthly_rule == "byday") $out .= "selected";
383         $out .= ">" . t("#num#th #wkday# of the given month") . "</option>\n";
384         $out .= "<option value='byday_neg' ";
385         if ($monthly_rule == "byday_neg") $out .= "selected";
386         $out .= ">" . t("#num#th-last #wkday# of the given month") . "</option>\n";
387         $out .= "</select>";
388         $out .= "</div>\n";
389
390
391         if ($recurrence) {
392                 $until = $recurrence->until;
393                 $count = $recurrence->count;
394                 if (is_a($until, "DateTime")) {
395                         /** @var DateTime $until */
396                         $rule_type        = "date";
397                         $rule_until_date  = $until->getTimestamp();
398                         $rule_until_count = 1;
399                 } elseif ($count > 0) {
400                         $rule_type        = "count";
401                         $rule_until_date  = time();
402                         $rule_until_count = $count;
403                 } else {
404                         $rule_type        = "infinite";
405                         $rule_until_date  = time();
406                         $rule_until_count = 1;
407                 }
408         } else {
409                 $rule_type        = "infinite";
410                 $rule_until_date  = time();
411                 $rule_until_count = 1;
412         }
413         $out .= "<label class='block' for='rec_until_type'>" . t("Repeat until") . ":</label> ";
414         $out .= "<select name='rec_until_type' id='rec_until_type' size='1'>";
415         $out .= "<option value='infinite' ";
416         if ($rule_type == "infinite") $out .= "selected";
417         $out .= ">" . t("Infinite") . "</option>\n";
418         $out .= "<option value='date' ";
419         if ($rule_type == "date") $out .= "selected";
420         $out .= ">" . t("Until the following date") . ":</option>\n";
421         $out .= "<option value='count' ";
422         if ($rule_type == "count") $out .= "selected";
423         $out .= ">" . t("Number of times") . ":</option>\n";
424         $out .= "</select>";
425
426         $out .= "<input name='rec_until_date' value='" . $localization->dateformat_datepicker_php($rule_until_date) . "' id='rec_until_date'>";
427         $out .= "<input name='rec_until_count' value='$rule_until_count' id='rec_until_count'><br>";
428
429         $out .= "<label class='block'>" . t("Exceptions") . ":</label><div class='rec_exceptions'>";
430         $out .= "<div class='rec_exceptions_none' ";
431         if (count($recurrentce_exdates) > 0) $out .= "style='display: none;'";
432         $out .= ">" . t("none") . "</div>";
433         $out .= "<div class='rec_exceptions_holder' ";
434         if (count($recurrentce_exdates) == 0) $out .= "style='display: none;'";
435         $out .= ">";
436
437         foreach ($recurrentce_exdates as $exdate) {
438                 $out .= "<div data-timestamp='$exdate' class='except'><input type='hidden' class='rec_exception' name='rec_exceptions[]' value='$exdate'>";
439                 $out .= "<a href='#' class='exception_remover'>[remove]</a> ";
440                 $out .= $localization->date_timestamp2localDate($exdate);
441                 $out .= "</div>\n";
442         }
443         $out .= "</div><div><a href='#' class='exception_adder'>[add]</a></div>";
444         $out .= "</div>\n";
445         $out .= "<br>\n";
446
447         $out .= "</div><br>";
448
449         $out .= "<h2>" . t("Notification") . "</h2>";
450
451         if (!$notifications) $notifications = array();
452         $notifications["new"] = array(
453                 "action" => "email",
454                 "trigger_value" => 60,
455                 "trigger_unit" => "minute",
456                 "rel" => "start",
457         );
458
459         foreach ($notifications as $index => $noti) {
460
461                 $unparsable = false;
462                 if (!in_array($noti["action"], array("email", "display"))) $unparsable = true;
463
464                 $out .= "<div class='noti_holder' ";
465                 if (!is_numeric($index) && $index == "new") $out .= "style='display: none;' id='noti_new_row'";
466                 $out .= "><label class='block' for='noti_type_" . $index . "'>" . t("Notify by") . ":</label>";
467                 $out .= "<select name='noti_type[$index]' size='1' id='noti_type_" . $index . "'>";
468                 $out .= "<option value=''>- " . t("Remove") . " -</option>\n";
469                 $out .= "<option value='email' "; if (!$unparsable && $noti["action"] == "email") $out .= "selected"; $out .= ">" . t("E-Mail") . "</option>\n";
470                 $out .= "<option value='display' "; if (!$unparsable && $noti["action"] == "display") $out .= "selected"; $out .= ">" . t("On Friendica / Display") . "</option>\n";
471                 //$out .= "<option value='other' "; if ($unparsable) $out .= "selected"; $out .= ">- " . t("other (leave it untouched)") . " -</option>\n"; // @TODO
472                 $out .= "</select><br>";
473
474                 $out .= "<label class='block'>" . t("Time") . ":</label>";
475                 $out .= "<input name='noti_value[$index]' size='5' style='width: 5em;' value='" . $noti["trigger_value"] . "'>";
476
477                 $out .= "<select name='noti_unit[$index]' size='1'>";
478                 $out .= "<option value='H' "; if ($noti["trigger_unit"] == "hour") $out .= "selected"; $out .= ">" . t("Hours") . "</option>\n";
479                 $out .= "<option value='M' "; if ($noti["trigger_unit"] == "minute") $out .= "selected"; $out .= ">" . t("Minutes") . "</option>\n";
480                 $out .= "<option value='S' "; if ($noti["trigger_unit"] == "second") $out .= "selected"; $out .= ">" . t("Seconds") . "</option>\n";
481                 $out .= "<option value='D' "; if ($noti["trigger_unit"] == "day") $out .= "selected"; $out .= ">" . t("Days") . "</option>\n";
482                 $out .= "<option value='W' "; if ($noti["trigger_unit"] == "week") $out .= "selected"; $out .= ">" . t("Weeks") . "</option>\n";
483                 $out .= "</select>";
484
485                 $out .= " <label class='plain'>" . t("before the") . " <select name='noti_ref[$index]' size='1'>";
486                 $out .= "<option value='start' "; if ($noti["rel"] == "start") $out .= "selected"; $out .= ">" . t("start of the event") . "</option>\n";
487                 $out .= "<option value='end' "; if ($noti["rel"] == "end") $out .= "selected"; $out .= ">" . t("end of the event") . "</option>\n";
488                 $out .= "</select></label>\n";
489
490                 $out .= "</div>";
491         }
492         $out .= "<input type='hidden' name='new_alarm' id='new_alarm' value='0'><div id='new_alarm_adder'><a href='#'>" . t("Add a notification") . "</a></div>";
493
494         $out .= "<script>\$(function() {
495                 wdcal_edit_init('" . $localization->dateformat_datepicker_js() . "', '${baseurl}/dav/');
496         });</script>";
497
498         $out .= "<br><input type='submit' name='save' value='Save'></form>";
499
500         return $out;
501 }
502
503
504 /**
505  * @param Sabre_VObject_Component_VEvent $component
506  * @param wdcal_local $localization
507  * @return int
508  */
509 function wdcal_set_component_date(&$component, &$localization)
510 {
511         if (isset($_REQUEST["allday"])) {
512                 $ts_start = $localization->date_local2timestamp($_REQUEST["start_date"] . " 00:00");
513                 $ts_end   = $localization->date_local2timestamp($_REQUEST["end_date"] . " 00:00");
514                 $type     = Sabre_VObject_Property_DateTime::DATE;
515         } else {
516                 $ts_start = $localization->date_local2timestamp($_REQUEST["start_date"] . " " . $_REQUEST["start_time"]);
517                 $ts_end   = $localization->date_local2timestamp($_REQUEST["end_date"] . " " . $_REQUEST["end_time"]);
518                 $type     = Sabre_VObject_Property_DateTime::LOCALTZ;
519         }
520         $datetime_start = new Sabre_VObject_Property_DateTime("DTSTART");
521         $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_start)), $type);
522         $datetime_end = new Sabre_VObject_Property_DateTime("DTEND");
523         $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_end)), $type);
524
525         $component->__unset("DTSTART");
526         $component->__unset("DTEND");
527         $component->add($datetime_start);
528         $component->add($datetime_end);
529
530         return $ts_start;
531 }
532
533 /**
534  * @param Sabre_VObject_Component_VEvent $component
535  * @param string $str
536  * @return string
537  */
538
539 function wdcal_set_component_recurrence_special(&$component, $str) {
540         $ret = "";
541
542         /** @var Sabre_VObject_Property_DateTime $start  */
543         $start  = $component->__get("DTSTART");
544         $dayMap = array(
545                 0 => 'SU',
546                 1 => 'MO',
547                 2 => 'TU',
548                 3 => 'WE',
549                 4 => 'TH',
550                 5 => 'FR',
551                 6 => 'SA',
552         );
553
554         switch ($str) {
555                 case "bymonthday":
556                         $day = $start->getDateTime()->format("j");
557                         $ret = ";BYMONTHDAY=" . $day;
558                         break;
559                 case "bymonthday_neg":
560                         $day     = $start->getDateTime()->format("j");
561                         $day_max = $start->getDateTime()->format("t");
562                         $ret = ";BYMONTHDAY=" . (-1 * ($day_max - $day + 1));
563                         break;
564                 case "byday":
565                         $day     = $start->getDateTime()->format("j");
566                         $weekday = $dayMap[$start->getDateTime()->format("w")];
567                         $num     = IntVal(ceil($day / 7));
568                         $ret = ";BYDAY=${num}${weekday}";
569                         break;
570                 case "byday_neg":
571                         $day     = $start->getDateTime()->format("j");
572                         $weekday = $dayMap[$start->getDateTime()->format("w")];
573                         $day_max = $start->getDateTime()->format("t");
574                         $day_last = ($day_max - $day + 1);
575                         $num     = IntVal(ceil($day_last / 7));
576                         $ret = ";BYDAY=-${num}${weekday}";
577                         break;
578         }
579         return $ret;
580 }
581
582 /**
583  * @param Sabre_VObject_Component_VEvent $component
584  * @param wdcal_local $localization
585  */
586 function wdcal_set_component_recurrence(&$component, &$localization)
587 {
588         $component->__unset("RRULE");
589         $component->__unset("EXRULE");
590         $component->__unset("EXDATE");
591         $component->__unset("RDATE");
592
593         $part_until = "";
594         switch ($_REQUEST["rec_until_type"]) {
595                 case "date":
596                         $date           = $localization->date_local2timestamp($_REQUEST["rec_until_date"]);
597                         $part_until     = ";UNTIL=" . date("Ymd", $date);
598                         $datetime_until = new Sabre_VObject_Property_DateTime("UNTIL");
599                         $datetime_until->setDateTime(new DateTime(date("Y-m-d H:i:s", $date)), Sabre_VObject_Property_DateTime::DATE);
600                         break;
601                 case "count":
602                         $part_until = ";COUNT=" . IntVal($_REQUEST["rec_until_count"]);
603                         break;
604         }
605
606         switch ($_REQUEST["rec_frequency"]) {
607                 case "daily":
608                         $part_freq = "FREQ=DAILY";
609                         if (isset($_REQUEST["rec_daily_byday"])) {
610                                 $days = array();
611                                 foreach ($_REQUEST["rec_daily_byday"] as $x) if (in_array($x, array("MO", "TU", "WE", "TH", "FR", "SA", "SU"))) $days[] = $x;
612                                 if (count($days) > 0) $part_freq .= ";BYDAY=" . implode(",", $days);
613                         }
614                         break;
615                 case "weekly":
616                         $part_freq = "FREQ=WEEKLY";
617                         if (isset($_REQUEST["rec_weekly_wkst"]) && in_array($_REQUEST["rec_weekly_wkst"], array("MO", "SU"))) $part_freq .= ";WKST=" . $_REQUEST["rec_weekly_wkst"];
618                         if (isset($_REQUEST["rec_weekly_byday"])) {
619                                 $days = array();
620                                 foreach ($_REQUEST["rec_weekly_byday"] as $x) if (in_array($x, array("MO", "TU", "WE", "TH", "FR", "SA", "SU"))) $days[] = $x;
621                                 if (count($days) > 0) $part_freq .= ";BYDAY=" . implode(",", $days);
622                         }
623                         break;
624                 case "monthly":
625                         $part_freq = "FREQ=MONTHLY";
626                         $part_freq .= wdcal_set_component_recurrence_special($component, $_REQUEST["rec_monthly_day"]);
627                         break;
628                 case "yearly":
629                         /** @var Sabre_VObject_Property_DateTime $start  */
630                         $start  = $component->__get("DTSTART");
631                         $part_freq = "FREQ=YEARLY";
632                         $part_freq .= ";BYMONTH=" . $start->getDateTime()->format("n");
633                         $part_freq .= wdcal_set_component_recurrence_special($component, $_REQUEST["rec_yearly_day"]);
634                         break;
635                 default:
636                         $part_freq = "";
637         }
638
639         if ($part_freq == "") return;
640
641         if (isset($_REQUEST["rec_interval"])) $part_freq .= ";INTERVAL=" . InTVal($_REQUEST["rec_interval"]);
642
643         if (isset($_REQUEST["rec_exceptions"])) {
644                 $arr = array();
645                 foreach ($_REQUEST["rec_exceptions"] as $except) {
646                         $arr[] = new DateTime(date("Y-m-d H:i:s", $except));
647                 }
648                 /** @var Sabre_VObject_Property_MultiDateTime $prop */
649                 $prop = Sabre_VObject_Property::create("EXDATE");
650                 $prop->setDateTimes($arr);
651                 $component->add($prop);
652         }
653
654         $rrule = $part_freq . $part_until;
655         $component->add(new Sabre_VObject_Property("RRULE", $rrule));
656
657 }
658
659
660         /**
661          * @param Sabre_VObject_Component_VEvent $component
662          * @param wdcal_local $localization
663          * @param string $summary
664          * @param int $dtstart
665          */
666 function wdcal_set_component_alerts(&$component, &$localization, $summary, $dtstart)
667 {
668         $a = get_app();
669
670         $prev_alarms = $component->select("VALARM");
671         $component->__unset("VALARM");
672
673         foreach ($prev_alarms as $al) {
674                 /** @var Sabre_VObject_Component_VAlarm $al */
675                 // @TODO Parse notifications that have been there before; e.g. from Lightning
676         }
677
678         foreach (array_keys($_REQUEST["noti_type"]) as $key) if (is_numeric($key) || ($key == "new" && $_REQUEST["new_alarm"] == 1)) {
679                 $alarm = new Sabre_VObject_Component_VAlarm("VALARM");
680
681                 switch ($_REQUEST["noti_type"][$key]) {
682                         case "email":
683                                 $mailtext = str_replace(array(
684                                         "#date#", "#name",
685                                 ), array(
686                                         $localization->date_timestamp2local($dtstart), $summary,
687                                 ), t("The event #name# will start at #date"));
688
689                                 $alarm->add(new Sabre_VObject_Property("ACTION", "EMAIL"));
690                                 $alarm->add(new Sabre_VObject_Property("SUMMARY", $summary));
691                                 $alarm->add(new Sabre_VObject_Property("DESCRIPTION", $mailtext));
692                                 $alarm->add(new Sabre_VObject_Property("ATTENDEE", "MAILTO:" . $a->user["email"]));
693                                 break;
694                         case "display":
695                                 $alarm->add(new Sabre_VObject_Property("ACTION", "DISPLAY"));
696                                 $text = str_replace("#name#", $summary, t("#name# is about to begin."));
697                                 $alarm->add(new Sabre_VObject_Property("DESCRIPTION", $text));
698                                 break;
699                         default:
700                                 continue;
701                 }
702
703                 $trigger_name = "TRIGGER";
704                 $trigger_val = ""; // @TODO Bugfix : und ; sind evtl. vertauscht vgl. http://www.kanzaki.com/docs/ical/trigger.html
705                 if ($_REQUEST["noti_ref"][$key] == "end") $trigger_name .= ";RELATED=END";
706                 $trigger_val .= "-P";
707                 if (in_array($_REQUEST["noti_unit"][$key], array("H", "M", "S"))) $trigger_val .= "T";
708                 $trigger_val .= IntVal($_REQUEST["noti_value"][$key]) . $_REQUEST["noti_unit"][$key];
709                 $alarm->add(new Sabre_VObject_Property($trigger_name, $trigger_val));
710
711                 $component->add($alarm);
712         }
713
714 }
715
716         /**
717  * @param string $uri
718  * @param int $uid
719  * @param string $timezone
720  * @param string $goaway_url
721  * @return array
722  */
723 function wdcal_postEditPage($uri, $uid = 0, $timezone = "", $goaway_url = "")
724 {
725         $uid          = IntVal($uid);
726         $localization = wdcal_local::getInstanceByUser($uid);
727
728         $server = dav_create_server(true, true, false);
729
730         if ($uri > 0) {
731                 $calendar = dav_get_current_user_calendar_by_id($server, $_REQUEST["calendar"], DAV_ACL_READ);
732                 $obj_uri  = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($uri);
733                 $obj_uri  = $obj_uri["uri"];
734
735                 $vObject   = dav_get_current_user_calendarobject($server, $calendar, $obj_uri, DAV_ACL_WRITE);
736                 $component = dav_get_eventComponent($vObject);
737
738                 if ($component == null) return array("ok" => false, "msg" => t('Could not open component for editing'));
739         } else {
740                 $calendar  = dav_get_current_user_calendar_by_id($server, $_REQUEST["calendar"], DAV_ACL_WRITE);
741                 $vObject   = dav_create_empty_vevent();
742                 $component = dav_get_eventComponent($vObject);
743                 $obj_uri   = $component->__get("UID");
744         }
745
746         $ts_start = wdcal_set_component_date($component, $localization);
747         wdcal_set_component_recurrence($component, $localization);
748         wdcal_set_component_alerts($component, $localization, icalendar_sanitize_string(dav_compat_parse_text_serverside("summary")), $ts_start);
749
750         $component->__unset("LOCATION");
751         $component->__unset("SUMMARY");
752         $component->__unset("DESCRIPTION");
753         $component->__unset("X-ANIMEXX-COLOR");
754         $component->add("SUMMARY", icalendar_sanitize_string(dav_compat_parse_text_serverside("summary")));
755         $component->add("LOCATION", icalendar_sanitize_string(dav_compat_parse_text_serverside("location")));
756         $component->add("DESCRIPTION", icalendar_sanitize_string(dav_compat_parse_text_serverside("wdcal_desc")));
757         if (isset($_REQUEST["color_override"])) {
758                 $component->add("X-ANIMEXX-COLOR", $_REQUEST["color"]);
759         }
760
761         $data = $vObject->serialize();
762
763         if ($uri == 0) {
764                 $calendar->createFile($obj_uri . ".ics", $data);
765         } else {
766                 $obj = $calendar->getChild($obj_uri);
767                 $obj->put($data);
768         }
769         return array("ok" => false, "msg" => t("Saved"));
770 }
771
772
773 /**
774  * @return string
775  */
776 function wdcal_getEditPage_exception_selector()
777 {
778         header("Content-type: application/json");
779
780         $a            = get_app();
781         $localization = wdcal_local::getInstanceByUser($a->user["uid"]);
782
783         $vObject = dav_create_empty_vevent();
784
785         foreach ($vObject->getComponents() as $component) {
786                 if ($component->name !== 'VTIMEZONE') break;
787         }
788         /** @var Sabre_VObject_Component_VEvent $component */
789         wdcal_set_component_date($component, $localization);
790         wdcal_set_component_recurrence($component, $localization);
791
792
793         $it         = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID"));
794         $max_ts     = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR + 1);
795         $last_start = 0;
796
797         $o = "<ul>";
798
799         $i = 0;
800         while ($it->valid() && $last_start < $max_ts && $i++ < 1000) {
801                 $last_start = $it->getDtStart()->getTimestamp();
802                 $o .= "<li><a href='#' class='exception_selector_link' data-timestamp='$last_start'>" . $localization->date_timestamp2localDate($last_start) . "</a></li>\n";
803                 $it->next();
804         }
805         $o .= "</ul>\n";
806
807         return $o;
808 }