0afc03bd74406087643b92e473bc1221d0bac3dc
[friendica-addons.git] / dav / friendica / dav_caldav_backend_virtual_friendica.inc.php
1 <?php
2
3 class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual
4 {
5
6         /**
7          * @var null|Sabre_CalDAV_Backend_Friendica
8          */
9         private static $instance = null;
10
11         /**
12          * @static
13          * @return Sabre_CalDAV_Backend_Friendica
14          */
15         public static function getInstance()
16         {
17                 if (self::$instance == null) {
18                         self::$instance = new Sabre_CalDAV_Backend_Friendica();
19                 }
20                 return self::$instance;
21         }
22
23         /**
24          * @return int
25          */
26         public function getNamespace()
27         {
28                 return CALDAV_NAMESPACE_PRIVATE;
29         }
30
31         /**
32          * @static
33          * @return string
34          */
35         public static function getBackendTypeName() {
36                 return t("Friendica-Native events");
37         }
38
39         /**
40          * @static
41          * @param int $calendarId
42          * @throws Sabre_DAV_Exception_NotFound
43          * @return void
44          */
45         protected static function createCache_internal($calendarId)
46         {
47                 $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
48
49                 switch ($calendar["uri"]) {
50                         case CALDAV_FRIENDICA_MINE:
51                                 $sql_where = " AND cid = 0";
52                                 break;
53                         case CALDAV_FRIENDICA_CONTACTS:
54                                 $sql_where = " AND cid > 0";
55                                 break;
56                         default:
57                                 throw new Sabre_DAV_Exception_NotFound();
58                 }
59
60                 $r = q("SELECT * FROM `event` WHERE `uid` = %d " . $sql_where . " ORDER BY `start`", IntVal($calendar["namespace_id"]));
61
62                 foreach ($r as $row) {
63                         $uid       = $calendar["uri"] . "-" . $row["id"];
64                         $vevent    = dav_create_empty_vevent($uid);
65                         $component = dav_get_eventComponent($vevent);
66
67                         if ($row["adjust"]) {
68                                 $start  = datetime_convert('UTC', date_default_timezone_get(), $row["start"]);
69                                 $finish = datetime_convert('UTC', date_default_timezone_get(), $row["finish"]);
70                         } else {
71                                 $start  = $row["start"];
72                                 $finish = $row["finish"];
73                         }
74
75                         $summary = ($row["summary"] != "" ? $row["summary"] : $row["desc"]);
76                         $desc    = ($row["summary"] != "" ? $row["desc"] : "");
77                         $component->add("SUMMARY", icalendar_sanitize_string($summary));
78                         $component->add("LOCATION", icalendar_sanitize_string($row["location"]));
79                         $component->add("DESCRIPTION", icalendar_sanitize_string($desc));
80
81                         $ts_start = wdcal_mySql2PhpTime($start);
82                         $ts_end   = wdcal_mySql2PhpTime($start);
83
84                         $allday = (strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false);
85                         $type           = ($allday ? Sabre\VObject\Property\DateTime::DATE : Sabre\VObject\Property\DateTime::LOCALTZ);
86
87                         $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
88                         $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_start)), $type);
89                         $datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
90                         $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_end)), $type);
91
92                         $component->add($datetime_start);
93                         $component->add($datetime_end);
94
95                         $data = $vevent->serialize();
96
97                         q("INSERT INTO %s%scal_virtual_object_cache (`calendar_id`, `data_uri`, `data_summary`, `data_location`, `data_start`, `data_end`, `data_allday`, `data_type`,
98                                 `calendardata`, `size`, `etag`) VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', %d, '%s')",
99                                 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId, dbesc($uid), dbesc($summary), dbesc($row["location"]), dbesc($row["start"]), dbesc($row["finish"]),
100                                         ($allday ? 1 : 0), dbesc(($row["type"] == "birthday" ? "birthday" : "")), dbesc($data), strlen($data), md5($data));
101
102                 }
103
104         }
105
106
107         /**
108          * @param array $row
109          * @param array $calendar
110          * @param string $base_path
111          * @return array
112          */
113         private function jqcal2wdcal($row, $calendar, $base_path)
114         {
115                 if ($row["adjust"]) {
116                         $start  = datetime_convert('UTC', date_default_timezone_get(), $row["start"]);
117                         $finish = datetime_convert('UTC', date_default_timezone_get(), $row["finish"]);
118                 } else {
119                         $start  = $row["start"];
120                         $finish = $row["finish"];
121                 }
122
123                 $allday = (strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false);
124
125                 $summary = (($row["summary"]) ? $row["summary"] : substr(preg_replace("/\[[^\]]*\]/", "", $row["desc"]), 0, 100));
126
127                 return array(
128                         "jq_id"             => $row["id"],
129                         "ev_id"             => $row["id"],
130                         "summary"           => escape_tags($summary),
131                         "start"             => wdcal_mySql2PhpTime($start),
132                         "end"               => wdcal_mySql2PhpTime($finish),
133                         "is_allday"         => ($allday ? 1 : 0),
134                         "is_moredays"       => (substr($start, 0, 10) != substr($finish, 0, 10)),
135                         "is_recurring"      => ($row["type"] == "birthday"),
136                         "color"             => "7878ff",
137                         "is_editable"       => 0,
138                         "is_editable_quick" => 0,
139                         "location"          => $row["location"],
140                         "attendees"         => '',
141                         "has_notification"  => 0,
142                         "url_detail"        => $base_path . "/events/event/" . $row["id"],
143                         "url_edit"          => "",
144                         "special_type"      => ($row["type"] == "birthday" ? "birthday" : ""),
145                 );
146         }
147
148
149         /**
150          * @param int $calendarId
151          * @param string $date_from
152          * @param string $date_to
153          * @param string $base_path
154          * @throws Sabre_DAV_Exception_NotFound
155          * @return array
156          */
157         public function listItemsByRange($calendarId, $date_from, $date_to, $base_path)
158         {
159                 $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
160
161                 if ($calendar["namespace"] != CALDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
162
163                 switch ($calendar["uri"]) {
164                         case CALDAV_FRIENDICA_MINE:
165                                 $sql_where = " AND cid = 0";
166                                 break;
167                         case CALDAV_FRIENDICA_CONTACTS:
168                                 $sql_where = " AND cid > 0";
169                                 break;
170                         default:
171                                 throw new Sabre_DAV_Exception_NotFound();
172                 }
173
174                 if ($date_from != "") {
175                         if (is_numeric($date_from)) $sql_where .= " AND `finish` >= '" . date("Y-m-d H:i:s", $date_from) . "'";
176                         else $sql_where .= " AND `finish` >= '" . dbesc($date_from) . "'";
177                 }
178                 if ($date_to != "") {
179                         if (is_numeric($date_to)) $sql_where .= " AND `start` <= '" . date("Y-m-d H:i:s", $date_to) . "'";
180                         else $sql_where .= " AND `start` <= '" . dbesc($date_to) . "'";
181                 }
182                 $ret = array();
183
184                 $r = q("SELECT * FROM `event` WHERE `uid` = %d " . $sql_where . " ORDER BY `start`", IntVal($calendar["namespace_id"]));
185
186                 $a = get_app();
187                 foreach ($r as $row) {
188                         $r                = $this->jqcal2wdcal($row, $calendar, $a->get_baseurl());
189                         $r["calendar_id"] = $calendar["id"];
190                         $ret[]            = $r;
191                 }
192
193                 return $ret;
194         }
195
196
197         /**
198          * Returns a list of calendars for a principal.
199          *
200          * Every project is an array with the following keys:
201          *  * id, a unique id that will be used by other functions to modify the
202          *    calendar. This can be the same as the uri or a database key.
203          *  * uri, which the basename of the uri with which the calendar is
204          *    accessed.
205          *  * principaluri. The owner of the calendar. Almost always the same as
206          *    principalUri passed to this method.
207          *
208          * Furthermore it can contain webdav properties in clark notation. A very
209          * common one is '{DAV:}displayname'.
210          *
211          * @param string $principalUri
212          * @return array
213          */
214         public function getCalendarsForUser($principalUri)
215         {
216                 $n = dav_compat_principal2namespace($principalUri);
217                 if ($n["namespace"] != $this->getNamespace()) return array();
218
219                 $cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), IntVal($n["namespace_id"]));
220                 $ret  = array();
221                 foreach ($cals as $cal) {
222                         if (!in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue;
223
224                         $dat = array(
225                                 "id"                                                      => $cal["id"],
226                                 "uri"                                                     => $cal["uri"],
227                                 "principaluri"                                            => $principalUri,
228                                 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
229                                 '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array("VEVENT")),
230                                 "calendar_class"                                          => "Sabre_CalDAV_Calendar_Virtual",
231                         );
232                         foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
233
234                         $ret[] = $dat;
235                 }
236
237                 return $ret;
238         }
239
240         /**
241          * @param int $calendar_id
242          * @param int $calendarobject_id
243          * @return string
244          */
245         function getItemDetailRedirect($calendar_id, $calendarobject_id)
246         {
247                 $a    = get_app();
248                 $item = q("SELECT `id` FROM `item` WHERE `event-id` = %d AND `uid` = %d AND deleted = 0", IntVal($calendarobject_id), $a->user["uid"]);
249                 if (count($item) == 0) return "/events/";
250                 return "/display/" . $a->user["nickname"] . "/" . IntVal($item[0]["id"]);
251
252         }
253 }