]> git.mxchange.org Git - friendica.git/blob - mod/poco.php
More joins replaced by view calls
[friendica.git] / mod / poco.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * @see https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
21  */
22
23 use Friendica\App;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Protocol\PortableContact;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
33 use Friendica\Util\XML;
34
35 function poco_init(App $a) {
36         $system_mode = false;
37
38         if (intval(DI::config()->get('system', 'block_public')) || (DI::config()->get('system', 'block_local_dir'))) {
39                 throw new \Friendica\Network\HTTPException\ForbiddenException();
40         }
41
42         if ($a->argc > 1) {
43                 $nickname = Strings::escapeTags(trim($a->argv[1]));
44         }
45         if (empty($nickname)) {
46                 if (!DBA::exists('profile', ['net-publish' => true])) {
47                         throw new \Friendica\Network\HTTPException\ForbiddenException();
48                 }
49                 $system_mode = true;
50         }
51
52         $format = ($_GET['format'] ?? '') ?: 'json';
53
54         $justme = false;
55         $global = false;
56
57         if ($a->argc > 1 && $a->argv[1] === '@server') {
58                 // List of all servers that this server knows
59                 $ret = PortableContact::serverlist();
60                 header('Content-type: application/json');
61                 echo json_encode($ret);
62                 exit();
63         }
64
65         if ($a->argc > 1 && $a->argv[1] === '@global') {
66                 // List of all profiles that this server recently had data from
67                 $global = true;
68                 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
69         }
70         if ($a->argc > 2 && $a->argv[2] === '@me') {
71                 $justme = true;
72         }
73         if ($a->argc > 3 && $a->argv[3] === '@all') {
74                 $justme = false;
75         }
76         if ($a->argc > 3 && $a->argv[3] === '@self') {
77                 $justme = true;
78         }
79         if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
80                 $cid = intval($a->argv[4]);
81         }
82
83         if (!$system_mode && !$global) {
84                 $user = DBA::selectFirst('owner-view', ['uid', 'nickname'], ['nickname' => $nickname, 'hide-friends' => false]);
85                 if (!DBA::isResult($user)) {
86                         throw new \Friendica\Network\HTTPException\NotFoundException();
87                 }
88         }
89
90         if ($justme) {
91                 $sql_extra = " AND `contact`.`self` = 1 ";
92         } else {
93                 $sql_extra = "";
94         }
95
96         if (!empty($cid)) {
97                 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
98         }
99         if (!empty($_GET['updatedSince'])) {
100                 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
101         }
102         if ($global) {
103                 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
104                         DBA::escape($update_limit),
105                         DBA::escape(Protocol::DFRN),
106                         DBA::escape(Protocol::DIASPORA),
107                         DBA::escape(Protocol::OSTATUS)
108                 );
109         } elseif ($system_mode) {
110                 $totalResults = DBA::count('profile', ['net-publish' => true]);
111         } else {
112                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
113                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
114                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
115                         intval($user['uid']),
116                         DBA::escape(Protocol::DFRN),
117                         DBA::escape(Protocol::DIASPORA),
118                         DBA::escape(Protocol::OSTATUS),
119                         DBA::escape(Protocol::STATUSNET)
120                 );
121         }
122         if (empty($totalResults) && DBA::isResult($contacts)) {
123                 $totalResults = intval($contacts[0]['total']);
124         } elseif (empty($totalResults)) {
125                 $totalResults = 0;
126         }
127         if (!empty($_GET['startIndex'])) {
128                 $startIndex = intval($_GET['startIndex']);
129         } else {
130                 $startIndex = 0;
131         }
132         $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
133
134         if ($global) {
135                 Logger::log("Start global query", Logger::DEBUG);
136                 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
137                         ORDER BY `updated` DESC LIMIT %d, %d",
138                         DBA::escape($update_limit),
139                         DBA::escape(Protocol::DFRN),
140                         DBA::escape(Protocol::DIASPORA),
141                         DBA::escape(Protocol::OSTATUS),
142                         intval($startIndex),
143                         intval($itemsPerPage)
144                 );
145         } elseif ($system_mode) {
146                 Logger::log("Start system mode query", Logger::DEBUG);
147                 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
148                                 `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
149                                 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
150                         FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
151                                 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
152                         WHERE `self` = 1 AND `profile`.`net-publish`
153                         LIMIT %d, %d",
154                         intval($startIndex),
155                         intval($itemsPerPage)
156                 );
157         } else {
158                 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
159                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
160                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
161                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
162                         intval($user['uid']),
163                         DBA::escape(Protocol::DFRN),
164                         DBA::escape(Protocol::DIASPORA),
165                         DBA::escape(Protocol::OSTATUS),
166                         DBA::escape(Protocol::STATUSNET),
167                         intval($startIndex),
168                         intval($itemsPerPage)
169                 );
170         }
171         Logger::log("Query done", Logger::DEBUG);
172
173         $ret = [];
174         if (!empty($_GET['sorted'])) {
175                 $ret['sorted'] = false;
176         }
177         if (!empty($_GET['filtered'])) {
178                 $ret['filtered'] = false;
179         }
180         if (!empty($_GET['updatedSince']) && ! $global) {
181                 $ret['updatedSince'] = false;
182         }
183         $ret['startIndex']   = (int) $startIndex;
184         $ret['itemsPerPage'] = (int) $itemsPerPage;
185         $ret['totalResults'] = (int) $totalResults;
186         $ret['entry']        = [];
187
188
189         $fields_ret = [
190                 'id' => false,
191                 'displayName' => false,
192                 'urls' => false,
193                 'updated' => false,
194                 'preferredUsername' => false,
195                 'photos' => false,
196                 'aboutMe' => false,
197                 'currentLocation' => false,
198                 'network' => false,
199                 'tags' => false,
200                 'address' => false,
201                 'contactType' => false,
202                 'generation' => false
203         ];
204
205         if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
206                 foreach ($fields_ret as $k => $v) {
207                         $fields_ret[$k] = true;
208                 }
209         } else {
210                 $fields_req = explode(',', $_GET['fields']);
211                 foreach ($fields_req as $f) {
212                         $fields_ret[trim($f)] = true;
213                 }
214         }
215
216         if (is_array($contacts)) {
217                 if (DBA::isResult($contacts)) {
218                         foreach ($contacts as $contact) {
219                                 if (!isset($contact['updated'])) {
220                                         $contact['updated'] = '';
221                                 }
222
223                                 if (! isset($contact['generation'])) {
224                                         if ($global) {
225                                                 $contact['generation'] = 3;
226                                         } elseif ($system_mode) {
227                                                 $contact['generation'] = 1;
228                                         } else {
229                                                 $contact['generation'] = 2;
230                                         }
231                                 }
232
233                                 if (($contact['about'] == "") && isset($contact['pabout'])) {
234                                         $contact['about'] = $contact['pabout'];
235                                 }
236                                 if ($contact['location'] == "") {
237                                         if (isset($contact['plocation'])) {
238                                                 $contact['location'] = $contact['plocation'];
239                                         }
240                                         if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
241                                                 if ($contact['location'] != "") {
242                                                         $contact['location'] .= ", ";
243                                                 }
244                                                 $contact['location'] .= $contact['pregion'];
245                                         }
246
247                                         if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
248                                                 if ($contact['location'] != "") {
249                                                         $contact['location'] .= ", ";
250                                                 }
251                                                 $contact['location'] .= $contact['pcountry'];
252                                         }
253                                 }
254
255                                 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
256                                         $contact['keywords'] = $contact['pub_keywords'];
257                                 }
258                                 if (isset($contact['account-type'])) {
259                                         $contact['contact-type'] = $contact['account-type'];
260                                 }
261                                 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
262                                 if (is_null($about)) {
263                                         $about = BBCode::convert($contact['about'], false);
264                                         DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
265                                 }
266
267                                 // Non connected persons can only see the keywords of a Diaspora account
268                                 if ($contact['network'] == Protocol::DIASPORA) {
269                                         $contact['location'] = "";
270                                         $about = "";
271                                 }
272
273                                 $entry = [];
274                                 if ($fields_ret['id']) {
275                                         $entry['id'] = (int)$contact['id'];
276                                 }
277                                 if ($fields_ret['displayName']) {
278                                         $entry['displayName'] = $contact['name'];
279                                 }
280                                 if ($fields_ret['aboutMe']) {
281                                         $entry['aboutMe'] = $about;
282                                 }
283                                 if ($fields_ret['currentLocation']) {
284                                         $entry['currentLocation'] = $contact['location'];
285                                 }
286                                 if ($fields_ret['generation']) {
287                                         $entry['generation'] = (int)$contact['generation'];
288                                 }
289                                 if ($fields_ret['urls']) {
290                                         $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
291                                         if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
292                                                 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
293                                         }
294                                 }
295                                 if ($fields_ret['preferredUsername']) {
296                                         $entry['preferredUsername'] = $contact['nick'];
297                                 }
298                                 if ($fields_ret['updated']) {
299                                         if (! $global) {
300                                                 $entry['updated'] = $contact['success_update'];
301
302                                                 if ($contact['name-date'] > $entry['updated']) {
303                                                         $entry['updated'] = $contact['name-date'];
304                                                 }
305                                                 if ($contact['uri-date'] > $entry['updated']) {
306                                                         $entry['updated'] = $contact['uri-date'];
307                                                 }
308                                                 if ($contact['avatar-date'] > $entry['updated']) {
309                                                         $entry['updated'] = $contact['avatar-date'];
310                                                 }
311                                         } else {
312                                                 $entry['updated'] = $contact['updated'];
313                                         }
314                                         $entry['updated'] = date("c", strtotime($entry['updated']));
315                                 }
316                                 if ($fields_ret['photos']) {
317                                         $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
318                                 }
319                                 if ($fields_ret['network']) {
320                                         $entry['network'] = $contact['network'];
321                                         if ($entry['network'] == Protocol::STATUSNET) {
322                                                 $entry['network'] = Protocol::OSTATUS;
323                                         }
324                                         if (($entry['network'] == "") && ($contact['self'])) {
325                                                 $entry['network'] = Protocol::DFRN;
326                                         }
327                                 }
328                                 if ($fields_ret['tags']) {
329                                         $tags = str_replace(",", " ", $contact['keywords']);
330                                         $tags = explode(" ", $tags);
331
332                                         $cleaned = [];
333                                         foreach ($tags as $tag) {
334                                                 $tag = trim(strtolower($tag));
335                                                 if ($tag != "") {
336                                                         $cleaned[] = $tag;
337                                                 }
338                                         }
339
340                                         $entry['tags'] = [$cleaned];
341                                 }
342                                 if ($fields_ret['address']) {
343                                         $entry['address'] = [];
344
345                                         // Deactivated. It just reveals too much data. (Although its from the default profile)
346                                         //if (isset($rr['paddress']))
347                                         //       $entry['address']['streetAddress'] = $rr['paddress'];
348
349                                         if (isset($contact['plocation'])) {
350                                                 $entry['address']['locality'] = $contact['plocation'];
351                                         }
352                                         if (isset($contact['pregion'])) {
353                                                 $entry['address']['region'] = $contact['pregion'];
354                                         }
355                                         // See above
356                                         //if (isset($rr['ppostalcode']))
357                                         //       $entry['address']['postalCode'] = $rr['ppostalcode'];
358
359                                         if (isset($contact['pcountry'])) {
360                                                 $entry['address']['country'] = $contact['pcountry'];
361                                         }
362                                 }
363
364                                 if ($fields_ret['contactType']) {
365                                         $entry['contactType'] = intval($contact['contact-type']);
366                                 }
367                                 $ret['entry'][] = $entry;
368                         }
369                 } else {
370                         $ret['entry'][] = [];
371                 }
372         } else {
373                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
374         }
375
376         Logger::log("End of poco", Logger::DEBUG);
377
378         if ($format === 'xml') {
379                 header('Content-type: text/xml');
380                 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
381                 exit();
382         }
383         if ($format === 'json') {
384                 header('Content-type: application/json');
385                 echo json_encode($ret);
386                 exit();
387         } else {
388                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
389         }
390 }