8d51022d267394a95d2064bc0a891d31c3ca006d
[friendica-addons.git] / dav / friendica / dav_carddav_backend_virtual_friendica.inc.php
1 <?php
2
3 class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual
4 {
5
6         /**
7          * @var null|Sabre_CardDAV_Backend_Friendica
8          */
9         private static $instance = null;
10
11         /**
12          * @static
13          * @return Sabre_CardDAV_Backend_Friendica
14          */
15         public static function getInstance() {
16                 if (self::$instance == null) {
17                         self::$instance = new Sabre_CardDAV_Backend_Friendica();
18                 }
19                 return self::$instance;
20         }
21
22
23         /**
24          * @return int
25          */
26         public function getNamespace()
27         {
28                 return CARDDAV_NAMESPACE_PRIVATE;
29         }
30
31         /**
32          * @static
33          * @return string
34          */
35         public static function getBackendTypeName() {
36                 return t("Friendica-Contacts");
37         }
38
39         /**
40          * Returns the list of addressbooks for a specific user.
41          *
42          * @param string $principalUri
43          * @return array
44          */
45         public function getAddressBooksForUser($principalUri)
46         {
47                 $uid = dav_compat_principal2uid($principalUri);
48
49                 $addressBooks = [];
50
51                 $books = q("SELECT id, ctag FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
52                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($uid), dbesc(CARDDAV_FRIENDICA_CONTACT));
53                 $ctag = $books[0]["ctag"];
54
55                 $addressBooks[] = [
56                         'id'                                                                => $books[0]["id"],
57                         'uri'                                                               => "friendica",
58                         'principaluri'                                                      => $principalUri,
59                         '{DAV:}displayname'                                                 => t("Friendica-Contacts"),
60                         '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => t("Your Friendica-Contacts"),
61                         '{http://calendarserver.org/ns/}getctag'                            => $ctag,
62                         '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data'  =>
63                         new Sabre_CardDAV_Property_SupportedAddressData(),
64                 ];
65
66                 return $addressBooks;
67
68         }
69
70         /**
71          * @static
72          * @param array $contact
73          * @return array
74          */
75         private static function dav_contactarr2vcardsource($contact)
76         {
77                 $name        = explode(" ", $contact["name"]);
78                 $first_name  = $last_name = "";
79                 $middle_name = [];
80                 $num         = count($name);
81                 for ($i = 0; $i < $num && $first_name == ""; $i++) if ($name[$i] != "") {
82                         $first_name = $name[$i];
83                         unset($name[$i]);
84                 }
85                 for ($i = $num - 1; $i >= 0 && $last_name == ""; $i--) if (isset($name[$i]) && $name[$i] != "") {
86                         $last_name = $name[$i];
87                         unset($name[$i]);
88                 }
89                 foreach ($name as $n) if ($n != "") $middle_name[] = $n;
90                 $vcarddata              = new vcard_source_data($first_name, implode(" ", $middle_name), $last_name);
91                 $vcarddata->homepages[] = new vcard_source_data_homepage("pref", $contact["url"]);
92                 $vcarddata->last_update = ($contact["last-update"] > 0 ? $contact["last-update"] : $contact["created"]);
93
94                 $photo = q("SELECT * FROM photo WHERE `contact-id` = %d ORDER BY scale DESC", $contact["id"]); //prefer size 80x80
95                 if ($photo && count($photo) > 0) {
96                         $photodata             = new vcard_source_data_photo();
97                         $photodata->width      = $photo[0]["width"];
98                         $photodata->height     = $photo[0]["height"];
99                         $photodata->type       = "JPEG";
100                         $photodata->binarydata = $photo[0]["data"];
101                         $vcarddata->photo      = $photodata;
102                 }
103
104                 switch ($contact["network"]) {
105                         case "face":
106                                 $vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("facebook", $contact["notify"], "http://www.facebook.com/" . $contact["notify"]);
107                                 break;
108                         case "dfrn":
109                                 $vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("dfrn", $contact["nick"], $contact["url"]);
110                                 break;
111                         case "twitter":
112                                 $vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("twitter", $contact["nick"], "http://twitter.com/" . $contact["nick"]); // @TODO Stimmt das?
113                                 break;
114                 }
115
116                 $vcard = vcard_source_compile($vcarddata);
117                 return [
118                         "id"           => $contact["id"],
119                         "carddata"     => $vcard,
120                         "uri"          => $contact["id"] . ".vcf",
121                         "lastmodified" => wdcal_mySql2PhpTime($vcarddata->last_update),
122                         "etag"         => md5($vcard),
123                         "size"         => strlen($vcard),
124                 ];
125
126         }
127
128         /**
129          * @static
130          * @param int $addressbookId
131          * @param bool $force
132          * @throws Sabre_DAV_Exception_NotFound
133          */
134         static protected function createCache_internal($addressbookId, $force = false) {
135                 //$notin    = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
136                 $addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
137                 if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
138                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY `name` ASC", $addressbook[0]["namespace_id"]);
139
140                 foreach ($contacts as $contact) {
141                         $x            = static::dav_contactarr2vcardsource($contact);
142                         q("INSERT INTO %s%saddressbookobjects (`addressbook_id`, `contact`, `carddata`, `uri`, `lastmodified`, `etag`, `size`) VALUES (%d, %d, '%s', '%s', NOW(), '%s', %d)",
143                                 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId, $contact["id"], dbesc($x["carddata"]), dbesc($x["uri"]), dbesc($x["etag"]), $x["size"]
144                         );
145                 }
146         }
147
148
149         /**
150          * @static
151          * @param int $addressbookId
152          * @param int $contactId
153          * @param bool $force
154          * @throws Sabre_DAV_Exception_NotFound
155          */
156         static protected function createCardCache($addressbookId, $contactId, $force = false)
157         {
158                 $addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
159                 if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
160
161                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 AND `id` = %d ORDER BY `name` ASC",
162                         $addressbook[0]["namespace_id"], IntVal($contactId));
163                 $contact = $contacts[0];
164
165                 $x            = static::dav_contactarr2vcardsource($contact);
166                 q("INSERT INTO %s%saddressbookobjects (`addressbook_id`, `contact`, `carddata`, `uri`, `lastmodified`, `etag`, `size`) VALUES (%d, %d, '%s', '%s', NOW(), '%s', %d)",
167                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId, $contact["id"], dbesc($x["carddata"]), dbesc($x["uri"]), dbesc($x["etag"]), $x["size"]
168                 );
169         }
170         /**
171          * Updates a card.
172          *
173          * The addressbook id will be passed as the first argument. This is the
174          * same id as it is returned from the getAddressbooksForUser method.
175          *
176          * The cardUri is a base uri, and doesn't include the full path. The
177          * cardData argument is the vcard body, and is passed as a string.
178          *
179          * It is possible to return an ETag from this method. This ETag should
180          * match that of the updated resource, and must be enclosed with double
181          * quotes (that is: the string itself must contain the actual quotes).
182          *
183          * You should only return the ETag if you store the carddata as-is. If a
184          * subsequent GET request on the same card does not have the same body,
185          * byte-by-byte and you did return an ETag here, clients tend to get
186          * confused.
187          *
188          * If you don't return an ETag, you can just return null.
189          *
190          * @param string $addressBookId
191          * @param string $cardUri
192          * @param string $cardData
193          * @throws Sabre_DAV_Exception_Forbidden
194          * @return string|null
195          */
196         public function updateCard($addressBookId, $cardUri, $cardData)
197         {
198                 $x = explode("-", $addressBookId);
199
200                 $etag = md5($cardData);
201                 q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
202                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
203                 );
204                 q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
205
206                 return '"' . $etag . '"';
207         }
208
209         /**
210          * Deletes a card
211          *
212          * @param string $addressBookId
213          * @param string $cardUri
214          * @throws Sabre_DAV_Exception_Forbidden
215          * @return bool
216          */
217         public function deleteCard($addressBookId, $cardUri)
218         {
219                 $x = explode("-", $addressBookId);
220
221                 q("UPDATE %s%scards SET manually_deleted = 1 WHERE namespace = %d AND namespace_id = %d AND uri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
222                 q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
223
224                 return true;
225         }
226
227 }