]> git.mxchange.org Git - friendica-addons.git/blob - dav/dav_carddav_backend_virtual_friendica.inc.php
More refactoring, mainly of the addressbook/VCARD-part
[friendica-addons.git] / dav / 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 = array();
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[] = array(
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 = array();
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 array(
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          * @throws Sabre_DAV_Exception_NotFound
132          */
133         static protected function createCache_internal($addressbookId) {
134                 //$notin    = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
135                 $addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
136                 if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
137                 $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"]);
138
139                 $retdata = array();
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          * Updates a card.
151          *
152          * The addressbook id will be passed as the first argument. This is the
153          * same id as it is returned from the getAddressbooksForUser method.
154          *
155          * The cardUri is a base uri, and doesn't include the full path. The
156          * cardData argument is the vcard body, and is passed as a string.
157          *
158          * It is possible to return an ETag from this method. This ETag should
159          * match that of the updated resource, and must be enclosed with double
160          * quotes (that is: the string itself must contain the actual quotes).
161          *
162          * You should only return the ETag if you store the carddata as-is. If a
163          * subsequent GET request on the same card does not have the same body,
164          * byte-by-byte and you did return an ETag here, clients tend to get
165          * confused.
166          *
167          * If you don't return an ETag, you can just return null.
168          *
169          * @param string $addressBookId
170          * @param string $cardUri
171          * @param string $cardData
172          * @throws Sabre_DAV_Exception_Forbidden
173          * @return string|null
174          */
175         public function updateCard($addressBookId, $cardUri, $cardData)
176         {
177                 $x = explode("-", $addressBookId);
178
179                 $etag = md5($cardData);
180                 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",
181                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
182                 );
183                 q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
184
185                 return '"' . $etag . '"';
186         }
187
188         /**
189          * Deletes a card
190          *
191          * @param string $addressBookId
192          * @param string $cardUri
193          * @throws Sabre_DAV_Exception_Forbidden
194          * @return bool
195          */
196         public function deleteCard($addressBookId, $cardUri)
197         {
198                 $x = explode("-", $addressBookId);
199
200                 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));
201                 q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
202
203                 return true;
204         }
205 }