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