]> git.mxchange.org Git - friendica.git/blob - mod/poco.php
Merge pull request #8297 from MrPetovan/task/8285-api-events
[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                 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
47                 if (!DBA::isResult($c)) {
48                         throw new \Friendica\Network\HTTPException\ForbiddenException();
49                 }
50                 $system_mode = true;
51         }
52
53         $format = ($_GET['format'] ?? '') ?: 'json';
54
55         $justme = false;
56         $global = false;
57
58         if ($a->argc > 1 && $a->argv[1] === '@server') {
59                 // List of all servers that this server knows
60                 $ret = PortableContact::serverlist();
61                 header('Content-type: application/json');
62                 echo json_encode($ret);
63                 exit();
64         }
65
66         if ($a->argc > 1 && $a->argv[1] === '@global') {
67                 // List of all profiles that this server recently had data from
68                 $global = true;
69                 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
70         }
71         if ($a->argc > 2 && $a->argv[2] === '@me') {
72                 $justme = true;
73         }
74         if ($a->argc > 3 && $a->argv[3] === '@all') {
75                 $justme = false;
76         }
77         if ($a->argc > 3 && $a->argv[3] === '@self') {
78                 $justme = true;
79         }
80         if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
81                 $cid = intval($a->argv[4]);
82         }
83
84         if (! $system_mode && ! $global) {
85                 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
86                         where `user`.`nickname` = '%s' limit 1",
87                         DBA::escape($nickname)
88                 );
89                 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
90                         throw new \Friendica\Network\HTTPException\NotFoundException();
91                 }
92
93                 $user = $users[0];
94         }
95
96         if ($justme) {
97                 $sql_extra = " AND `contact`.`self` = 1 ";
98         } else {
99                 $sql_extra = "";
100         }
101
102         if (!empty($cid)) {
103                 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
104         }
105         if (!empty($_GET['updatedSince'])) {
106                 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
107         }
108         if ($global) {
109                 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
110                         DBA::escape($update_limit),
111                         DBA::escape(Protocol::DFRN),
112                         DBA::escape(Protocol::DIASPORA),
113                         DBA::escape(Protocol::OSTATUS)
114                 );
115         } elseif ($system_mode) {
116                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
117                         AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
118         } else {
119                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
120                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
121                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
122                         intval($user['uid']),
123                         DBA::escape(Protocol::DFRN),
124                         DBA::escape(Protocol::DIASPORA),
125                         DBA::escape(Protocol::OSTATUS),
126                         DBA::escape(Protocol::STATUSNET)
127                 );
128         }
129         if (DBA::isResult($contacts)) {
130                 $totalResults = intval($contacts[0]['total']);
131         } else {
132                 $totalResults = 0;
133         }
134         if (!empty($_GET['startIndex'])) {
135                 $startIndex = intval($_GET['startIndex']);
136         } else {
137                 $startIndex = 0;
138         }
139         $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
140
141         if ($global) {
142                 Logger::log("Start global query", Logger::DEBUG);
143                 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
144                         ORDER BY `updated` DESC LIMIT %d, %d",
145                         DBA::escape($update_limit),
146                         DBA::escape(Protocol::DFRN),
147                         DBA::escape(Protocol::DIASPORA),
148                         DBA::escape(Protocol::OSTATUS),
149                         intval($startIndex),
150                         intval($itemsPerPage)
151                 );
152         } elseif ($system_mode) {
153                 Logger::log("Start system mode query", Logger::DEBUG);
154                 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
155                                 `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
156                                 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
157                         FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
158                                 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
159                         WHERE `self` = 1
160                         AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
161                         intval($startIndex),
162                         intval($itemsPerPage)
163                 );
164         } else {
165                 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
166                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
167                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
168                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
169                         intval($user['uid']),
170                         DBA::escape(Protocol::DFRN),
171                         DBA::escape(Protocol::DIASPORA),
172                         DBA::escape(Protocol::OSTATUS),
173                         DBA::escape(Protocol::STATUSNET),
174                         intval($startIndex),
175                         intval($itemsPerPage)
176                 );
177         }
178         Logger::log("Query done", Logger::DEBUG);
179
180         $ret = [];
181         if (!empty($_GET['sorted'])) {
182                 $ret['sorted'] = false;
183         }
184         if (!empty($_GET['filtered'])) {
185                 $ret['filtered'] = false;
186         }
187         if (!empty($_GET['updatedSince']) && ! $global) {
188                 $ret['updatedSince'] = false;
189         }
190         $ret['startIndex']   = (int) $startIndex;
191         $ret['itemsPerPage'] = (int) $itemsPerPage;
192         $ret['totalResults'] = (int) $totalResults;
193         $ret['entry']        = [];
194
195
196         $fields_ret = [
197                 'id' => false,
198                 'displayName' => false,
199                 'urls' => false,
200                 'updated' => false,
201                 'preferredUsername' => false,
202                 'photos' => false,
203                 'aboutMe' => false,
204                 'currentLocation' => false,
205                 'network' => false,
206                 'tags' => false,
207                 'address' => false,
208                 'contactType' => false,
209                 'generation' => false
210         ];
211
212         if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
213                 foreach ($fields_ret as $k => $v) {
214                         $fields_ret[$k] = true;
215                 }
216         } else {
217                 $fields_req = explode(',', $_GET['fields']);
218                 foreach ($fields_req as $f) {
219                         $fields_ret[trim($f)] = true;
220                 }
221         }
222
223         if (is_array($contacts)) {
224                 if (DBA::isResult($contacts)) {
225                         foreach ($contacts as $contact) {
226                                 if (!isset($contact['updated'])) {
227                                         $contact['updated'] = '';
228                                 }
229
230                                 if (! isset($contact['generation'])) {
231                                         if ($global) {
232                                                 $contact['generation'] = 3;
233                                         } elseif ($system_mode) {
234                                                 $contact['generation'] = 1;
235                                         } else {
236                                                 $contact['generation'] = 2;
237                                         }
238                                 }
239
240                                 if (($contact['about'] == "") && isset($contact['pabout'])) {
241                                         $contact['about'] = $contact['pabout'];
242                                 }
243                                 if ($contact['location'] == "") {
244                                         if (isset($contact['plocation'])) {
245                                                 $contact['location'] = $contact['plocation'];
246                                         }
247                                         if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
248                                                 if ($contact['location'] != "") {
249                                                         $contact['location'] .= ", ";
250                                                 }
251                                                 $contact['location'] .= $contact['pregion'];
252                                         }
253
254                                         if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
255                                                 if ($contact['location'] != "") {
256                                                         $contact['location'] .= ", ";
257                                                 }
258                                                 $contact['location'] .= $contact['pcountry'];
259                                         }
260                                 }
261
262                                 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
263                                         $contact['keywords'] = $contact['pub_keywords'];
264                                 }
265                                 if (isset($contact['account-type'])) {
266                                         $contact['contact-type'] = $contact['account-type'];
267                                 }
268                                 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
269                                 if (is_null($about)) {
270                                         $about = BBCode::convert($contact['about'], false);
271                                         DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
272                                 }
273
274                                 // Non connected persons can only see the keywords of a Diaspora account
275                                 if ($contact['network'] == Protocol::DIASPORA) {
276                                         $contact['location'] = "";
277                                         $about = "";
278                                 }
279
280                                 $entry = [];
281                                 if ($fields_ret['id']) {
282                                         $entry['id'] = (int)$contact['id'];
283                                 }
284                                 if ($fields_ret['displayName']) {
285                                         $entry['displayName'] = $contact['name'];
286                                 }
287                                 if ($fields_ret['aboutMe']) {
288                                         $entry['aboutMe'] = $about;
289                                 }
290                                 if ($fields_ret['currentLocation']) {
291                                         $entry['currentLocation'] = $contact['location'];
292                                 }
293                                 if ($fields_ret['generation']) {
294                                         $entry['generation'] = (int)$contact['generation'];
295                                 }
296                                 if ($fields_ret['urls']) {
297                                         $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
298                                         if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
299                                                 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
300                                         }
301                                 }
302                                 if ($fields_ret['preferredUsername']) {
303                                         $entry['preferredUsername'] = $contact['nick'];
304                                 }
305                                 if ($fields_ret['updated']) {
306                                         if (! $global) {
307                                                 $entry['updated'] = $contact['success_update'];
308
309                                                 if ($contact['name-date'] > $entry['updated']) {
310                                                         $entry['updated'] = $contact['name-date'];
311                                                 }
312                                                 if ($contact['uri-date'] > $entry['updated']) {
313                                                         $entry['updated'] = $contact['uri-date'];
314                                                 }
315                                                 if ($contact['avatar-date'] > $entry['updated']) {
316                                                         $entry['updated'] = $contact['avatar-date'];
317                                                 }
318                                         } else {
319                                                 $entry['updated'] = $contact['updated'];
320                                         }
321                                         $entry['updated'] = date("c", strtotime($entry['updated']));
322                                 }
323                                 if ($fields_ret['photos']) {
324                                         $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
325                                 }
326                                 if ($fields_ret['network']) {
327                                         $entry['network'] = $contact['network'];
328                                         if ($entry['network'] == Protocol::STATUSNET) {
329                                                 $entry['network'] = Protocol::OSTATUS;
330                                         }
331                                         if (($entry['network'] == "") && ($contact['self'])) {
332                                                 $entry['network'] = Protocol::DFRN;
333                                         }
334                                 }
335                                 if ($fields_ret['tags']) {
336                                         $tags = str_replace(",", " ", $contact['keywords']);
337                                         $tags = explode(" ", $tags);
338
339                                         $cleaned = [];
340                                         foreach ($tags as $tag) {
341                                                 $tag = trim(strtolower($tag));
342                                                 if ($tag != "") {
343                                                         $cleaned[] = $tag;
344                                                 }
345                                         }
346
347                                         $entry['tags'] = [$cleaned];
348                                 }
349                                 if ($fields_ret['address']) {
350                                         $entry['address'] = [];
351
352                                         // Deactivated. It just reveals too much data. (Although its from the default profile)
353                                         //if (isset($rr['paddress']))
354                                         //       $entry['address']['streetAddress'] = $rr['paddress'];
355
356                                         if (isset($contact['plocation'])) {
357                                                 $entry['address']['locality'] = $contact['plocation'];
358                                         }
359                                         if (isset($contact['pregion'])) {
360                                                 $entry['address']['region'] = $contact['pregion'];
361                                         }
362                                         // See above
363                                         //if (isset($rr['ppostalcode']))
364                                         //       $entry['address']['postalCode'] = $rr['ppostalcode'];
365
366                                         if (isset($contact['pcountry'])) {
367                                                 $entry['address']['country'] = $contact['pcountry'];
368                                         }
369                                 }
370
371                                 if ($fields_ret['contactType']) {
372                                         $entry['contactType'] = intval($contact['contact-type']);
373                                 }
374                                 $ret['entry'][] = $entry;
375                         }
376                 } else {
377                         $ret['entry'][] = [];
378                 }
379         } else {
380                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
381         }
382
383         Logger::log("End of poco", Logger::DEBUG);
384
385         if ($format === 'xml') {
386                 header('Content-type: text/xml');
387                 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
388                 exit();
389         }
390         if ($format === 'json') {
391                 header('Content-type: application/json');
392                 echo json_encode($ret);
393                 exit();
394         } else {
395                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
396         }
397 }